Cifar10 Drift Detection

In this example we will deploy an image classification model along with a drift detector trained on the same dataset. For in depth details on creating a drift detection model for your own dataset see the alibi-detect project and associated documentation. You can find details for this CIFAR10 example in their documentation as well.

Prequisites:

Tested on GKE with Knative 0.13 and Istio 1.3.1

[ ]:
!pip install -r requirements_notebook.txt

Ensure gateway installed

[ ]:
!kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml

Setup Resources

Enabled eventing on default namespace. This will activate a default Knative Broker.

[ ]:
!kubectl label namespace default knative-eventing-injection=enabled

Create a Knative service to log events it receives. This will be the example final sink for outlier events.

[ ]:
!pygmentize message-dumper.yaml
[ ]:
!kubectl apply -f message-dumper.yaml

Create the SeldonDeployment image classification model for Cifar10. We add in a logger for requests - the default destination is the namespace Knative Broker.

[ ]:
!pygmentize cifar10.yaml
[ ]:
!kubectl apply -f cifar10.yaml

Create the pretrained Drift Detector. We forward replies to the message-dumper we started. Notice the drift_batch_size. The drift detector will wait until drify_batch_size number of requests are received before making a drift prediction.

[ ]:
!pygmentize cifar10cd.yaml
[ ]:
!kubectl apply -f cifar10cd.yaml

Create a Knative trigger to forward logging events to our Outlier Detector.

[ ]:
!pygmentize trigger.yaml
[ ]:
!kubectl apply -f trigger.yaml

Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer.

[ ]:
CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
CLUSTER_IP=CLUSTER_IPS[0]
print(CLUSTER_IP)
[ ]:
SERVICE_HOSTNAMES=!(kubectl get ksvc drift-detector -o jsonpath='{.status.url}' | cut -d "/" -f 3)
SERVICE_HOSTNAME_CD=SERVICE_HOSTNAMES[0]
print(SERVICE_HOSTNAME_CD)
[ ]:
import matplotlib.pyplot as plt
import numpy as np
import requests
import json
import tensorflow as tf
tf.keras.backend.clear_session()

train, test = tf.keras.datasets.cifar10.load_data()
X_train, y_train = train
X_test, y_test = test

X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32') / 255
print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
classes = ('plane', 'car', 'bird', 'cat',
           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

def show(X):
    plt.imshow(X.reshape(32, 32, 3))
    plt.axis('off')
    plt.show()

def predict(X):
    formData = {
    'instances': X.tolist()
    }
    headers = {}
    res = requests.post('http://'+CLUSTER_IP+'/seldon/default/tfserving-cifar10/v1/models/resnet32/:predict', json=formData, headers=headers)
    if res.status_code == 200:
        j = res.json()
        if len(j["predictions"]) == 1:
            return classes[np.array(j["predictions"])[0].argmax()]
    else:
        print("Failed with ",res.status_code)
        return []

def drift(X):
    formData = {
    'instances': X.tolist()
    }
    headers = {}
    headers["Host"] = SERVICE_HOSTNAME_CD
    res = requests.post('http://'+CLUSTER_IP+'/', json=formData, headers=headers)
    if res.status_code == 200:
        od = res.json()
        return od
    else:
        print("Failed with ",res.status_code)
        return []

Normal Prediction

[ ]:
idx = 1
X = X_train[idx:idx+1]
show(X)
predict(X)

Test Drift

We need to accumulate a large enough batch size so no drift will be tested as yet.

[ ]:
!kubectl logs $(kubectl get pod -l serving.knative.dev/configuration=message-dumper -o jsonpath='{.items[0].metadata.name}') user-container

We will now send 5000 requests to the model in batches. The drift detector will run at the end of this as we set the drift_batch_size to 5000 in our yaml above.

[ ]:
from tqdm.notebook import tqdm
for i in tqdm(range(0,5000,100)):
    X = X_train[i:i+100]
    predict(X)

Let’s check the message dumper and extract the first drift result.

[ ]:
res=!kubectl logs $(kubectl get pod -l serving.knative.dev/configuration=message-dumper -o jsonpath='{.items[0].metadata.name}') user-container
data= []
for i in range(0,len(res)):
    if res[i] == 'Data,':
        data.append(res[i+1])
j = json.loads(json.loads(data[0]))
print("Drift",j["data"]["is_drift"]==1)

Now, let’s create some CIFAR10 examples with motion blur.

[ ]:
from alibi_detect.datasets import fetch_cifar10c, corruption_types_cifar10c
corruption = ['motion_blur']
X_corr, y_corr = fetch_cifar10c(corruption=corruption, severity=5, return_X_y=True)
X_corr = X_corr.astype('float32') / 255
[ ]:
show(X_corr[0])
show(X_corr[1])
show(X_corr[2])

Send these examples to the predictor.

[ ]:
for i in tqdm(range(0,5000,100)):
    X = X_corr[i:i+100]
    predict(X)

Now when we check the message dump we should find a new drift response.

[ ]:
res=!kubectl logs $(kubectl get pod -l serving.knative.dev/configuration=message-dumper -o jsonpath='{.items[0].metadata.name}') user-container
data= []
for i in range(0,len(res)):
    if res[i] == 'Data,':
        data.append(res[i+1])
j = json.loads(json.loads(data[1]))
print("Drift",j["data"]["is_drift"]==1)

Tear Down

[ ]:
!kubectl delete -f cifar10.yaml
!kubectl delete -f cifar10cd.yaml
!kubectl delete -f trigger.yaml
!kubectl delete -f message-dumper.yaml
[ ]: