Skip to main content

Deploy an embedding model for search with Model Serving

An embedding model turns a text into a vector, a list of numbers, and texts that mean similar things get vectors that are close together. To search, you turn a query and your documents into vectors, then return the documents whose vectors are closest to the query's.

Foundation Model APIs host some embedding models, listed in Detailed list of models supported by Databricks Foundation Model APIs. To serve your own, such as one you fine-tuned on your company's text, deploy it as a custom model. This example serves BAAI/bge-small-en-v1.5 from Hugging Face, a model not supported by Foundation Model APIs, on a GPU endpoint and ranks three sample documents for one query.

Requirements​

Run the example​

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

Deploy an embedding model 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 sentence-transformers, which loads the model. 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. This model loads through sentence-transformers.
%pip install sentence-transformers

%restart_python

Log the model​

The cell downloads BAAI/bge-small-en-v1.5 from Hugging Face through SentenceTransformer and logs it with mlflow.sentence_transformers.log_model. MLflow infers the signature from the input example, a list that holds one text. The logged signature takes a list of texts and returns one vector of 384 numbers for each text. Unity Catalog requires a signature on each new model version. SentenceTransformer loads a model from a folder on disk when you pass its path, and downloads a pre-trained model when you pass a name. To log the model, run the following:

Python
import mlflow
from sentence_transformers import SentenceTransformer

# BAAI/bge-small-en-v1.5 maps each text to a vector of 384 numbers.
# SentenceTransformer loads a model by name from Hugging Face, or from a folder on disk.
model = SentenceTransformer("BAAI/bge-small-en-v1.5")

model_info = mlflow.sentence_transformers.log_model(
model=model,
name="bge_embeddings",
input_example=["What is Databricks?"],
)

The cell prints only library messages, such as a Hugging Face token warning, download progress, and MLflow's link to the logged model.

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_embeddings",
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-embeddings-endpoint with create_and_wait. It serves the registered version as the served entity bge-embeddings 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-embeddings-endpoint"

w = WorkspaceClient()
w.serving_endpoints.create_and_wait(
name=endpoint_name,
config=EndpointCoreConfigInput(
name=endpoint_name,
served_entities=[
ServedEntityInput(
name="bge-embeddings",
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.

Turn texts into vectors​

The request sends the texts as inputs, a list of strings. The response's predictions field holds one vector for each text. Run the following:

Python
import time
from databricks.sdk.errors import NotFound

texts = ["What is Databricks?", "Databricks is a data and AI company."]

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

# The response holds one vector for each text.
vectors = response.predictions
print(len(vectors), "vectors of length", len(vectors[0]))

The cell prints the following:

Text
2 vectors of length 384

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.

Search the sample documents​

The cell sends the query and three sample documents in one request and takes the first vector as the query's. It scores each document by its cosine similarity to the query and prints the documents from the highest score to the lowest. A higher score means the document is closer in meaning to the query. Replace the sample query and documents with your own, then run the following:

Python
import numpy as np

query = "How do I reset my password?"
documents = [
"To reset your password, open Settings and select Reset password.",
"Our office is closed on public holidays.",
"Bananas are a yellow fruit that grows in bunches.",
]

# Embed the query and the documents in one request. The first vector is the query's.
response = w.serving_endpoints.query(name=endpoint_name, inputs=[query] + documents)
vectors = np.array(response.predictions)
query_vector, document_vectors = vectors[0], vectors[1:]

# Cosine similarity: a higher score means a document is closer in meaning to the query.
scores = document_vectors @ query_vector / (
np.linalg.norm(document_vectors, axis=1) * np.linalg.norm(query_vector)
)
for score, document in sorted(zip(scores, documents), reverse=True):
print(round(float(score), 4), document)

The output is similar to the following:

Text
0.9271 To reset your password, open Settings and select Reset password.
0.454 Our office is closed on public holidays.
0.2794 Bananas are a yellow fruit that grows in bunches.

The document about resetting a password ranks first, and the other two score lower. Your own query and documents get their own scores. To reorder the top results with a model that scores each query and document pair, see Deploy a reranker with Model Serving.

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_embeddings

Additional resources​