Skip to main content

Deploy an image classification model with Model Serving

An image classification model returns a label for an image, such as "Egyptian cat" or "espresso", and a score for that label. You can use one to assign keywords to stock photos, or to organize and categorize photo galleries.

This example serves the google/vit-base-patch16-224 model from Hugging Face on a GPU endpoint and sends it two sample images. It also shows how to send an image to an endpoint: the request is JSON, so each image file travels as a base64 string.

Requirements​

Run the example​

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

Deploy an image classification 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 transformers, which runs the model, pillow, which reads and writes the image files, and scikit-image, which provides the two sample photos. After the installs, the cell restarts Python. 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 the model uses, and scikit-image for the sample photos.
%pip install transformers pillow scikit-image

%restart_python

Define and log the model​

The model is a custom MLflow model, a Python class whose predict method answers each request.

  1. Define the model class. The class has two methods:

    • load_context runs one time, when the model loads. It builds a Transformers image-classification pipeline from the model's files, on the GPU when one is present.
    • predict runs on every request. It decodes each row's base64 string into an image and returns the image's top label and score.

    To define the model, run the following:

    Python
    import mlflow
    import pandas as pd


    class ImageClassifier(mlflow.pyfunc.PythonModel):
    def load_context(self, context):
    import torch
    from transformers import pipeline

    # Load the model one time, from the files packaged with it, on the GPU when one is present.
    device = 0 if torch.cuda.is_available() else -1
    self.classifier = pipeline("image-classification", model=context.artifacts["model_dir"], device=device)

    def predict(self, context, model_input, params=None):
    import base64
    import io

    from PIL import Image

    # Each row holds one image file, encoded as a base64 string.
    predictions = []
    for data in model_input["image"]:
    image = Image.open(io.BytesIO(base64.b64decode(data))).convert("RGB")
    top = self.classifier(image, top_k=1)[0]
    predictions.append({"label": top["label"], "score": top["score"]})
    return pd.DataFrame(predictions)

    The cell prints an MLflow warning about type hints for predict. You can ignore it, because the next cell gives MLflow an input example.

  2. Log the model. The cell saves the model's files to a local folder and logs the folder with the model, so the files are packaged with it. It also saves two sample photos from scikit-image, a cat and a cup of coffee, as JPEG files. Both photos ship inside the scikit-image package and are released under CC0.

    encode_image turns an image file into a base64 string, which is about 33% larger than the file. MLflow infers the model's signature from the input example, one row that holds the cat photo. Unity Catalog requires a signature on each new model version. To log the model, run the following:

    Python
    import base64

    from PIL import Image
    from skimage import data
    from transformers import pipeline

    # Save the model's files to a local folder. MLflow packages the folder with the model.
    MODEL_DIR = "/tmp/vit-base-patch16-224"
    pipeline("image-classification", model="google/vit-base-patch16-224").save_pretrained(MODEL_DIR)

    # Save two sample photos from scikit-image as local JPEG files.
    SAMPLE_IMAGES = {"/tmp/cat.jpg": data.chelsea(), "/tmp/coffee.jpg": data.coffee()}
    for path, pixels in SAMPLE_IMAGES.items():
    Image.fromarray(pixels).save(path)


    def encode_image(path):
    # A JSON request carries an image file as text, so encode the file's bytes as a base64 string.
    with open(path, "rb") as f:
    return base64.b64encode(f.read()).decode("utf-8")


    model_info = mlflow.pyfunc.log_model(
    name="vit_image_classifier",
    python_model=ImageClassifier(),
    artifacts={"model_dir": MODEL_DIR},
    input_example=pd.DataFrame({"image": [encode_image("/tmp/cat.jpg")]}),
    )

    The cell prints only library messages, such as 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>.vit_image_classifier",
env_pack=EnvPackConfig(name="databricks_model_serving"),
)
print("Registered", model_version.name, "version", model_version.version)

The cell prints the following:

Text
Registered <catalog>.<schema>.vit_image_classifier version 1

MLflow also prints lines about packing the environment and a link to the new version.

Create the endpoint​

The cell creates the endpoint vit-image-classifier-endpoint with create_and_wait. It serves the registered version as the served entity vit-image-classifier on a GPU workload type. 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 = "vit-image-classifier-endpoint"

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

Send images to the endpoint​

The request sends one row for each image, and each row holds the image's base64 string from encode_image in image. The response holds one prediction, a label and a score, for each row. image_paths holds the paths of the two sample photos that the logging cell saved. To classify your own images, replace them with the paths to your image files, then run the following:

Python
import time

from databricks.sdk.errors import NotFound

image_paths = ["/tmp/cat.jpg", "/tmp/coffee.jpg"]

# 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=[{"image": encode_image(path)} for path in image_paths],
)
break
except NotFound:
time.sleep(10)
else:
raise TimeoutError("The endpoint didn't accept the request after 12 tries.")

# Each prediction holds the top label and its score for one image.
for path, prediction in zip(image_paths, response.predictions):
print(path, prediction["label"], round(prediction["score"], 4))

The output is similar to the following:

Text
/tmp/cat.jpg Egyptian cat 0.967
/tmp/coffee.jpg espresso 0.9933

Each label is one of the 1,000 classes of ImageNet, the image dataset the model was fine-tuned on. The labels and scores are for the two sample images, and your own images get their own.

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.

A request can be at most 16 MB. To send each image file as raw bytes instead of base64 text, see Send files in protobuf requests.

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>.vit_image_classifier

Additional resources​