> ## 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.

# See How TabPFN Learns: Pretraining in 2D

> Pretrain a tiny TabPFN-style model on simple 2D tables with line and sine-wave boundaries, watch its predictions sharpen, and compare it with logistic regression and random forest.

By
Frank Hutter

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

*Pretrain a tiny model in seconds and watch it learn decision boundaries it has never seen.*

This cookbook is fully self-contained and made for teaching: it builds a tiny tabular foundation model, using the TabPFN-2-style architecture of nanoTabPFN and simpler synthetic pretraining data.

Here we implement this whole pretraining pipeline, in three parts:

1. The **prior** – code for sampling new classification datasets every time it is called.
2. The **model** – a transformer-like architecture that attends across the rows and the columns of a table.
3. The **training loop** – learn to predict the label of new rows based on labeled rows.

The model and training loop are further simplified from **nanoTabPFN** ([github.com/automl/nanotabpfn](https://github.com/automl/nanotabpfn)), a minimal re-implementation of the TabPFN v2 architecture.

# Let's pretrain a tiny TabPFN together!

## 0. Setup

Everything runs on plain PyTorch. A GPU (or Apple Silicon) makes pretraining faster, but a CPU works too. In Colab, pick a GPU runtime under *Runtime → Change runtime type*.

```python theme={null}
import importlib.util

required = ("torch", "numpy", "sklearn", "matplotlib")
if not all(importlib.util.find_spec(package) for package in required):
    %pip install -q torch numpy scikit-learn matplotlib
```

```python theme={null}
import time
import torch
import torch.nn.functional as F
from torch import nn

torch.manual_seed(42)
```

```console theme={null}
<torch._C.Generator at 0x10cb1b850>
```

### Plotting and evaluation helpers

These helpers pick the device, define three fixed test datasets that the model never sees in pretraining (a **line**, a slow **sine wave** and a **sine + fast wave** boundary, each with 40 labeled and 200 hold-out points), and plot and score predictions. They are not part of TabPFN itself, so feel free to skip ahead.

```python theme={null}
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression

device = ("cuda" if torch.cuda.is_available()
          else "mps" if torch.backends.mps.is_available() else "cpu")
print("device:", device)

# Three fixed test datasets, never seen in pretraining: 40 labeled + 200 hold-out points each.
TEST_BOUNDARIES = {
    "line": lambda t: 0.2 - 0.3 * t,
    "sine wave": lambda t: 1.0 + 0.5 * t + 1.5 * torch.sin(1.5 * t),
    "sine + fast wave": lambda t: -0.5 + 0.5 * t + 1.2 * torch.sin(4 * t),
}


def make_test_set(boundary, n_train=40, n_test=200, seed=0):
    gen = torch.Generator().manual_seed(seed)
    x1 = 4 * torch.rand(n_train + n_test, generator=gen) - 2  # x1 ~ U(-2, 2)
    x2 = boundary(x1) + torch.randn(n_train + n_test, generator=gen)
    x, y = torch.stack([x1, x2], dim=-1), (x2 > boundary(x1)).float()
    return x[:n_train], y[:n_train], x[n_train:], y[n_train:]


TEST_SETS = {name: make_test_set(f, seed=i)
             for i, (name, f) in enumerate(TEST_BOUNDARIES.items())}


@torch.no_grad()
def predict_proba(model, x_train, y_train, x_test):
    '''P(class 1) for every test row, from a single forward pass.'''
    logits = model(x_train[None].to(device), y_train[None].to(device),
                   x_test[None].to(device))
    return logits.softmax(-1)[0, :, 1].cpu()


def accuracies(model):
    return {name: ((predict_proba(model, xtr, ytr, xte) > 0.5).float() == yte)
            .float().mean().item() for name, (xtr, ytr, xte, yte) in TEST_SETS.items()}


def evaluate_model(model):
    '''Mean hold-out accuracy over the three test datasets.'''
    return float(np.mean(list(accuracies(model).values())))


def _scatter(ax, x, y, size=30):
    ax.scatter(*x[y == 1].T, c="red", edgecolors="white", s=size, label="class 1")
    ax.scatter(*x[y == 0].T, c="blue", marker="x", s=size, label="class 0")


def plot_prior_samples(x, y, boundary):
    '''One panel per synthetic table, with its true boundary dashed.'''
    n = len(x)
    lo, hi = x[..., 0].min(1).values[:, None], x[..., 0].max(1).values[:, None]
    t = lo + (hi - lo) * torch.linspace(0, 1, 200)  # per-table x1 range
    curves = boundary(t)
    fig, axes = plt.subplots(1, n, figsize=(3.2 * n, 3.4))
    for i, ax in enumerate(np.atleast_1d(axes)):
        _scatter(ax, x[i], y[i], size=12)
        ax.plot(t[i], curves[i], "k--", lw=1)
        ax.set_ylim(x[i, :, 1].min() - 0.3, x[i, :, 1].max() + 0.3)
        ax.set_title(f"table {i}", fontsize=10)
        ax.set_xticks([]); ax.set_yticks([])
    fig.suptitle("Synthetic tables sampled from the prior "
                 "(x1 vs x2, colored by class, dashed: boundary)")
    plt.tight_layout(); plt.show()


def plot_predictions(model):
    '''Predicted P(class 1) over the plane for each test dataset.'''
    levels = [0, 0.1, 0.25, 0.4, 0.6, 0.75, 0.9, 1]
    fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
    for ax, (name, (xtr, ytr, xte, yte)) in zip(axes, TEST_SETS.items()):
        x_all = torch.cat([xtr, xte])
        g1, g2 = torch.meshgrid(
            torch.linspace(-2, 2, 150),
            torch.linspace(x_all[:, 1].min() - 0.5, x_all[:, 1].max() + 0.5, 150),
            indexing="xy")
        grid = torch.stack([g1.ravel(), g2.ravel()], dim=-1)
        p = predict_proba(model, xtr, ytr, grid).reshape(g1.shape)
        cs = ax.contourf(g1, g2, p, levels=levels, cmap="RdBu_r", alpha=0.8)
        t = torch.linspace(-2, 2, 200)
        ax.plot(t, TEST_BOUNDARIES[name](t), "k--", lw=1, label="true boundary")
        _scatter(ax, xtr, ytr)
        ax.set_xlim(-2, 2); ax.set_ylim(g2.min(), g2.max())
        ax.set_title(name); ax.set_xlabel("x1")
    axes[0].set_ylabel("x2")
    axes[0].legend(loc="lower right", fontsize=8)
    fig.colorbar(cs, ax=axes, label="P(class 1)")
    fig.suptitle(f"nanoTabPFN predicted class probabilities (white = unsure), "
                 f"with the {len(xtr)} labeled points as context")
    plt.show()


def compare_with_baseline(models):
    '''Hold-out accuracy table: our models vs. two classic baselines.'''
    rows = {name: accuracies(m) for name, m in models.items()}
    for name, clf in [("logistic regression", LogisticRegression()),
                      ("random forest", RandomForestClassifier(random_state=0))]:
        rows[name] = {ds: clf.fit(xtr.numpy(), ytr.numpy()).score(xte.numpy(), yte.numpy())
                      for ds, (xtr, ytr, xte, yte) in TEST_SETS.items()}
    cols = list(TEST_SETS) + ["mean"]
    print(f"{'accuracy':<20}" + "".join(f"{c:>{len(c) + 3}}" for c in cols))
    print("-" * (20 + sum(len(c) + 3 for c in cols)))
    for name, acc in rows.items():
        vals = list(acc.values()) + [np.mean(list(acc.values()))]
        print(f"{name:<20}" + "".join(f"{v:>{len(c) + 3}.3f}" for c, v in zip(cols, vals)))
```

```console theme={null}
device: mps
```

## 1. The prior: generating the datasets to pretrain on

We sample synthetic tables with 50 rows each, split randomly into train and test rows. We start simple: a random boundary line $f(x_1) = a + b x_1$ with
$a, b \sim \mathcal{N}(0, 1)$. We use $x_1 \sim \mathcal{N}(0, 1)$ and $x_2 \sim f(x_1) + \mathcal{N}(0, 1)$; the label
is 1 if the point lies above the line and 0 below it, with a little noise near the boundary.

```python theme={null}
def sample_from_prior(batch_size, num_rows=50, noise_std=0.1):
    '''A batch of synthetic tables with two features x1 and x2:
    class 1 above a random boundary line, class 0 below it.'''
    # boundary x2 = a + b*x1, one per table
    a = torch.randn(batch_size, 1)  # intercept ~ N(0, 1)
    b = torch.randn(batch_size, 1)  # slope ~ N(0, 1)
    boundary = lambda t: a + b * t
    # points scattered around the boundary
    x1 = torch.randn(batch_size, num_rows)
    x2 = boundary(x1) + torch.randn(batch_size, num_rows)
    # class 1 above the boundary, class 0 below (slightly noisy)
    noise = noise_std * torch.randn(batch_size, num_rows)
    y = (x2 + noise > boundary(x1)).float()
    # the first n_train rows are labeled, the model predicts the rest
    n_train = torch.randint(10, num_rows - 2, ()).item()
    # the boundary is returned only for plotting
    return torch.stack([x1, x2], dim=-1), y, n_train, boundary
```

```python theme={null}
x, y, n_train, boundary = sample_from_prior(4)
plot_prior_samples(x, y, boundary)
```

![1. The prior: generating the datasets to pretrain on](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/pretrain_nanotabpfn_teaching/plot-01.png)

## 2. The model: a transformer over table cells

Every cell of the table becomes a vector, so a batch of tables is a tensor of shape `(batch, rows, columns, embedding)`.
The label is appended as one more column: classes 0 and 1 enter the model as $-1$ and $+1$, so that 0 can mean "unknown" for the rows we want to predict.

Each layer applies attention in **two directions**:

* **between features** – within a row, cells attend to each other,
* **between datapoints** – within a column, every row attends to the **labeled** rows.

The output for each test row is two logits, one per class. Their softmax is the predicted probability of each class, to quantify model uncertainty.

```python theme={null}
class TransformerLayer(nn.Module):
    '''Attention between features (within a row), attention between
    datapoints (within a column), then an MLP.'''

    def __init__(self, emb, heads):
        super().__init__()
        self.attn_features = nn.MultiheadAttention(
            emb, heads, batch_first=True)
        self.attn_datapoints = nn.MultiheadAttention(
            emb, heads, batch_first=True)
        self.mlp = nn.Sequential(
            nn.Linear(emb, 4 * emb), nn.GELU(), nn.Linear(4 * emb, emb))
        self.norm1 = nn.LayerNorm(emb)
        self.norm2 = nn.LayerNorm(emb)
        self.norm3 = nn.LayerNorm(emb)

    def forward(self, h, n_train):
        B, R, C, E = h.shape  # (batch, rows, columns, embedding)
        # self-attention over the features of each row:
        # fold the row dimension into the batch dimension
        h = h.reshape(B * R, C, E)
        h = self.norm1(h + self.attn_features(h, h, h)[0])
        h = h.reshape(B, R, C, E)
        # attention over the rows of each column:
        # fold the column dimension into the batch dimension;
        # all rows attend to the labeled rows only
        h = h.transpose(1, 2).reshape(B * C, R, E)
        labeled = h[:, :n_train]
        h = self.norm2(h + self.attn_datapoints(h, labeled, labeled)[0])
        h = h.reshape(B, C, R, E).transpose(1, 2)
        return self.norm3(h + self.mlp(h))
```

```python theme={null}
class NanoTabPFN(nn.Module):
    def __init__(self, emb, layers, heads=4, num_classes=2):
        super().__init__()
        self.x_encoder = nn.Linear(1, emb)  # embeds each feature cell
        self.y_encoder = nn.Linear(1, emb)  # embeds each label cell
        self.layers = nn.ModuleList(
            [TransformerLayer(emb, heads) for _ in range(layers)])
        self.decoder = nn.Sequential(
            nn.Linear(emb, 4 * emb), nn.GELU(),
            nn.Linear(4 * emb, num_classes))

    def forward(self, x_train, y_train, x_test):
        # x_train: (B, n_train, features), y_train: (B, n_train),
        # x_test: (B, n_test, features)
        n_train = x_train.shape[1]
        # standardize each feature using the labeled rows
        mean = x_train.mean(1, keepdim=True)
        std = x_train.std(1, keepdim=True)
        x = torch.cat([x_train, x_test], dim=1)  # (B, rows, features)
        x = (x - mean) / (std + 1e-8)
        # classes 0 / 1 enter as -1 / +1; unknown test labels as 0
        y = F.pad(2 * y_train - 1, (0, x_test.shape[1]))
        # embed every cell (one number) as a vector of length emb
        x_emb = self.x_encoder(x.unsqueeze(-1))  # (B, rows, features, emb)
        # the label column: (B, rows, 1, emb)
        y_emb = self.y_encoder(y.unsqueeze(-1)).unsqueeze(2)
        h = torch.cat([x_emb, y_emb], dim=2)  # the label: one more column
        for layer in self.layers:
            h = layer(h, n_train)  # (B, rows, features + 1, emb)
        # class logits from the label cell of every test row
        return self.decoder(h[:, n_train:, -1])
```

## 3. The pretraining loop

Every step in pretraining draws 32 fresh tables, gives the model the labeled rows, and scores its predicted class probabilities on the
unlabeled rows with cross-entropy. Minimizing this loss *is* learning to predict in context. The learning rate decays to
zero on a cosine schedule, and every 10 % of the steps we check accuracy on three test datasets the model never trained on.

```python theme={null}
def train(model, num_steps, lr, batch_size=32):
    model = model.to(device)  # run on the GPU if there is one
    optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
        optimizer, T_max=num_steps)
    t0 = time.time()
    for step in range(1, num_steps + 1):
        # fresh synthetic tables every step
        x, y, n_train, _ = sample_from_prior(batch_size)
        x, y = x.to(device), y.to(device)
        # split into labeled (train) and unlabeled (test) rows
        x_train, x_test = x[:, :n_train], x[:, n_train:]
        y_train, y_test = y[:, :n_train], y[:, n_train:]
        logits = model(x_train, y_train, x_test)
        # only the unlabeled rows are scored
        loss = F.cross_entropy(
            logits.reshape(-1, 2), y_test.reshape(-1).long())
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        scheduler.step()
        if step % (num_steps // 10) == 0:
            seconds = time.time() - t0
            acc = evaluate_model(model)
            print(f"step {step:4d} | {seconds:5.1f}s | "
                  f"loss {loss.item():6.3f} | test accuracy {acc:.3f}")
    return model
```

### A first, fast run

A small model (48-dimensional embeddings, 2 layers) pretrained for 750 steps: about 10 seconds on a GPU or Apple Silicon.

```python theme={null}
small_lines = train(
    NanoTabPFN(emb=48, layers=2), num_steps=750, lr=1e-3)
```

```console theme={null}
step   75 |  13.3s | loss  0.275 | test accuracy 0.810
step  150 |  15.7s | loss  0.137 | test accuracy 0.852
step  225 |  16.6s | loss  0.195 | test accuracy 0.850
step  300 |  17.6s | loss  0.160 | test accuracy 0.852
step  375 |  18.5s | loss  0.127 | test accuracy 0.852
step  450 |  19.5s | loss  0.198 | test accuracy 0.852
step  525 |  20.5s | loss  0.128 | test accuracy 0.843
step  600 |  21.5s | loss  0.263 | test accuracy 0.853
step  675 |  22.5s | loss  0.183 | test accuracy 0.853
step  750 |  23.5s | loss  0.189 | test accuracy 0.853
```

## A simple evaluation on three datasets

We use three test datasets with different boundaries: a straight **line**, a slow **sine wave**, and a **sine + fast wave**. Our model has only seen data from lines during pre-training.

The pretrained model sees 40 labeled points (red dots and blue crosses) as context; the background is its prediction everywhere else: red for class 1, blue for class 0, and white where the model is unsure.

```python theme={null}
plot_predictions(small_lines)
```

![A simple evaluation on three datasets](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/pretrain_nanotabpfn_teaching/plot-02.png)

We now compare our model's accuracy on hold-out points against logistic regression and a random forest fitted on the same 40 points.

```python theme={null}
compare_with_baseline({"small, lines prior": small_lines})
```

```console theme={null}
accuracy               line   sine wave   sine + fast wave   mean
-----------------------------------------------------------------
small, lines prior    0.980       0.835              0.745  0.853
logistic regression   0.950       0.750              0.725  0.808
random forest         0.905       0.825              0.760  0.830
```

## 4. A richer prior

We now make the boundary functions a bit more complex by adding a sine wave on top of the line, with amplitude $A \sim \mathcal{U}(0, 2)$,
frequency $\omega \sim \mathcal{U}(0.5, 5)$ and phase $\varphi \sim \mathcal{U}(0, 2\pi)$. The new boundary is
$f(x_1) = a + b x_1 + A \sin(\omega x_1 + \varphi)$.

```python theme={null}
def sample_from_prior(batch_size, num_rows=50, noise_std=0.1):
    '''A batch of synthetic tables with two features x1 and x2:
    class 1 above a random boundary curve, class 0 below it.'''
    # boundary x2 = a + b*x1 + A*sin(w*x1 + phi), one per table
    a = torch.randn(batch_size, 1)                  # intercept ~ N(0, 1)
    b = torch.randn(batch_size, 1)                  # slope ~ N(0, 1)
    amp = 2 * torch.rand(batch_size, 1)             # amplitude ~ U(0, 2)
    w = 0.5 + 4.5 * torch.rand(batch_size, 1)       # frequency ~ U(0.5, 5)
    phi = 2 * torch.pi * torch.rand(batch_size, 1)  # phase ~ U(0, 2 pi)
    boundary = lambda t: a + b * t + amp * torch.sin(w * t + phi)
    # points scattered around the boundary
    x1 = torch.randn(batch_size, num_rows)
    x2 = boundary(x1) + torch.randn(batch_size, num_rows)
    # class 1 above the boundary, class 0 below (slightly noisy)
    noise = noise_std * torch.randn(batch_size, num_rows)
    y = (x2 + noise > boundary(x1)).float()
    # the first n_train rows are labeled, the model predicts the rest
    n_train = torch.randint(10, num_rows - 2, ()).item()
    # the boundary is returned only for plotting
    return torch.stack([x1, x2], dim=-1), y, n_train, boundary
```

### A run with the richer prior

```python theme={null}
x, y, n_train, boundary = sample_from_prior(4)
plot_prior_samples(x, y, boundary)
```

![A run with the richer prior](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/pretrain_nanotabpfn_teaching/plot-03.png)

```python theme={null}
# The same small model and pretraining run, now on the richer prior.
small = train(NanoTabPFN(emb=48, layers=2), num_steps=750, lr=1e-3)
```

```console theme={null}
step   75 |   0.9s | loss  0.555 | test accuracy 0.633
step  150 |   1.8s | loss  0.387 | test accuracy 0.857
step  225 |   2.8s | loss  0.413 | test accuracy 0.870
step  300 |   3.7s | loss  0.397 | test accuracy 0.875
step  375 |   4.6s | loss  0.467 | test accuracy 0.880
step  450 |   5.5s | loss  0.286 | test accuracy 0.890
step  525 |   6.6s | loss  0.295 | test accuracy 0.882
step  600 |   7.8s | loss  0.353 | test accuracy 0.898
step  675 |   8.9s | loss  0.218 | test accuracy 0.892
step  750 |   9.9s | loss  0.291 | test accuracy 0.887
```

### Results with the richer prior

```python theme={null}
plot_predictions(small)
```

![Results with the richer prior](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/pretrain_nanotabpfn_teaching/plot-04.png)

```python theme={null}
compare_with_baseline(
    {"small, lines prior": small_lines, "small, wave prior": small})
```

```console theme={null}
accuracy               line   sine wave   sine + fast wave   mean
-----------------------------------------------------------------
small, lines prior    0.980       0.835              0.745  0.853
small, wave prior     0.945       0.905              0.810  0.887
logistic regression   0.950       0.750              0.725  0.808
random forest         0.905       0.825              0.760  0.830
```

## 5. Scaling up

We now scale up by doubling three knobs: a wider embedding (48 → 96), more layers (2 → 4) and more training steps (750 → 1,500). This run takes about 1 minute on a GPU or Apple Silicon.

```python theme={null}
large = train(NanoTabPFN(emb=96, layers=4), num_steps=1500, lr=1e-3)
```

```console theme={null}
step  150 |   7.7s | loss  0.277 | test accuracy 0.882
step  300 |  12.7s | loss  0.275 | test accuracy 0.890
step  450 |  17.2s | loss  0.284 | test accuracy 0.918
step  600 |  21.8s | loss  0.408 | test accuracy 0.923
step  750 |  26.5s | loss  0.325 | test accuracy 0.927
step  900 |  31.1s | loss  0.225 | test accuracy 0.918
step 1050 |  35.7s | loss  0.277 | test accuracy 0.932
step 1200 |  40.2s | loss  0.366 | test accuracy 0.923
step 1350 |  45.2s | loss  0.285 | test accuracy 0.925
step 1500 |  50.1s | loss  0.155 | test accuracy 0.923
```

## Evaluating the larger model

The large model now follows the wavy boundary. The white uncertainty band runs along the boundary and gets wider where labeled points of the two classes are far apart.

The model also beats logistic regression and random forests on this data.

```python theme={null}
plot_predictions(large)
```

![Evaluating the larger model](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/pretrain_nanotabpfn_teaching/plot-05.png)

```python theme={null}
compare_with_baseline(
    {"small, wave prior": small, "large, wave prior": large})
```

```console theme={null}
accuracy               line   sine wave   sine + fast wave   mean
-----------------------------------------------------------------
small, wave prior     0.945       0.905              0.810  0.887
large, wave prior     0.965       0.920              0.885  0.923
logistic regression   0.950       0.750              0.725  0.808
random forest         0.905       0.825              0.760  0.830
```

## Next steps

Ready for more complex data? Continue with [Pretrain a Tabular Foundation Model from Scratch](https://docs.priorlabs.ai/cookbook/pretrain_nanotabpfn.md), which uses a richer random-network prior and evaluates zero-shot on real datasets.


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