Model Serving with KFServing and Scikit-learn - Iris Flower Classification

Model Serving with KFServing and Scikit-Learn - Iris Flower Classification


INPUT –> MODEL –> PREDICTION

This notebook requires KFServing to be installed

NOTE: It is assumed that a model called irisflowerclassifier is already available in Hopsworks. An example of training a model for the Iris flower classification problem is available in Jupyter/end_to_end_pipelines/sklearn/end_to_end_sklearn.ipynb

Model Serving on Hopsworks

hops.png

The hops python library

hops is a helper library for Hops that facilitates development by hiding the complexity of running applications and iteracting with services.

Have a feature request or encountered an issue? Please let us know on github.

Serve the Iris Flower classifier

Query Model Registry for best Iris Classifier Model

import hsml

conn = hsml.connection()
mr = conn.get_model_registry()
Connected. Call `.close()` to terminate connection gracefully.
MODEL_NAME="irisflowerclassifier"
EVALUATION_METRIC="accuracy"

best_model = mr.get_best_model(MODEL_NAME, EVALUATION_METRIC, "max")

print('Model name: ' + best_model.name)
print('Model version: ' + str(best_model.version))
print(best_model.training_metrics)
Model name: irisflowerclassifier
Model version: 1
{'accuracy': '0.98'}

Create Model Serving of Exported Model

from hops import serving
# Create serving instance
SERVING_NAME = MODEL_NAME

response = serving.create_or_update(SERVING_NAME, # define a name for the serving instance
                                    model_path=best_model.model_path, # set the path of the model to be deployed
                                    model_server="PYTHON", # set the model server to run the model
                                    kfserving=True, # whether to serve the model using KFServing or the default tool in the current Hopsworks version
                                    # optional arguments
                                    model_version=best_model.version, # set the version of the model to be deployed
                                    topic_name="CREATE", # (optional) set the topic name or CREATE to create a new topic for inference logging
                                    inference_logging="ALL", # with KFServing, select the type of inference data to log into Kafka, e.g MODEL_INPUTS, PREDICTIONS or ALL
                                    instances=1, # with KFServing, set 0 instances to leverage scale-to-zero capabilities
                                    )
2022-01-17 15:14:07,102 INFO: Serving irisflowerclassifier successfully created

Once the serving instance is created, it will be shown in the “Model Serving” tab in the Hopsworks UI. You can view detailed information like server-logs and which Kafka Topic it is logging inference requests to.

kfserving_sklearn_modelonly_details.gif

You can also use the Python module to query the Hopsworks REST API about information on the existing servings using methods like:

  • get_all()
  • get_id(serving_name)
  • get_model_path(serving_name)
  • get_model_version(serving_name)
  • get_artifact_version(serving_name)
  • get_kafka_topic(serving_name)
  • ...
print("Info: \tid: {},\n \
       model_path: {},\n \
       model_version: {},\n \
       artifact_version: {},\n \
       model_server: {},\n \
       serving_tool: {}".format(
    serving.get_id(SERVING_NAME),
    serving.get_model_path(SERVING_NAME),
    serving.get_model_version(SERVING_NAME),
    serving.get_artifact_version(SERVING_NAME),
    serving.get_model_server(SERVING_NAME),
    serving.get_serving_tool(SERVING_NAME)))
Info:   id: 2523,
        model_path: /Projects/demo_ml_meb10000/Models/irisflowerclassifier,
        model_version: 1,
        artifact_version: 0,
        model_server: PYTHON,
        serving_tool: KFSERVING
for s in serving.get_all():
    print(s.name)
irisflowerclassifier

Classify flowers with the Iris Flower classifier

Start Model Serving Server

if serving.get_status(SERVING_NAME) == 'Stopped':
    serving.start(SERVING_NAME)
Starting serving with name: irisflowerclassifier...
Serving with name: irisflowerclassifier successfully started
import time
while serving.get_status(SERVING_NAME) != "Running":
    time.sleep(5) # Let the serving startup correctly
time.sleep(10)

Check the Server Logs

You can access the server logs using Kibana by clicking on the ‘Show logs’ button in the action bar, and filter them using fields such as serving component (i.e., predictor or transformer) or container name among other things.

kfserving_sklearn_modelonly_logs.gif

Send Prediction Requests to the Served Model using Hopsworks REST API

import json
import random

NUM_FEATURES = 4

for i in range(20):
    data = {"instances" : [[random.uniform(1, 8) for i in range(NUM_FEATURES)]]}
    response = serving.make_inference_request(SERVING_NAME, data)
    print(response)
{'predictions': [2]}
{'predictions': [1]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [0]}
{'predictions': [0]}
{'predictions': [2]}
{'predictions': [1]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [0]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [2]}
{'predictions': [0]}

Monitor Prediction Requests and Responses using Kafka

from hops import kafka
from confluent_kafka import Producer, Consumer, KafkaError

Setup Kafka consumer and subscribe to the topic containing the prediction logs

TOPIC_NAME = serving.get_kafka_topic(SERVING_NAME)

config = kafka.get_kafka_default_config()
config['default.topic.config'] = {'auto.offset.reset': 'earliest'}
consumer = Consumer(config)
topics = [TOPIC_NAME]
consumer.subscribe(topics)

Read the Kafka Avro schema from Hopsworks and setup an Avro reader

json_schema = kafka.get_schema(TOPIC_NAME)
avro_schema = kafka.convert_json_schema_to_avro(json_schema)

Read messages from the Kafka topic, parse them with the Avro schema and print the results

PRINT_INSTANCES=False
PRINT_PREDICTIONS=True

for i in range(0, 10):
    msg = consumer.poll(timeout=5.0)
    if msg is not None:
        value = msg.value()
        try:
            event_dict = kafka.parse_avro_msg(value, avro_schema)  
            payload = json.loads(event_dict["payload"])
            
            if (event_dict['messageType'] == "request" and not PRINT_INSTANCES) or \
                (event_dict['messageType'] == "response" and not PRINT_PREDICTIONS):
                continue
            
            print("INFO -> servingId: {}, modelName: {}, modelVersion: {},"\
                  "requestTimestamp: {}, inferenceId:{}, messageType:{}".format(
                       event_dict["servingId"],
                       event_dict["modelName"],
                       event_dict["modelVersion"],
                       event_dict["requestTimestamp"],
                       event_dict["inferenceId"],
                       event_dict["messageType"]))

            if event_dict['messageType'] == "request":
                print("Instances -> {}\n".format(payload['instances']))
                
            if event_dict['messageType'] == "response":
                print("Predictions -> {}\n".format(payload['predictions']))

        except Exception as e:
            print("A message was read but there was an error parsing it")
            print(e)
    else:
        print("timeout.. no more messages to read from topic")
INFO -> servingId: 2523, modelName: irisflowerclassifier, modelVersion: 1,requestTimestamp: 1641839298, inferenceId:9fff76ad-55e1-4c52-b0e9-7019ce79a249, messageType:response
Predictions -> [2]

INFO -> servingId: 2523, modelName: irisflowerclassifier, modelVersion: 1,requestTimestamp: 1641839298, inferenceId:03c8d155-cbb9-4907-bfc2-630d3777e56f, messageType:response
Predictions -> [1]

INFO -> servingId: 2523, modelName: irisflowerclassifier, modelVersion: 1,requestTimestamp: 1641839298, inferenceId:cd45feb2-d1c1-43b6-a612-f0dffeaf0e01, messageType:response
Predictions -> [2]

INFO -> servingId: 2523, modelName: irisflowerclassifier, modelVersion: 1,requestTimestamp: 1641839298, inferenceId:4b14a25a-fed1-45cc-a994-a1b37ba55543, messageType:response
Predictions -> [2]

INFO -> servingId: 2523, modelName: irisflowerclassifier, modelVersion: 1,requestTimestamp: 1641839299, inferenceId:dbe84132-b0ce-4196-bd5c-da72f1607f45, messageType:response
Predictions -> [0]