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

# Get Started with TabPFN-4

> Get started with TabPFN-4 and see how its predictive quality and fit-plus-predict time grow with training rows, compared with TabPFN 3.5 and XGBoost

By
Prior Labs[LinkedIn](https://www.linkedin.com/company/prior-labs)[X](https://twitter.com/prior_labs)

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

TabPFN-4 is our latest tabular foundation model (as of writing: December 2026). It can use up to 10 million rows as context in a single forward pass, and its inference time grows subquadratically with the number of training rows. TabPFN-4 is available through the API with `tabpfn-client`; see the [technical report](https://priorlabs.ai/technical-reports/tabpfn-4-preview) for the full benchmark results.

The [TabPFN 3.5 getting-started cookbook](https://docs.priorlabs.ai/cookbook/tabpfn_35_vs_baselines.md) compared models on one small dataset. TabPFN-4's main change is scale, so here we ask a different question: **what happens as the training set grows?** We fit every model on increasingly large slices of the same training data and score them on the same held-out rows:

* **TabPFN-4** and **TabPFN 3.5**, both through the API with default settings
* **XGBoost** with library defaults at every size
* **XGBoost tuned for 10 minutes** on the largest training set

We use the [Covertype](https://archive.ics.uci.edu/dataset/31/covertype) dataset: 581,012 forest cells, 54 cartographic features, and seven tree-cover classes. It is a classic large-tabular benchmark where gradient-boosted trees keep improving with more data, which makes it a fair test for scaling.

> **Runtime:** the full run fits each TabPFN version on up to 400,000 rows and tunes XGBoost for 10 minutes, so expect it to take a while. TabPFN runs through the API and does not use your local GPU; XGBoost runs on your CPU. Lower `TRAIN_SIZES` for a quicker pass.

## Client setup

Create an API key on the [TabPFN platform](https://platform.priorlabs.ai/account/api-keys) and set the `TABPFN_TOKEN` environment variable before starting Jupyter. On Colab, store it as a secret named `TABPFN_TOKEN` using the key icon in the sidebar. TabPFN-4 needs `tabpfn-client` 0.11.2.

```python theme={null}
%pip install -q tabpfn-client==0.11.2 xgboost scikit-learn matplotlib pandas
```

```python theme={null}
import os
import sys

import tabpfn_client

IN_COLAB = "google.colab" in sys.modules
if IN_COLAB and not os.environ.get("TABPFN_TOKEN"):
    from google.colab import userdata

    try:
        token = userdata.get("TABPFN_TOKEN")
    except userdata.SecretNotFoundError:
        token = None
    if token:
        os.environ["TABPFN_TOKEN"] = token

if os.environ.get("TABPFN_TOKEN"):
    tabpfn_client.set_access_token(os.environ["TABPFN_TOKEN"])

tabpfn_client.init()
```

## Imports and configuration

`create_default_for_version` pins each TabPFN version, so the comparison stays the same after future releases. `TabPFNClassifier()` without a version always uses the current default model.

`TRAIN_SIZES` sets the training slices. Each slice contains the previous one, so a larger slice only adds rows.

```python theme={null}
import math
import random
import time

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_covtype
from sklearn.metrics import accuracy_score, log_loss
from sklearn.model_selection import train_test_split
from tabpfn_client import RefitRequiredError, TabPFNClassifier
from tabpfn_client.api_models import ModelVersion
from xgboost import XGBClassifier

SEED = 42
TRAIN_SIZES = [10_000, 50_000, 100_000, 200_000, 400_000]
TEST_ROWS = 20_000
TABPFN_VERSIONS = {"TabPFN-4": ModelVersion.V4, "TabPFN 3.5": ModelVersion.V3_5}
```

## Load the data and fix the splits

We hold out 20,000 rows as the test set and 10,000 as a validation set for tuning XGBoost. Both are stratified by class and stay fixed for every model and every training size. The remaining rows are shuffled once, and each training slice takes the first `n` of them.

The seven class labels are shifted to start at 0, which XGBoost expects.

```python theme={null}
data = fetch_covtype(as_frame=True)
X, y = data.data, data.target.to_numpy() - 1

X_rest, X_test, y_rest, y_test = train_test_split(
    X, y, test_size=TEST_ROWS, stratify=y, random_state=SEED
)
X_pool, X_valid, y_pool, y_valid = train_test_split(
    X_rest, y_rest, test_size=10_000, stratify=y_rest, random_state=SEED
)
order = np.random.default_rng(SEED).permutation(len(X_pool))
X_pool, y_pool = X_pool.iloc[order].reset_index(drop=True), y_pool[order]

assert max(TRAIN_SIZES) <= len(X_pool)
print(f"{len(X):,} rows, {X.shape[1]} features, {len(np.unique(y))} classes")
print(f"training pool {len(X_pool):,} | validation {len(X_valid):,} | test {len(X_test):,}")
pd.Series(y).value_counts(normalize=True).sort_index().rename("class share").round(3)
```

```console theme={null}
581,012 rows, 54 features, 7 classes
training pool 551,012 | validation 10,000 | test 20,000
0    0.365
1    0.488
2    0.062
3    0.005
4    0.016
5    0.030
6    0.035
Name: class share, dtype: float64
```

## Measuring quality and speed

We score predicted probabilities with **accuracy** (share of test rows whose most likely class is right; higher is better) and **log loss** (how much probability lands on the right class; lower is better).

For speed we time one `fit` plus `predict_proba` call per model and size. For TabPFN this is wall time through the API, so it includes uploading the training rows and the network round trip. XGBoost runs on your CPU, so its times depend on your machine. The two are not directly comparable as compute, but they are what you wait for in practice.

```python theme={null}
def score(proba: np.ndarray) -> dict[str, float]:
    proba = np.clip(np.asarray(proba, dtype=float), 1e-12, None)
    proba /= proba.sum(axis=1, keepdims=True)
    return {
        "accuracy": accuracy_score(y_test, proba.argmax(axis=1)),
        "log_loss": log_loss(y_test, proba, labels=np.arange(proba.shape[1])),
    }


def timed(model, X_train, y_train) -> dict[str, float]:
    for attempt in range(2):
        start = time.perf_counter()
        model.fit(X_train, y_train)
        try:
            proba = model.predict_proba(X_test)
        except RefitRequiredError:
            # The API was updated between fit and predict: fit again and retime.
            if attempt == 1:
                raise
            continue
        return {**score(proba), "seconds": time.perf_counter() - start}


rows = []


def record(model_name: str, n_train: int, result: dict[str, float]) -> None:
    rows.append({"model": model_name, "train_rows": n_train, **result})
    print(f"{model_name:>22} | {n_train:>7,} rows | accuracy {result['accuracy']:.4f} | "
          f"log loss {result['log_loss']:.4f} | {result['seconds']:,.1f}s", flush=True)
```

## TabPFN-4 and TabPFN 3.5

Both versions use the same `TabPFNClassifier` with default settings. `fit` uploads the training rows as context, and `predict_proba` predicts every test row in one call. No hyperparameters, no preprocessing: the features go in as they are.

```python theme={null}
for n_train in TRAIN_SIZES:
    for name, version in TABPFN_VERSIONS.items():
        model = TabPFNClassifier.create_default_for_version(version, random_state=SEED)
        record(name, n_train, timed(model, X_pool.iloc[:n_train], y_pool[:n_train]))
```

```console theme={null}
              TabPFN-4 |  10,000 rows | accuracy 0.8848 | log loss 0.3051 | 5.8s
            TabPFN 3.5 |  10,000 rows | accuracy 0.8853 | log loss 0.2977 | 6.9s
              TabPFN-4 |  50,000 rows | accuracy 0.9505 | log loss 0.1337 | 6.3s
            TabPFN 3.5 |  50,000 rows | accuracy 0.9486 | log loss 0.1318 | 20.8s
              TabPFN-4 | 100,000 rows | accuracy 0.9645 | log loss 0.0938 | 12.2s
            TabPFN 3.5 | 100,000 rows | accuracy 0.9632 | log loss 0.0929 | 41.5s
              TabPFN-4 | 200,000 rows | accuracy 0.9755 | log loss 0.0605 | 13.0s
            TabPFN 3.5 | 200,000 rows | accuracy 0.9747 | log loss 0.0627 | 102.9s
              TabPFN-4 | 400,000 rows | accuracy 0.9817 | log loss 0.0434 | 28.0s
            TabPFN 3.5 | 400,000 rows | accuracy 0.9813 | log loss 0.0452 | 298.5s
```

## XGBoost, out of the box

The same training slices with XGBoost's default hyperparameters, histogram trees, and all available CPU threads. All Covertype features are numeric, so XGBoost needs no preprocessing here either.

```python theme={null}
def xgb_model(**params) -> XGBClassifier:
    return XGBClassifier(
        objective="multi:softprob", tree_method="hist", n_jobs=-1,
        random_state=SEED, verbosity=0, **params,
    )


for n_train in TRAIN_SIZES:
    record("XGBoost · default", n_train, timed(xgb_model(), X_pool.iloc[:n_train], y_pool[:n_train]))
```

```console theme={null}
     XGBoost · default |  10,000 rows | accuracy 0.7986 | log loss 0.5062 | 1.7s
     XGBoost · default |  50,000 rows | accuracy 0.8504 | log loss 0.3693 | 2.1s
     XGBoost · default | 100,000 rows | accuracy 0.8599 | log loss 0.3518 | 2.9s
     XGBoost · default | 200,000 rows | accuracy 0.8640 | log loss 0.3347 | 4.2s
     XGBoost · default | 400,000 rows | accuracy 0.8680 | log loss 0.3443 | 7.7s
```

### XGBoost, tuned for 10 minutes

To give XGBoost a fair shot on the largest slice, we run a random search over its main hyperparameters for 10 minutes. Each candidate trains on the largest slice with early stopping on the fixed validation set; the first candidate is a sensible hand-picked configuration. The best configuration by validation log loss is then refit, with its number of boosting rounds, and timed like the other models. The search itself is outside the timer.

This cell takes about 10 minutes, plus the final fit.

```python theme={null}
def sample_params(rng: random.Random) -> dict:
    def log_uniform(low: float, high: float) -> float:
        return math.exp(rng.uniform(math.log(low), math.log(high)))

    return {
        "learning_rate": log_uniform(0.02, 0.3),
        "max_depth": rng.randint(4, 14),
        "min_child_weight": log_uniform(0.1, 20),
        "subsample": rng.uniform(0.6, 1.0),
        "colsample_bytree": rng.uniform(0.5, 1.0),
        "reg_lambda": log_uniform(1e-3, 100),
        "max_bin": rng.choice([128, 256, 512]),
    }


n_train = max(TRAIN_SIZES)
X_big, y_big = X_pool.iloc[:n_train], y_pool[:n_train]
rng = random.Random(SEED)
deadline = time.perf_counter() + 600
trials = []
params = {"learning_rate": 0.1, "max_depth": 10, "min_child_weight": 1.0,
          "subsample": 0.9, "colsample_bytree": 0.9, "reg_lambda": 1.0, "max_bin": 256}
while time.perf_counter() < deadline:
    model = xgb_model(**params, n_estimators=5_000, early_stopping_rounds=50, eval_metric="mlogloss")
    model.fit(X_big, y_big, eval_set=[(X_valid, y_valid)], verbose=False)
    trials.append({"params": params, "valid_log_loss": model.best_score,
                   "rounds": model.best_iteration + 1})
    params = sample_params(rng)

best = min(trials, key=lambda trial: trial["valid_log_loss"])
print(f"{len(trials)} trials; best validation log loss {best['valid_log_loss']:.4f} "
      f"with {best['rounds']} rounds")
tuned = xgb_model(**best["params"], n_estimators=best["rounds"])
record("XGBoost · 10-min tuning", n_train, timed(tuned, X_big, y_big))
```

```console theme={null}
3 trials; best validation log loss 0.0890 with 1303 rounds
XGBoost · 10-min tuning | 400,000 rows | accuracy 0.9705 | log loss 0.0784 | 132.2s
```

## Results on the largest training set

All four models on the same 400,000 training rows and the same 20,000 test rows.

```python theme={null}
results = pd.DataFrame(rows)
largest = (
    results[results.train_rows == max(TRAIN_SIZES)]
    .set_index("model")[["accuracy", "log_loss", "seconds"]]
    .rename(columns={"accuracy": "Accuracy", "log_loss": "Log loss", "seconds": "Fit + predict (s)"})
    .sort_values("Log loss")
)
largest.round({"Accuracy": 4, "Log loss": 4, "Fit + predict (s)": 1})
```

```console theme={null}
                         Accuracy  Log loss  Fit + predict (s)
model
TabPFN-4                   0.9817    0.0434               28.0
TabPFN 3.5                 0.9813    0.0452              298.5
XGBoost · 10-min tuning    0.9704    0.0784              132.2
XGBoost · default          0.8680    0.3443                7.7
```

## How quality and time scale with training rows

The left panel shows test accuracy for each training size, the right panel the time for one fit plus
predict. The tuned XGBoost point sits at the largest size only.

```python theme={null}
from matplotlib.ticker import FuncFormatter

colors = {"TabPFN-4": "#2563EB", "TabPFN 3.5": "#93C5FD",
          "XGBoost · default": "#A8B3C2", "XGBoost · 10-min tuning": "#475569"}
fig, axes = plt.subplots(1, 2, figsize=(12, 4.8), gridspec_kw={"wspace": 0.3})
for name, group in results.groupby("model", sort=False):
    style = dict(color=colors[name], marker="o", lw=2, label=name)
    axes[0].plot(group.train_rows, 100 * group.accuracy, **style)
    axes[1].plot(group.train_rows, group.seconds, **style)
    last = group.iloc[-1]
    axes[1].annotate(f"{last.seconds:.0f}s", (last.train_rows, last.seconds),
                     xytext=(6, 0), textcoords="offset points", va="center",
                     fontsize=9, color=colors[name])

axes[0].set(xlabel="training rows", ylabel="test accuracy (%), higher is better")
axes[0].set_title("Predictive quality", loc="left", weight="bold")
axes[1].set(xlabel="training rows", ylabel="fit + predict_proba time (s), lower is better")
axes[1].set_title("Time", loc="left", weight="bold")
axes[1].set_ylim(bottom=0)
for ax in axes:
    ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: f"{x / 1000:.0f}k"))
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(alpha=0.2)
axes[0].legend(frameon=False, loc="lower right")
fig.suptitle("Covertype: scaling with training rows", x=0.06, ha="left", fontsize=16, weight="bold")
plt.show()
```

![How quality and time scale with training rows](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/tabpfn_4_vs_baselines/plot-01.png)

```python theme={null}
from IPython.display import display

for column, label in [("accuracy", "Test accuracy"), ("seconds", "Fit + predict (s)")]:
    print(label)
    display(results.pivot(index="train_rows", columns="model", values=column).round(4))
```

```console theme={null}
Test accuracy
model       TabPFN 3.5  TabPFN-4  XGBoost · 10-min tuning  XGBoost · default
train_rows
10000           0.8854    0.8848                      NaN             0.7986
50000           0.9486    0.9504                      NaN             0.8504
100000          0.9632    0.9644                      NaN             0.8599
200000          0.9746    0.9754                      NaN             0.8640
400000          0.9813    0.9817                   0.9704             0.8680
Fit + predict (s)
model       TabPFN 3.5  TabPFN-4  XGBoost · 10-min tuning  XGBoost · default
train_rows
10000           6.8667    5.7954                      NaN             1.6649
50000          20.8223    6.2817                      NaN             2.1437
100000         41.4974   12.1633                      NaN             2.8895
200000        102.8814   12.9981                      NaN             4.1756
400000        298.4691   27.9627                 132.2199             7.6584
```

## Reading the results

On the largest slice, TabPFN-4 has the best accuracy (0.982) and log loss (0.043), with default settings and no tuning. TabPFN 3.5 is close on quality (0.981, 0.045), and both are well ahead of XGBoost, which reaches 0.970 after 10 minutes of tuning and 0.868 with its defaults.

The difference between the two TabPFN versions is time. On the smallest slice they take about the same, 6 to 7 seconds. As the training set grows, TabPFN 3.5 slows down steeply: 41 seconds at 100,000 rows and almost 5 minutes at 400,000. TabPFN-4 stays at 12 seconds at 100,000 rows and 28 seconds at 400,000, about 10 times faster than TabPFN 3.5 on the largest slice for the same quality. Default XGBoost is the fastest at every size, but far behind on quality.

These results describe one dataset and one held-out split. TabPFN timings are API wall times and include uploading the training rows; XGBoost timings depend on your CPU and exclude the 10-minute search. To go further, try TabPFN-4 on a dataset of your own, or join the [Advent of TabPFN-4](https://platform.priorlabs.ai/).


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