---
url: /stable/tutorials/save-and-deploy.md
description: >-
  Save a fitted relational model without its database rows, then load it with
  pickle and attach the tables used for prediction.
---

# Save, load and deploy relational models

**Call `sklink.detach(model)` before saving a fitted relational model so the
artifact carries its fitted state and schema without the database rows. After
loading, use `sklink.rebind(model, database)` to attach the tables you want
to score.** The model keeps the rules, thresholds and categories it learned.

## Detach before saving

```python
import pickle

import sklink
from sklink.datasets import make_relational_classification
from sklink.tree import RelationalDecisionTreeClassifier

db, X, y = make_relational_classification(
    n_entities=500, signal="conditional", random_state=0
)
model = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", max_depth=2
).fit(X, y)

with_data = pickle.dumps(model)
without_data = pickle.dumps(sklink.detach(model))
print("Detached artifact is smaller:", len(without_data) < len(with_data))
```

```text
Detached artifact is smaller: True
```

A detached artifact stores the schema and model state. You can inspect the
byte counts with `len(with_data)` and `len(without_data)` in your environment.
`detach` returns a copy. The original model keeps its database. The same
operation works on a pipeline or fitted search that holds relational
estimators.

## Load and rebind

Loading a pickle can execute code, so only load artifacts you trust. A
detached model raises `DetachedDatabaseError` if you try to predict before
attaching a database.

```python
from sklink.exceptions import DetachedDatabaseError

loaded = pickle.loads(without_data)
try:
    loaded.predict(X)
except DetachedDatabaseError as error:
    print(error)

ready = sklink.rebind(loaded, db)
print((ready.predict(X) == model.predict(X)).all())
```

```text
This model was detached from its database. Call sklink.rebind(model, database) before using it.
True
```

`rebind` checks that the database provides the schema the fitted model uses.
Extra tables and columns are allowed. Rebinding the original database
reproduces the original predictions, as the final `True` shows.

A `Database` infers the type of each column from its values, so the same
column can get another type from other rows: a column of labels read as
`categorical` during training can be read as `text` from one day of rows in
which every label is different. `rebind` then raises a `SchemaError` that
names the declaration to add, such as
`column_types={"orders": {"type": "categorical"}}`. Declaring the types of
such columns in the training and in the prediction database avoids the
difference.

## Load with the same version

A saved model keeps the version of scikit-link that saved it. Loading it with
another version emits an `InconsistentVersionWarning`, as scikit-learn does
for its own estimators: the model may fail or give other results. Record
`sklink.__version__` with the artifact, install that version where the model
is loaded, and refit the model when you upgrade.

## Score fresh data

When new data arrives, build a database with the current tables and put the
customers to score in `X_today`. To simulate a correction here, `table()`
returns an editable copy of `orders`. `with_tables` creates a database with
the changed orders and keeps the existing keys, relationships and other
tables.

```python
orders_today = db.table("orders", output="pandas")
orders_today.loc[0, "amount"] = 120.0
X_today = orders_today.loc[[0], ["customer_id"]]  # the customer of that order

today = db.with_tables(orders=orders_today)
predictions = sklink.rebind(loaded, today).predict(X_today)
```

## New entities

Include new customers in the database you attach so the model can read their
attributes and orders. By default, prediction raises an error for a key that
is missing from the attached entity table. If the model should still make a
prediction, fit it with `handle_unknown_entity="empty"` to treat unknown keys
as having no entity row or related rows.

```python
import pandas as pd

lenient = RelationalDecisionTreeClassifier(
    db,
    entity="customers",
    key="customer_id",
    max_depth=2,
    handle_unknown_entity="empty",
).fit(X, y)
print(lenient.predict(pd.DataFrame({"customer_id": [10_000_001]})))
```

```text
[0]
```

This tree predicts class 0 for the unknown key because it finds no qualifying
express order.

## Memory and speed

`sklink.set_config` and `sklink.config_context` control resources for the
current thread. Environment variables with the `SKLINK_` prefix, such as
`SKLINK_CACHE_BYTES`, set the initial values.

| Option | What it does |
| --- | --- |
| `cache_bytes` | Size of the cache of evaluated expressions. `0` disables it |
| `chunk_rows` | Population rows evaluated at once by `transform` and `predict` |
| `engine_threads` | Requested thread count for backends that support it. The NumPy backend ignores this setting. |
| `backend` | Evaluation backend; `"numpy"` is the in-memory reference |
| `warn_pickle_bytes` | Size above which pickling an in-memory database warns |
| `tree_kernels` | `"auto"` compiles the inner loops of relational trees, forests and gradient boosting with Numba when it is installed (it installs with the package where Numba has wheels), `"numpy"` never does and `"numba"` requires it. Models are the same either way. Numba keeps the compiled code next to the package or in the user's cache; on a read-only file system, point `NUMBA_CACHE_DIR` to a writable directory or each process compiles again |

```python
with sklink.config_context(chunk_rows=10_000, cache_bytes=0):
    model.predict(X)
print(sklink.get_config()["cache_bytes"] > 0)
```

```text
True
```

## A JSON copy for other languages

`sklink.inspection.export_json(model, "model.json")` writes a description of
the tree or forest that another system can evaluate. See
[inspect and explain](./inspect-and-explain#export-to-json).

To load tables from files for a prediction job, see the
[data-loading recipes](../cookbook/loading-data).

Next, add an aggregation of your own with
[custom primitives](./custom-primitives).
