Deploy a two-tower recommender endpoint with Model Serving
This example trains a two-tower recommender on synthetic data and serves it on a CPU Model Serving endpoint. It then queries the endpoint for scores and deletes the endpoint and the model.
For the other compute choices, see Compute type.
Requirements
- A workspace in a supported region.
- The Unity Catalog privileges to register and delete models, described in Manage model lifecycle in Unity Catalog.
Run the example
To run every step, import the notebook. Run the cells in order, in the same notebook.
Two-tower recommender endpoint notebook
Install the packages
To install the packages, run the following:
%pip install -U "mlflow>=3" "databricks-sdk>=0.102.0" pandas==3.1.1 torch==2.15.0
dbutils.library.restartPython()
The output ends with a message about restarting the kernel.
Set the model and endpoint names
A Unity Catalog model name has three levels, catalog.schema.model. Replace <catalog> and <schema> with a catalog and schema where you have the privileges listed under Requirements. To set the names, run the following:
# Set these once. Replace the placeholders with your own names.
CATALOG = "<catalog>"
SCHEMA = "<schema>"
MODEL = "two_tower_model"
ENDPOINT_NAME = "two-tower-recs"
FULL_MODEL_NAME = f"{CATALOG}.{SCHEMA}.{MODEL}"
Generate the data and define the model
This step generates synthetic training data, so the example needs no dataset of your own. Each row pairs a user and an item, labeled 1.0 (a positive pair) when the user interacts with the item and 0.0 (a negative pair) when the user doesn't. Users and items each belong to one of five groups. For each of the 300 users, the cell picks 15 random items from the user's group, labeled 1.0. It also picks 15 items from other groups, labeled 0.0, for 9,000 rows in all. Run the following:
import numpy as np
import pandas as pd
import torch
SEED = 0
N_USERS, N_ITEMS, N_GROUPS = 300, 400, 5
DIM = 16
EPOCHS = 10
rng = np.random.default_rng(SEED)
torch.manual_seed(SEED)
# Each user and each item belongs to one of five groups. A user interacts with items from the same group.
user_group = rng.integers(0, N_GROUPS, N_USERS)
item_group = rng.integers(0, N_GROUPS, N_ITEMS)
rows = []
for user in range(N_USERS):
in_group = np.flatnonzero(item_group == user_group[user])
out_group = np.flatnonzero(item_group != user_group[user])
positives = rng.choice(in_group, size=15, replace=False)
negatives = rng.choice(out_group, size=15, replace=False)
rows += [(user, item, 1.0) for item in positives]
rows += [(user, item, 0.0) for item in negatives]
interactions = pd.DataFrame(rows, columns=["user_id", "item_id", "label"]).astype(
{"user_id": "int64", "item_id": "int64"}
)
print("Interactions:", len(interactions), "rows")
The cell prints the following:
Interactions: 9000 rows
The model has two towers, one for users and one for items. Each tower turns an ID into a vector of 16 numbers. It looks the ID up in an embedding table (torch.nn.Embedding, which stores a vector for each ID) and passes the vector through two linear layers. A pair's score multiplies the two vectors element by element, sums the products, and applies a sigmoid, so the score falls between 0 and 1.
TwoTowerModel wraps the towers for MLflow. Its load_context loads the trained weights one time when the model loads. It passes weights_only=True, so torch.load reads only tensors. Its predict scores each row of a request. Run the following:
import mlflow.pyfunc
class Tower(torch.nn.Module):
"""One tower: an embedding for each ID, then a small MLP."""
def __init__(self, num_ids, dim):
super().__init__()
self.embedding = torch.nn.Embedding(num_ids, dim)
self.mlp = torch.nn.Sequential(
torch.nn.Linear(dim, dim), torch.nn.ReLU(), torch.nn.Linear(dim, dim)
)
def forward(self, ids):
return self.mlp(self.embedding(ids))
def score_pairs(user_tower, item_tower, pairs):
"""Return one score for each row of user_id and item_id."""
user_ids = torch.as_tensor(pairs["user_id"].to_numpy(), dtype=torch.long)
item_ids = torch.as_tensor(pairs["item_id"].to_numpy(), dtype=torch.long)
with torch.no_grad():
logits = (user_tower(user_ids) * item_tower(item_ids)).sum(dim=-1)
return torch.sigmoid(logits).numpy()
class TwoTowerModel(mlflow.pyfunc.PythonModel):
def __init__(self, n_users, n_items, dim):
self.n_users = n_users
self.n_items = n_items
self.dim = dim
def load_context(self, context):
# Runs once, when the model loads. The tower weights are artifacts packaged with the model.
self.user_tower = Tower(self.n_users, self.dim)
self.user_tower.load_state_dict(torch.load(context.artifacts["user_tower"], weights_only=True))
self.user_tower.eval()
self.item_tower = Tower(self.n_items, self.dim)
self.item_tower.load_state_dict(torch.load(context.artifacts["item_tower"], weights_only=True))
self.item_tower.eval()
def predict(self, context, model_input, params=None):
return score_pairs(self.user_tower, self.item_tower, model_input)
Train the model
The cell trains both towers for 10 epochs to score the pairs labeled 1.0 high and the pairs labeled 0.0 low. It prints the loss after each epoch, then the mean score of each kind of pair as a check. Run the following:
import torch
user_tower = Tower(N_USERS, DIM)
item_tower = Tower(N_ITEMS, DIM)
optimizer = torch.optim.Adam(
list(user_tower.parameters()) + list(item_tower.parameters()), lr=0.01
)
loss_fn = torch.nn.BCEWithLogitsLoss()
users = torch.as_tensor(interactions["user_id"].to_numpy(), dtype=torch.long)
items = torch.as_tensor(interactions["item_id"].to_numpy(), dtype=torch.long)
labels = torch.as_tensor(interactions["label"].to_numpy(), dtype=torch.float32)
for epoch in range(1, EPOCHS + 1):
order = torch.randperm(len(labels))
total_loss = 0.0
for start in range(0, len(order), 256):
idx = order[start : start + 256]
logits = (user_tower(users[idx]) * item_tower(items[idx])).sum(dim=-1)
loss = loss_fn(logits, labels[idx])
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item() * len(idx)
print(f"Epoch {epoch}: loss {total_loss / len(labels):.4f}")
scores = score_pairs(user_tower, item_tower, interactions)
labels_np = interactions["label"].to_numpy()
print(f"Mean score, positive pairs: {scores[labels_np == 1].mean():.3f}")
print(f"Mean score, negative pairs: {scores[labels_np == 0].mean():.3f}")
The cell prints the following:
Epoch 1: loss 0.6989
Epoch 2: loss 0.6878
Epoch 3: loss 0.6714
Epoch 4: loss 0.6235
Epoch 5: loss 0.5271
Epoch 6: loss 0.3933
Epoch 7: loss 0.2728
Epoch 8: loss 0.1752
Epoch 9: loss 0.1277
Epoch 10: loss 0.0785
Mean score, positive pairs: 0.958
Mean score, negative pairs: 0.027
The positive pairs score higher than the negative pairs. The check uses the training pairs, so it doesn't show how well the model recommends.
Save and log the model
To save the weights and log the model, run the following:
import os
import tempfile
import mlflow
from mlflow.models import infer_signature
weights_dir = tempfile.mkdtemp()
user_path = os.path.join(weights_dir, "user_tower.pt")
item_path = os.path.join(weights_dir, "item_tower.pt")
torch.save(user_tower.state_dict(), user_path)
torch.save(item_tower.state_dict(), item_path)
example = interactions[["user_id", "item_id"]].head(5)
signature = infer_signature(example, score_pairs(user_tower, item_tower, example))
info = mlflow.pyfunc.log_model(
name="model",
python_model=TwoTowerModel(n_users=N_USERS, n_items=N_ITEMS, dim=DIM),
artifacts={"user_tower": user_path, "item_tower": item_path},
# MLflow doesn't infer torch for this model, so pin it. The split drops a local version label such as +cpu.
extra_pip_requirements=[f"torch=={torch.__version__.split('+')[0]}"],
signature=signature,
input_example=example,
registered_model_name=FULL_MODEL_NAME,
)
MODEL_VERSION = str(info.registered_model_version)
print("Registered model:", FULL_MODEL_NAME)
print("Version:", MODEL_VERSION)
The cell prints the following:
Registered model: <catalog>.<schema>.two_tower_model
Version: 1
The output shows the registered model name and version 1.
Each tower's weights are saved to a file and passed to log_model as an artifact. extra_pip_requirements adds torch at the notebook's version, because the serving container needs it to load the towers and MLflow doesn't add it. Unity Catalog requires a signature on each new model version. infer_signature builds the signature from the five example rows and their scores. Setting registered_model_name creates the model version and the registered model when the name doesn't exist.
Create the endpoint
To create the endpoint for the logged model version, run the following:
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import (
EndpointCoreConfigInput,
ServedEntityInput,
ServingModelWorkloadType,
)
w = WorkspaceClient()
endpoint = w.serving_endpoints.create_and_wait(
name=ENDPOINT_NAME,
config=EndpointCoreConfigInput(
name=ENDPOINT_NAME,
served_entities=[
ServedEntityInput(
entity_name=FULL_MODEL_NAME,
entity_version=MODEL_VERSION,
workload_type=ServingModelWorkloadType.CPU,
workload_size="Small",
scale_to_zero_enabled=True,
)
],
),
)
print("state.ready:", endpoint.state.ready)
print("state.config_update:", endpoint.state.config_update)
print("scale_to_zero_enabled:", endpoint.config.served_entities[0].scale_to_zero_enabled)
The cell prints the following:
state.ready: EndpointStateReady.READY
state.config_update: EndpointStateConfigUpdate.NOT_UPDATING
scale_to_zero_enabled: True
After a successful create, state.ready shows READY and state.config_update shows NOT_UPDATING.
The endpoint uses a Small workload size and has scale to zero enabled. For the workload sizes and the other endpoint settings, including scale to zero, see Create an endpoint for custom models in Model Serving.
Query the endpoint
The request asks the endpoint to score five candidate items for user 7. They're the first two items in user 7's group and the first three items in other groups. It sends one row for each candidate. The rows have two columns, user_id and item_id, and the response's predictions field holds one score for each row. The cell prints the candidates from the highest score to the lowest. Run the following:
import time
from databricks.sdk.errors import NotFound
from databricks.sdk.service.serving import DataframeSplitInput
USER_ID = 7
same_group = np.flatnonzero(item_group == user_group[USER_ID])[:2]
other_groups = np.flatnonzero(item_group != user_group[USER_ID])[:3]
CANDIDATE_ITEMS = [int(item) for item in np.concatenate([same_group, other_groups])]
rows = [[USER_ID, item] for item in CANDIDATE_ITEMS]
# Retry while the endpoint is not accepting requests yet.
for attempt in range(12):
try:
response = w.serving_endpoints.query(
name=ENDPOINT_NAME,
dataframe_split=DataframeSplitInput(columns=["user_id", "item_id"], data=rows),
)
break
except NotFound:
time.sleep(10)
else:
raise TimeoutError("The endpoint didn't accept the request after 12 tries.")
QUERY_TRIES = attempt + 1
print("Query tries:", QUERY_TRIES)
ranked = sorted(zip(CANDIDATE_ITEMS, response.predictions), key=lambda pair: pair[1], reverse=True)
print(f"Scores for user {USER_ID}, highest first:")
for rank, (item, score) in enumerate(ranked, start=1):
print(f"{rank}. item {item}: {score:.4f}")
The cell prints the following:
Query tries: 1
Scores for user 7, highest first:
1. item 0: 1.0000
2. item 1: 1.0000
3. item 7: 0.0000
4. item 3: 0.0000
5. item 6: 0.0000
The two items from user 7's group score highest, at 1.0000 each, and the three items from other groups score 0.0000.
A query sent after the endpoint reports READY can get a 404 with the error code ENDPOINT_NOT_FOUND for a short time, so the loop retries. It makes up to 12 tries and waits 10 seconds after each 404.
To call the endpoint over REST, see Format scoring requests.
Delete the endpoint and the model
Optionally, delete the endpoint and the model. You can't undo deleting the endpoint or the registered model. To delete the endpoint, run the following:
w.serving_endpoints.delete(name=ENDPOINT_NAME)
print("Deleted endpoint:", ENDPOINT_NAME)
The cell prints the following:
Deleted endpoint: two-tower-recs
To delete the model versions and the registered model, run the following:
from mlflow import MlflowClient
client = MlflowClient()
for version in client.search_model_versions(f"name='{FULL_MODEL_NAME}'"):
client.delete_model_version(name=FULL_MODEL_NAME, version=version.version)
print("Deleted version:", version.version)
client.delete_registered_model(name=FULL_MODEL_NAME)
print("Deleted registered model:", FULL_MODEL_NAME)
The cell prints the following:
Deleted version: 1
Deleted registered model: <catalog>.<schema>.two_tower_model