Wallaroo SDK Upload Arbitrary Python Tutorial: Deploy VGG16 Model
This tutorial can be downloaded as part of the Wallaroo Tutorials repository.
Arbitrary Python Tutorial Deploy Model in Wallaroo Upload and Deploy
This tutorial demonstrates how to use arbitrary python as a ML Model in Wallaroo. Arbitrary Python allows organizations to use Python scripts that require specific libraries and artifacts as models in the Wallaroo engine. This allows for highly flexible use of ML models with supporting scripts.
Tutorial Goals
This tutorial is split into two parts:
- Wallaroo SDK Upload Arbitrary Python Tutorial: Generate Model: Train a dummy
KMeans
model for clustering images using a pre-trainedVGG16
model oncifar10
as a feature extractor. The Python entry points used for Wallaroo deployment will be added and described.- A copy of the arbitrary Python model
models/model-auto-conversion-BYOP-vgg16-clustering.zip
is included in this tutorial, so this step can be skipped.
- A copy of the arbitrary Python model
- Arbitrary Python Tutorial Deploy Model in Wallaroo Upload and Deploy: Deploys the
KMeans
model in an arbitrary Python package in Wallaroo, and perform sample inferences. The filemodels/model-auto-conversion-BYOP-vgg16-clustering.zip
is provided so users can go right to testing deployment.
Arbitrary Python Script Requirements
The entry point of the arbitrary python model is any python script that must include the following.
class ImageClustering(Inference)
: The default inference class. This is used to perform the actual inferences. Wallaroo uses the_predict
method to receive the inference data and call the appropriate functions for the inference.def __init__
: Used to initialize this class and load in any other classes or other required settings.def expected_model_types
: Used by Wallaroo to anticipate what model types are used by the script.def model(self, model)
: Defines the model used for the inference. Accepts the model instance used in the inference.self._raise_error_if_model_is_wrong_type(model)
: Returns the error if the wrong model type is used. This verifies that only the anticipated model type is used for the inference.self._model = model
: Sets the submitted model as the model for this class, provided_raise_error_if_model_is_wrong_type
is not raised.
def _predict(self, input_data: InferenceData)
: This is the entry point for Wallaroo to perform the inference. This will receive the inference data, then perform whatever steps and return a dictionary of numpy arrays.
class ImageClusteringBuilder(InferenceBuilder)
: Loads the model and prepares it for inferencing.def inference(self) -> ImageClustering
: Sets the inference class being used for the inferences.def create(self, config: CustomInferenceConfig) -> ImageClustering
: Creates an inference subclass, assigning the model and any attributes required for it to function.
The following requirements.txt
specifies the libraries to use - these must match the versions specified in the Wallaroo Model Upload documentation.
tensorflow==2.9.3
scikit-learn==1.3.0
All other methods used for the functioning of these classes are optional, as long as they meet the requirements listed above.
Tutorial Prerequisites
- Wallaroo Version 2024.2 or above instance.
References
Tutorial Steps
Import Libraries
The first step is to import the libraries we’ll be using. These are included by default in the Wallaroo instance’s JupyterHub service.
import numpy as np
import pandas as pd
import json
import os
import pickle
import pyarrow as pa
#import tensorflow as tf
import wallaroo
# from sklearn.cluster import KMeans
# from tensorflow.keras.datasets import cifar10
# from tensorflow.keras import Model
# from tensorflow.keras.layers import Flatten
from wallaroo.pipeline import Pipeline
from wallaroo.deployment_config import DeploymentConfigBuilder
from wallaroo.framework import Framework
Open a Connection to Wallaroo
The next step is connect to Wallaroo through the Wallaroo client. The Python library is included in the Wallaroo install and available through the Jupyter Hub interface provided with your Wallaroo environment.
This is accomplished using the wallaroo.Client()
command, which provides a URL to grant the SDK permission to your specific Wallaroo environment. When displayed, enter the URL into a browser and confirm permissions. Store the connection into a variable that can be referenced later.
If logging into the Wallaroo instance through the internal JupyterHub service, use wl = wallaroo.Client()
. If logging in externally, update the wallarooPrefix
and wallarooSuffix
variables with the proper DNS information. For more information on Wallaroo DNS settings, see the Wallaroo DNS Integration Guide.
wl = wallaroo.Client()
Set Variables
We’ll set the name of our workspace, pipeline, models and files. Workspace names must be unique across the Wallaroo workspace. For this, we’ll add in a randomly generated 4 characters to the workspace name to prevent collisions with other users’ workspaces. If running this tutorial, we recommend hard coding the workspace name so it will function in the same workspace each time it’s run.
workspace_name = f'vgg16-clustering-workspace'
pipeline_name = f'vgg16-clustering-pipeline'
model_name = 'vgg16-clustering'
model_file_name = './models/model-auto-conversion-BYOP-vgg16-clustering.zip'
Create Workspace and Pipeline
We will now create the Wallaroo workspace to store our model and set it as the current workspace. Future commands will default to this workspace for pipeline creation, model uploads, etc. We’ll create our Wallaroo pipeline that is used to deploy our arbitrary Python model.
workspace = wl.get_workspace(name=workspace_name, create_if_not_exist=True)
wl.set_current_workspace(workspace)
pipeline = wl.build_pipeline(pipeline_name)
Upload Arbitrary Python Model
Arbitrary Python models are uploaded to Wallaroo through the Wallaroo Client upload_model
method.
Upload Arbitrary Python Model Parameters
The following parameters are required for Arbitrary Python models. Note that while some fields are considered as optional for the upload_model
method, they are required for proper uploading of a Arbitrary Python model to Wallaroo.
Parameter | Type | Description |
---|---|---|
name | string (Required) | The name of the model. Model names are unique per workspace. Models that are uploaded with the same name are assigned as a new version of the model. |
path | string (Required) | The path to the model file being uploaded. |
framework | string (Upload Method Optional, Arbitrary Python model Required) | Set as Framework.CUSTOM . |
input_schema | pyarrow.lib.Schema (Upload Method Optional, Arbitrary Python model Required) | The input schema in Apache Arrow schema format. |
output_schema | pyarrow.lib.Schema (Upload Method Optional, Arbitrary Python model Required) | The output schema in Apache Arrow schema format. |
convert_wait | bool (Upload Method Optional, Arbitrary Python model Optional) (Default: True) |
|
Once the upload process starts, the model is containerized by the Wallaroo instance. This process may take up to 10 minutes.
Upload Arbitrary Python Model Return
The following is returned with a successful model upload and conversion.
Field | Type | Description |
---|---|---|
name | string | The name of the model. |
version | string | The model version as a unique UUID. |
file_name | string | The file name of the model as stored in Wallaroo. |
image_path | string | The image used to deploy the model in the Wallaroo engine. |
last_update_time | DateTime | When the model was last updated. |
For our example, we’ll start with setting the input_schema
and output_schema
that is expected by our ImageClustering._predict()
method.
input_schema = pa.schema([
pa.field('images', pa.list_(
pa.list_(
pa.list_(
pa.int64(),
list_size=3
),
list_size=32
),
list_size=32
)),
])
output_schema = pa.schema([
pa.field('predictions', pa.int64()),
])
Upload Model
Now we’ll upload our model. The framework is Framework.CUSTOM
for arbitrary Python models, and we’ll specify the input and output schemas for the upload.
model = wl.upload_model(model_name,
model_file_name,
framework=Framework.CUSTOM,
input_schema=input_schema,
output_schema=output_schema,
convert_wait=False)
# time to finish the auto-packaging
import time
time.sleep(120)
#verify the model is ready
model = wl.get_model(model_name)
model
Name | vgg16-clustering |
Version | d6f8207e-5e05-4d69-b8fd-40cf1ff422f2 |
File Name | model-auto-conversion-BYOP-vgg16-clustering.zip |
SHA | 58e49d43c18312c9773f6a237409eb26c9f9f20be65b0edd4e823bee5b95eb75 |
Status | ready |
Image Path | proxy.replicated.com/proxy/wallaroo/ghcr.io/wallaroolabs/mac-deploy:v2024.2.0-main-5455 |
Architecture | x86 |
Acceleration | none |
Updated At | 2024-31-Jul 14:54:48 |
Workspace id | 19 |
Workspace name | vgg16-clustering-workspace |
model.config().runtime()
'flight'
Deploy Pipeline
The model is uploaded and ready for use. We’ll add it as a step in our pipeline, then deploy the pipeline. For this example we’re allocated 0.25 cpu and 4 Gi RAM to the pipeline through the pipeline’s deployment configuration.
pipeline.add_model_step(model)
name | vgg16-clustering-pipeline |
---|---|
created | 2024-07-31 14:54:00.841249+00:00 |
last_updated | 2024-07-31 14:54:00.841249+00:00 |
deployed | (none) |
workspace_id | 19 |
workspace_name | vgg16-clustering-workspace |
arch | None |
accel | None |
tags | |
versions | 92d5c219-10ff-4426-baf5-809f3807b42b |
steps | |
published | False |
deployment_config = DeploymentConfigBuilder() \
.cpus(0.25).memory('4Gi') \
.build()
pipeline.deploy(deployment_config=deployment_config)
pipeline.status()
{'status': 'Running',
'details': [],
'engines': [{'ip': '10.28.1.37',
'name': 'engine-8df9df74f-sp66t',
'status': 'Running',
'reason': None,
'details': [],
'pipeline_statuses': {'pipelines': [{'id': 'vgg16-clustering-pipeline',
'status': 'Running',
'version': '6e868401-ab85-41b0-ae86-577899886e96'}]},
'model_statuses': {'models': [{'name': 'vgg16-clustering',
'sha': '58e49d43c18312c9773f6a237409eb26c9f9f20be65b0edd4e823bee5b95eb75',
'status': 'Running',
'version': 'd6f8207e-5e05-4d69-b8fd-40cf1ff422f2'}]}}],
'engine_lbs': [{'ip': '10.28.1.36',
'name': 'engine-lb-6b59985857-ms6w7',
'status': 'Running',
'reason': None,
'details': []}],
'sidekicks': [{'ip': '10.28.1.38',
'name': 'engine-sidekick-vgg16-clustering-31-6b7fdd78bf-cdxzv',
'status': 'Running',
'reason': None,
'details': [],
'statuses': '\n'}]}
pipeline.status()
{'status': 'Running',
'details': [],
'engines': [{'ip': '10.28.1.37',
'name': 'engine-8df9df74f-sp66t',
'status': 'Running',
'reason': None,
'details': [],
'pipeline_statuses': {'pipelines': [{'id': 'vgg16-clustering-pipeline',
'status': 'Running',
'version': '6e868401-ab85-41b0-ae86-577899886e96'}]},
'model_statuses': {'models': [{'name': 'vgg16-clustering',
'sha': '58e49d43c18312c9773f6a237409eb26c9f9f20be65b0edd4e823bee5b95eb75',
'status': 'Running',
'version': 'd6f8207e-5e05-4d69-b8fd-40cf1ff422f2'}]}}],
'engine_lbs': [{'ip': '10.28.1.36',
'name': 'engine-lb-6b59985857-ms6w7',
'status': 'Running',
'reason': None,
'details': []}],
'sidekicks': [{'ip': '10.28.1.38',
'name': 'engine-sidekick-vgg16-clustering-31-6b7fdd78bf-cdxzv',
'status': 'Running',
'reason': None,
'details': [],
'statuses': '\n'}]}
Run inference
Everything is in place - we’ll now run a sample inference with some toy data. In this case we’re randomly generating some values in the data shape the model expects, then submitting an inference request through our deployed pipeline.
input_data = {
"images": [np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8)] * 2,
}
dataframe = pd.DataFrame(input_data)
dataframe
images | |
---|---|
0 | [[[228, 254, 5], [182, 238, 111], [230, 71, 23... |
1 | [[[228, 254, 5], [182, 238, 111], [230, 71, 23... |
pipeline.infer(dataframe, timeout=10000)
time | in.images | out.predictions | anomaly.count | |
---|---|---|---|---|
0 | 2024-07-31 14:56:43.210 | [[[228, 254, 5], [182, 238, 111], [230, 71, 23... | 1 | 0 |
1 | 2024-07-31 14:56:43.210 | [[[228, 254, 5], [182, 238, 111], [230, 71, 23... | 1 | 0 |
Undeploy Pipelines
The inference is successful, so we will undeploy the pipeline and return the resources back to the cluster.
pipeline.undeploy()
name | vgg16-clustering-pipeline |
---|---|
created | 2024-07-31 14:54:00.841249+00:00 |
last_updated | 2024-07-31 14:56:07.967336+00:00 |
deployed | False |
workspace_id | 19 |
workspace_name | vgg16-clustering-workspace |
arch | x86 |
accel | none |
tags | |
versions | 6e868401-ab85-41b0-ae86-577899886e96, 92d5c219-10ff-4426-baf5-809f3807b42b |
steps | vgg16-clustering |
published | False |