---
url: /stable/cookbook/performance.md
description: >-
  Speed up scikit-link: compile the tree loops with Numba, choose n_jobs, narrow
  the search of a tree, and limit memory when predicting on large tables.
---

# Fit faster

**Most of the time of a relational tree goes into scoring candidate
questions. Compile those loops with Numba, grow forest trees in parallel, and
narrow the search when it is wider than your data needs.** The first two
recipes never change the fitted model; the parameters in the third do.

## Setup

```python
from sklink.datasets import make_relational_classification
from sklink.ensemble import RelationalRandomForestClassifier

db, X, y = make_relational_classification(300, signal="child_numeric", random_state=0)


def make_forest(**params):
    return RelationalRandomForestClassifier(
        db,
        entity="customers",
        key="customer_id",
        n_estimators=20,
        random_state=0,
        **params,
    )
```

## Compile the tree loops with Numba {#numba}

Numba installs with the package. With the default `tree_kernels="auto"`,
relational trees, forests and gradient boosting run their inner loops
compiled with Numba. The fitted models are exactly the same as with NumPy, so
you can switch at any time:

```python
import numpy as np
import sklink

with sklink.config_context(tree_kernels="numpy"):
    reference = make_forest().fit(X, y)
with sklink.config_context(tree_kernels="auto"):
    compiled = make_forest().fit(X, y)
print(np.array_equal(reference.predict_proba(X), compiled.predict_proba(X)))
```

```text
True
```

What to expect:

* **The first fit in a new environment** spends a few seconds compiling, and
  caches the result on disk for the next runs. On a read-only file system,
  point `NUMBA_CACHE_DIR` to a writable folder, or each process compiles
  again.
* **Each process that uses Numba** loads it once, about a second and 100 MB.
  A small forest fitted with `n_jobs` pays that in every worker, so it can be
  faster with `tree_kernels="numpy"`.
* **`tree_kernels="numba"`** requires Numba and raises an error that says
  why when it cannot be used, for example on a free-threaded Python build.
  Use it in production to make sure the compiled loops are in use.
* **The environment variable** `SKLINK_TREE_KERNELS=numpy` sets the same
  option before Python starts, which is handy in a job scheduler.

Intel Macs and Python versions that Numba does not support yet install the
package without Numba, because it has no wheels there, and use the NumPy
loops.

## Grow forest trees in parallel {#n-jobs}

`n_jobs` fits the trees of a forest in worker processes. With a
`random_state`, any number of workers gives the same forest:

```python
serial = make_forest(n_jobs=1).fit(X, y)
parallel = make_forest(n_jobs=2).fit(X, y)
print(np.array_equal(serial.predict_proba(X), parallel.predict_proba(X)))
```

```text
True
```

Gradient boosting grows its trees one after another, because each corrects
the previous ones, so it has no `n_jobs`. To use several cores with it,
parallelize the search around it instead, as in `GridSearchCV(..., n_jobs=-1)`.

## Narrow the search {#search}

These parameters change which questions a tree can ask, so they can change
the model. Compare the scores before and after on the same folds, as in
[compare models](./evaluation).

| Parameter | Default | Faster with | What the tree loses |
| --- | --- | --- | --- |
| `max_relationship_depth` | `2` | `1` | Aggregates two relationships away, such as order lines |
| `max_conditions` | `2` | `1` or `0` | Two conditions inside one aggregate, such as express orders above 100, or any |
| `primitives` | `"default"` | A short list, such as `["count", "mean", "max"]` | The other aggregations |
| `max_bins` | `255` | `64` | Thresholds between the quantiles it keeps |
| `max_condition_bins` | `32` | `16` | Thresholds inside conditions |
| `max_features` (forests) | `"sqrt"` (classifier), `1.0` (regressor) | A smaller fraction | Candidates scored at each node |
| `max_search_samples` | `None`, `2000` for boosting | `1000`, or `2000` for trees and forests | Aggregates with learned conditions are searched on that many samples of a larger node, then the best few are scored on all of them |

`max_relationship_depth` and `max_conditions` usually matter most, because
each extra hop or condition multiplies the number of candidates. On large
data, `max_search_samples` matters most: the condition search then costs the
same at any number of samples, and on RelBench H\&M with 50 000 samples gradient
boosting fits 6 times faster with it than with `None`, with the same accuracy
within the spread over seeds.

## Predict on large tables with bounded memory {#memory}

Forests and gradient boosting evaluate the rows of `X` in chunks of at most
`chunk_rows` rows in `predict`, `predict_proba`, `decision_function` and
`apply`, and make each chunk smaller so that the values of all their
expressions take about 256 MB. Evaluated expressions are kept in a cache of
`cache_bytes`. If a batch job still runs out of memory, lower both options:

```python
with sklink.config_context(chunk_rows=10_000, cache_bytes=0):
    predictions = serial.predict(X)
print(predictions.shape)
```

```text
(300,)
```

Neither option changes the predictions. Before you pickle a model, detach the
tables with `sklink.detach` so the file holds only the model: see
[save and deploy](../tutorials/save-and-deploy).
