跳到正文

第 22 课 · Servers, Deployment and Teams

Serve and Deploy Models

Serve MLflow models over a REST API, send correctly shaped requests to the invocations endpoint, build Docker images and test before you deploy.

A model helps only when something can use it. MLflow can start a local inference server for a model, and it can build a container image for deployment.

Check the model first

Run one prediction in a fresh environment. It catches missing dependencies early:

Terminal
mlflow models predict -m "models:/churn-classifier@champion" \
  -i sample.csv -t csv --env-manager virtualenv

--env-manager can be local, virtualenv, uv or conda. Building a new environment takes time but tests the recorded requirements. local uses your current environment.

Serve locally

Terminal
export MLFLOW_TRACKING_URI=http://localhost:5000
mlflow models serve -m "models:/churn-classifier@champion" -p 5001

Use a different port from your tracking server. The documented endpoints are:

Endpoint Purpose
POST /invocations Get predictions
GET /ping, GET /health Health checks
GET /version MLflow version

Send a request

The server accepts JSON or CSV. A common table format is dataframe_split:

Terminal
curl http://127.0.0.1:5001/invocations \
  -H "Content-Type: application/json" \
  -d '{"dataframe_split": {"columns": ["visits", "plan"],
                           "data": [[2, "basic"], [9, "pro"]]}}'

Other keys include dataframe_records, instances and inputs (the last two are for tensor-style data). The docs do not recommend dataframe_records, because column order is not guaranteed. A model with a signature gets better type handling.

Build the payload in code

This stand-in converts rows to the split shape. It sends nothing over the network.

Python Stand-in: build a dataframe_split payload

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Listing the column order once is explicit, so each value lines up with its column.

Build a container

Terminal
mlflow models build-docker -m "models:/churn-classifier/3" -n churn-service
docker run -p 5001:8080 churn-service

The port inside the container in the second command assumes the usual setting of MLflow images. Check the docs for your version. A version number, not an alias, ties the image clearly to one model.

Deployment targets

MLflow documents local serving, Docker images, Amazon SageMaker (mlflow sagemaker), Azure ML (with the azureml-mlflow package), Databricks Model Serving, and plugins for other platforms. Each target has its own setup, permissions and costs, so follow the guide for your target.

Production readiness

A local server is only a start. Before real traffic, plan for:

  1. Authentication and TLS. Do not expose the inference server openly.
  2. Input validation, including value ranges.
  3. Timeouts and limits on request size and rate.
  4. Monitoring of errors, latency, input drift and outcomes.
  5. Version logging for each prediction.
  6. Rollback to a previous version.

Predictions that affect people, such as credit or hiring decisions, need human review, fairness checks and legal advice that fits your region. A technically healthy server can still make harmful decisions.

Batch scoring

Not every model needs an API. For nightly scoring, load the model with mlflow.pyfunc.load_model in a scheduled job, score a table and save the result. It is often simpler and cheaper than running a live service.

Handle responses and errors

A client should check the HTTP status before it reads the body. A rejected request usually means that the input does not match the schema. Log the error message on your side, but be careful about logging the input itself if it contains personal data.

Python
import requests

response = requests.post(
    "http://127.0.0.1:5001/invocations",
    json={"dataframe_split": {"columns": ["visits", "plan"],
                              "data": [[2, "basic"]]}},
    timeout=10,
)
response.raise_for_status()
print(response.json())

Always set a timeout. Without one, a stuck server can make your application wait for a very long time. Decide what your app does when the model does not answer: retry a few times with a delay, use a safe default, or hand the case to a person. A default decision is itself a product choice, so make it deliberately.

Test the container

Before you deploy an image, run it on your computer:

  1. Start the container.
  2. Call /ping and confirm that it answers.
  3. Send a normal request and compare the result with mlflow.pyfunc.load_model on your computer.
  4. Send a broken request and confirm a clear rejection.
  5. Measure how long start-up and one request take.

Step 3 is a strong check. If both paths give the same predictions for the same input, the packaging probably kept the behavior. If they differ, look at library versions and preprocessing.

Plan capacity

A single server process handles a limited number of requests. Estimate your peak traffic, then load test with realistic input in a safe environment, never against a production system without permission. Add more replicas behind a load balancer if needed, and watch memory, since each replica loads its own copy of the model.

Common mistakes

Do not send real customer data to a test server that has weaker protection than production. Use made-up rows with the same shape. Also do not assume that a successful health check means correct predictions. A health check shows that the process responds, so keep a small set of known inputs and check their outputs after each deployment.

Record what you served

Keep the model version, request time and outcome for each prediction, following your privacy rules. When real results arrive later, you can join them to the predictions and measure how the live model performs.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Which endpoint receives prediction requests?

    Predictions are posted to /invocations. The others report health or version.
  2. 2. Why is dataframe_split usually preferred over dataframe_records?

    The columns list fixes the order of values, while records do not guarantee it.
  3. 3. What is a good way to detect missing dependencies before you deploy?

    A fresh environment uses the recorded requirements and reveals gaps.

Summary

  • Test with mlflow models predict, then serve with mlflow models serve.
  • Send requests to /invocations in a supported format.
  • build-docker creates a container image.
  • Production needs security, monitoring and rollback.

Next: Teams, Security and Reproducibility

你的学习进度保存在此浏览器中,无需账号。