Skip to main content

Deploy a reranker with Model Serving

A reranker is a model that takes a question and a list of texts, such as search results, and scores how well each text answers the question. You can then put the best texts first, for example when you rerank the search results of a retrieval-augmented generation (RAG) app.

This example serves the BAAI/bge-reranker-base model from Hugging Face on a GPU endpoint and scores two sample sentences against one question.

Requirements​

Run the example​

To run every step, import the notebook. Run the cells in order, in the same notebook.

Deploy a reranker notebook

Check for GPU compute​

Run this notebook on serverless GPU compute, because registering the model packages the notebook's environment with it. The first cell checks for serverless GPU compute and stops with an error if it's missing. Run the following:

Python
import os

# Run this notebook on serverless GPU compute, because registration packages the notebook's environment.
if not os.environ.get("DATABRICKS_ACCELERATOR"):
raise RuntimeError("Attach this notebook to serverless GPU compute, then run the cell again.")

When the check passes, the cell finishes without an error. If it raises the error, attach the notebook to serverless GPU compute and run the cell again.

Install the packages​

The cell installs MLflow 3.12 or above and the Databricks SDK for Python 0.102.0 or above, which this example needs to register the model with env_pack. The cell also installs transformers, which the model uses. After the installs, the cell restarts Python. To install them, run the following:

Python
# Registering with env_pack requires recent MLflow and Databricks SDK versions.
%pip install -U "mlflow>=3.12" "databricks-sdk>=0.102.0"

# Install the libraries your model needs. transformers is preinstalled in the
# AI environment. Install it explicitly because this model depends on it.
%pip install transformers

%restart_python

Log the model​

The cell loads BAAI/bge-reranker-base as a Transformers text-classification pipeline and logs it to MLflow. Its input example is a one-row table that has a text column for the query and a text_pair column for the document. MLflow runs the pipeline on the example to infer the output signature. The logged input schema has two required string columns, text and text_pair. The model_config setting truncates each pair to 512 tokens, the model's input limit, so a long document still gets a score. Unity Catalog requires a signature on each new model version. To log the model, run the following:

Python
import mlflow
import pandas as pd
from transformers import pipeline

# BAAI/bge-reranker-base is a cross-encoder reranker: it scores how well a document answers a query.
pipe = pipeline("text-classification", model="BAAI/bge-reranker-base")

# Give the input example as a one-row table, so the logged signature has a text column and a text_pair column.
model_info = mlflow.transformers.log_model(
transformers_model=pipe,
name="bge_reranker",
input_example=pd.DataFrame(
[{"text": "What is Databricks?", "text_pair": "Databricks is a data and AI company."}]
),
# Truncate each query and document pair to the model's 512-token input limit at inference.
model_config={"truncation": True, "max_length": 512},
)

The cell prints only library messages, such as a Hugging Face token warning and MLflow's signature inference message.

Register the model​

A Unity Catalog model name has three levels, catalog.schema.model. Replace <catalog> and <schema> with a Unity Catalog schema where you have the privileges in Requirements. The cell registers the model with env_pack=EnvPackConfig(name="databricks_model_serving"), which packages the notebook environment during registration. To register the model, run the following:

Python
import mlflow
from mlflow.utils.env_pack import EnvPackConfig

mlflow.set_registry_uri("databricks-uc")

model_version = mlflow.register_model(
model_uri=model_info.model_uri,
name="<catalog>.<schema>.bge_reranker",
env_pack=EnvPackConfig(name="databricks_model_serving"),
)

The output names the new version, version 1 for a new model, and says that the version is staged for Model Serving. For more on env_pack, see Express deployments for model serving endpoints.

Create the endpoint​

The cell creates the endpoint bge-reranker-endpoint with create_and_wait. It serves the registered version as the served entity bge-reranker on a GPU workload type, and it turns scale to zero off. For the GPU workload types on each cloud, see GPU workload types. To create the endpoint, run the following:

Python
from datetime import timedelta

from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import (
EndpointCoreConfigInput,
ServedEntityInput,
ServingModelWorkloadType,
)

endpoint_name = "bge-reranker-endpoint"

w = WorkspaceClient()
w.serving_endpoints.create_and_wait(
name=endpoint_name,
config=EndpointCoreConfigInput(
name=endpoint_name,
served_entities=[
ServedEntityInput(
name="bge-reranker",
entity_name=model_version.name,
entity_version=model_version.version,
workload_type=ServingModelWorkloadType.GPU_SMALL,
workload_size="Small",
scale_to_zero_enabled=False,
)
],
),
timeout=timedelta(minutes=45),
)

Scale to zero is off, so the endpoint doesn't scale down to zero, and you're billed for each replica while it runs. To delete it, see Delete the endpoint and the model. If a later cell fails, run the delete cells anyway, so the endpoint doesn't keep running.

Score documents for a query​

A document is a text that you rank against the query, such as a search result. The example scores two sample sentences. The request sends one row for each document, and each row holds the query in text and the document in text_pair. The response holds one prediction for each row, and a higher score means the document answers the query better. Replace the sample query and documents with your own, then run the following:

Python
import time
from databricks.sdk.errors import NotFound

query = "What is Databricks?"
documents = [
"Databricks is a data and AI company.",
"Bananas are a yellow fruit that grows in bunches.",
]

# Retry while the endpoint is not accepting requests yet.
for attempt in range(12):
try:
response = w.serving_endpoints.query(
name=endpoint_name,
dataframe_records=[{"text": query, "text_pair": document} for document in documents],
)
break
except NotFound:
time.sleep(10)
else:
raise TimeoutError("The endpoint didn't accept the request after 12 tries.")

# Each prediction scores one query and document pair. A higher score means a better answer.
for document, prediction in zip(documents, response.predictions):
print(round(prediction["score"], 4), document)

The output is similar to the following:

Text
0.9981 Databricks is a data and AI company.
0.0 Bananas are a yellow fruit that grows in bunches.

The relevant document scores close to 1, and the unrelated one scores close to 0. Your own query and documents get their own scores. To rerank a list of documents, sort them by score from highest to lowest.

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 Send a request from an application over REST.

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:

Python
delete_result = w.serving_endpoints.delete(name=endpoint_name)
print("delete returned:", repr(delete_result))

The cell prints the following:

Text
delete returned: None

To delete the model version that this notebook registered, run the following. When no other version of the model is left, the cell also deletes the registered model:

Python
from mlflow import MlflowClient

client = MlflowClient()
client.delete_model_version(name=model_version.name, version=model_version.version)
print("Deleted version:", model_version.version)
if not client.search_model_versions(f"name='{model_version.name}'"):
client.delete_registered_model(name=model_version.name)
print("Deleted registered model:", model_version.name)

The cell prints the following:

Text
Deleted version: 1
Deleted registered model: <catalog>.<schema>.bge_reranker

Additional resources​