Score an XGBoost model with Model Serving
This example trains an XGBoost classifier on the iris dataset and logs it with mlflow.xgboost. It then serves the model on a CPU Model Serving endpoint, queries the endpoint, and deletes the endpoint and the model.
The iris dataset comes with scikit-learn, so the example downloads no data.
If you prefer a scikit-learn model, see Deploy a scikit-learn model with Model Serving.
Requirements
- A workspace in a supported region.
- Unity Catalog permissions for models, as 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.
Score an XGBoost model notebook
Install the packages
To install the packages, run the following:
%pip install -U "mlflow>=3" "databricks-sdk>=0.102.0" scikit-learn==1.9.1 pandas==3.1.1 xgboost==3.4.1
dbutils.library.restartPython()
The install can print a pip warning that databricks-connect requires pandas below 3. The install still finishes, and the sample runs.
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, and the MLflow APIs take that name. Replace <catalog> and <schema> with a catalog and schema where you have the permissions 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 = "iris_xgboost"
ENDPOINT_NAME = "iris-xgboost"
FULL_MODEL_NAME = f"{CATALOG}.{SCHEMA}.{MODEL}"
The endpoint name must be unique across the workspace. If the name is taken, change ENDPOINT_NAME in the cell above.
Load the data and split it
To load the iris data and split it, run the following:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris(as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=0
)
The as_frame=True argument makes the data a pandas DataFrame. The dataset has 150 rows, 50 in each of three classes, and four numeric features.
Train and log the model
To train the XGBoost classifier and log it, run the following:
import mlflow.xgboost
from mlflow.models import infer_signature
from xgboost import XGBClassifier
xgb_model = XGBClassifier().fit(X_train, y_train)
signature = infer_signature(X_train, xgb_model.predict(X_train))
info = mlflow.xgboost.log_model(
xgb_model=xgb_model,
name="model",
signature=signature,
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>.iris_xgboost
Version: 1
Unity Catalog requires a signature on each new model version. The cell builds the signature with infer_signature from the training inputs and the model's predictions on them.
When registered_model_name is set, log_model creates a model version under that name, and it also creates the registered model if none exists.
The entity_version field of ServedEntityInput is an optional string, and the cell converts the version with str().
This example doesn't pass pip_requirements, so log_model infers the requirements from the current software environment. For how the endpoint's container uses them, see Deployment container and dependencies.
The cell also writes two MLflow warnings that say no run link is recorded for the model version, and it still finishes.
Create the endpoint
The endpoint serves the version that the log cell registered, as a CPU workload. For the workload sizes and the other endpoint settings, see Create an endpoint for custom models in Model Serving. To create the endpoint and wait for it, 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)
The cell prints the following:
state.ready: EndpointStateReady.READY
state.config_update: EndpointStateConfigUpdate.NOT_UPDATING
The scale_to_zero_enabled=True argument lets the endpoint scale to zero.
Query the endpoint
To query the endpoint with the first two rows of the test set, run the following:
import time
from databricks.sdk.errors import NotFound
from databricks.sdk.service.serving import DataframeSplitInput
FEATURE_COLUMNS = ["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"]
rows = X_test[FEATURE_COLUMNS].head(2).values.tolist()
# 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=FEATURE_COLUMNS, 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(response.as_dict())
The cell prints the following:
{'predictions': [2, 1], 'served-model-name': 'iris_xgboost-1'}
The request names the four feature columns, and the logged signature checks the inputs against them.
For the request body when you call the endpoint over REST, see Format scoring requests.
A query can get a 404 for a short time after state.ready shows READY, so the sample retries for up to 12 tries.
The predictions list has one value for each row in the request. The served-model-name value is the name of the served entity that answered. For this model, the default name is the last part of the three-level model name, a hyphen, and the version, so it reads iris_xgboost-1.
The model was fit on the iris target codes. To turn the predictions into class names, index iris.target_names with them, as the load_iris example in the scikit-learn reference does.
Delete the endpoint and the registered model
Optionally, delete the endpoint and the registered model. You can't undo deleting the endpoint or the registered model. To delete the endpoint, run the following:
delete_result = w.serving_endpoints.delete(name=ENDPOINT_NAME)
print("delete returned:", repr(delete_result))
The cell prints the following:
delete returned: None
To delete the registered model with the MLflow client, run the following:
from mlflow import MlflowClient
MlflowClient().delete_registered_model(name=FULL_MODEL_NAME)
print("Deleted registered model:", FULL_MODEL_NAME)
The cell prints the following:
Deleted registered model: <catalog>.<schema>.iris_xgboost