{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Amazon SageMaker Clarify Model Explainability Monitor - JSON Lines Format" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "This notebook's CI test result for us-west-2 is as follows. CI test results in other regions can be found at the end of the notebook. \n", "\n", "![This us-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-west-2/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Runtime\n", "\n", "This notebook takes approximately 60 minutes to run." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Contents\n", "\n", "* [Introduction](#Introduction)\n", "* [General Setup](#General-Setup)\n", " * [Imports](#Imports)\n", " * [Handful of configuration](#Handful-of-configuration)\n", " * [Model file and data files](#Model-file-and-data-files)\n", "* [Real-time Inference Endpoint](#Real-time-Inference-Endpoint)\n", " * [Deploy the model to an endpoint](#Deploy-the-model-to-an-endpoint)\n", " * [Invoke the endpoint](#Invoke-the-endpoint)\n", " * [Example: Single record](#Example:-Single-record)\n", " * [Example: Two records](#Example:-Two-records)\n", " * [View captured data](#View-captured-data)\n", " * [Start generating some artificial traffic](#Start-generating-some-artificial-traffic)\n", "* [Model Explainability Monitor](#Model-Explainability-Monitor)\n", " * [Baselining job](#Baselining-job)\n", " * [Configurations](#Configurations)\n", " * [Kick off baselining job](#Kick-off-baselining-job)\n", " * [Monitoring Schedule](#Monitoring-Schedule)\n", " * [Wait for the first execution](#Wait-for-the-first-execution)\n", " * [Wait for the execution to finish](#Wait-for-the-execution-to-finish)\n", " * [Inspect execution results](#Inspect-execution-results)\n", "* [Cleanup](#Cleanup)" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "## Introduction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Amazon SageMaker Model Monitor](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor.html) continuously monitors the quality of Amazon SageMaker machine learning models in production. It enables developers to set alerts for when there are deviations in the model quality. Early and pro-active detection of these deviations enables corrective actions, such as retraining models, auditing upstream systems, or fixing data quality issues without having to monitor models manually or build additional tooling. \n", "\n", "[Amazon SageMaker Clarify Model Explainability Monitor](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-feature-attribution-drift.html) is a model monitor that helps data scientists and ML engineers monitor predictions for feature attribution drift on a regular basis. A drift in the distribution of live data for models in production can result in a corresponding drift in the feature attribution values. As the model is monitored, customers can view exportable reports and graphs detailing feature attributions in SageMaker Studio and configure alerts in Amazon CloudWatch to receive notifications if it is detected that the attribution values drift beyond a certain threshold. \n", "\n", "This notebook demonstrates the process for setting up a model monitor for continuous monitoring of feature attribution drift of a [SageMaker real-time inference endpoint](https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints.html). The model input and output are in [SageMaker JSON Lines dense format](https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html#common-in-formats). SageMaker Clarify model monitor also supports analyzing CSV data, which is illustrated in [another notebook](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker_model_monitor/fairness_and_explainability/SageMaker-Model-Monitor-Fairness-and-Explainability.ipynb).\n", "\n", "In general, you can use the model explainability monitor for real-time inference endpoint in this way,\n", "\n", "1. Enable the endpoint for data capture. Then, when the customer invokes the endpoint, the endpoint saves the invocations to a data capture S3 location. \n", "1. Schedule a model explainability monitor to monitor the endpoint (to be more specific, the data capture S3 location) and a ground truth S3 location.\n", "\n", "The monitor executes processing jobs regularly to do feature attribution analysis, and then generate analysis reports and publish metrics to CloudWatch." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## General Setup" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The notebook uses the [SageMaker Python SDK](https://github.com/aws/sagemaker-python-sdk). The following cell upgrades the SDK and its dependencies. Then you may need to restart the kernel and rerun the notebook to pick up the up-to-date APIs, if the notebook is executed in the SageMaker Studio." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -U sagemaker\n", "!pip install -U boto3\n", "!pip install -U botocore" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Imports\n", "\n", "The following cell imports the APIs to be used by the notebook." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import sagemaker\n", "import pandas as pd\n", "import copy\n", "import datetime\n", "import json\n", "import random\n", "import threading\n", "import time\n", "import pprint" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Handful of configuration\n", "\n", "To begin, ensure that these prerequisites have been completed.\n", "\n", "* Specify an AWS Region to host the model.\n", "* Specify an IAM role to execute jobs.\n", "* Define the S3 URIs that stores the model file, input data and output data. For demonstration purposes, this notebook uses the same bucket for them. In reality, they could be separated with different security policies." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AWS region: us-west-2\n", "RoleArn: arn:aws:iam::000000000000:role/service-role/AmazonSageMaker-ExecutionRole-20200714T163791\n", "Demo Bucket: sagemaker-us-west-2-000000000000\n", "Demo Prefix: sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04\n", "Demo S3 key: s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04\n", "The endpoint will save the captured data to: s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/data-capture\n", "The baselining job will save the analysis results to: s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/baselining-output\n", "The monitor will save the analysis results to: s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/monitor-output\n" ] } ], "source": [ "sagemaker_session = sagemaker.Session()\n", "\n", "region = sagemaker_session.boto_region_name\n", "print(f\"AWS region: {region}\")\n", "\n", "role = sagemaker.get_execution_role()\n", "print(f\"RoleArn: {role}\")\n", "\n", "# A different bucket can be used, but make sure the role for this notebook has\n", "# the s3:PutObject permissions. This is the bucket into which the data is captured\n", "bucket = sagemaker_session.default_bucket()\n", "print(f\"Demo Bucket: {bucket}\")\n", "prefix = sagemaker.utils.unique_name_from_base(\"sagemaker/DEMO-ClarifyModelMonitor\")\n", "print(f\"Demo Prefix: {prefix}\")\n", "s3_key = f\"s3://{bucket}/{prefix}\"\n", "print(f\"Demo S3 key: {s3_key}\")\n", "\n", "data_capture_s3_uri = f\"{s3_key}/data-capture\"\n", "baselining_output_s3_uri = f\"{s3_key}/baselining-output\"\n", "monitor_output_s3_uri = f\"{s3_key}/monitor-output\"\n", "\n", "print(f\"The endpoint will save the captured data to: {data_capture_s3_uri}\")\n", "print(f\"The baselining job will save the analysis results to: {baselining_output_s3_uri}\")\n", "print(f\"The monitor will save the analysis results to: {monitor_output_s3_uri}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Model file and data files\n", "\n", "This example includes a prebuilt [SageMaker Linear Learner](https://docs.aws.amazon.com/sagemaker/latest/dg/linear-learner.html) model trained by [a SageMaker Clarify offline processing example notebook](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-clarify/fairness_and_explainability/fairness_and_explainability_jsonlines_format.ipynb). The model supports [SageMaker JSON Lines dense format](https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html#common-in-formats) (MIME type `\"application/jsonlines\"`).\n", "\n", "* The model input can one or more lines, each line is a JSON object that has a \"features\" key pointing to a list of feature values concerning demographic characteristics of individuals. For example,\n", "\n", "```\n", "{\"features\":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}\n", "{\"features\":[43,2,72338,12,14,2,12,0,1,1,0,0,40,37]}\n", "```\n", "\n", "* The model output has the predictions of whether a person has a yearly income that is more than $50,000. Each prediction is a JSON object that has a \"predicted_label\" key pointing to the predicted label, and the \"score\" key pointing to the confidence score. For example,\n", "\n", "```\n", "{\"predicted_label\":1,\"score\":0.989977359771728}\n", "{\"predicted_label\":1,\"score\":0.504138827323913}\n", "```" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "model_file = \"model/ll-adult-prediction-model.tar.gz\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example includes two dataset files, both in the JSON Lines format. The data also originates from [the SageMaker Clarify offline processing example notebook](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-clarify/fairness_and_explainability/fairness_and_explainability_jsonlines_format.ipynb)." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "train_dataset_path = \"test_data/validation-dataset.jsonl\"\n", "test_dataset_path = \"test_data/test-dataset.jsonl\"\n", "dataset_type = \"application/jsonlines\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The train dataset has the features and the ground truth label (pointed to by the key \"label\")," ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\"features\":[41,2,220531,14,15,2,9,0,4,1,0,0,60,38],\"label\":1}\n", "{\"features\":[33,2,35378,9,13,2,11,5,4,0,0,0,45,38],\"label\":1}\n", "{\"features\":[36,2,223433,12,14,2,11,0,4,1,7688,0,50,38],\"label\":1}\n", "{\"features\":[40,2,220589,7,12,4,0,1,4,0,0,0,40,38],\"label\":0}\n", "{\"features\":[30,2,231413,15,10,2,2,0,4,1,0,0,40,38],\"label\":1}\n" ] } ], "source": [ "!head -n 5 $train_dataset_path" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The test dataset only has features." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\"features\":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}\n", "{\"features\":[43,2,72338,12,14,2,12,0,1,1,0,0,40,37]}\n", "{\"features\":[34,2,162604,11,9,4,2,2,2,1,0,0,40,37]}\n", "{\"features\":[20,2,258509,11,9,4,6,3,2,1,0,0,40,37]}\n", "{\"features\":[27,2,446947,9,13,4,0,4,2,0,0,0,55,37]}\n" ] } ], "source": [ "!head -n 5 $test_dataset_path" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here are the headers of the train dataset. \"Target\" is the header of the ground truth label, and the others are the feature headers. They will be used to beautify the analysis report." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "all_headers = [\n", " \"Age\",\n", " \"Workclass\",\n", " \"fnlwgt\",\n", " \"Education\",\n", " \"Education-Num\",\n", " \"Marital Status\",\n", " \"Occupation\",\n", " \"Relationship\",\n", " \"Ethnic group\",\n", " \"Sex\",\n", " \"Capital Gain\",\n", " \"Capital Loss\",\n", " \"Hours per week\",\n", " \"Country\",\n", " \"Target\",\n", "]\n", "label_header = all_headers[-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To verify that the execution role for this notebook has the necessary permissions to proceed, put a simple test object into the S3 bucket specified above. If this command fails, update the role to have `s3:PutObject` permission on the bucket and try again." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success! We are all set to proceed with uploading to S3.\n" ] } ], "source": [ "sagemaker.s3.S3Uploader.upload_string_as_file_body(\n", " body=\"hello\",\n", " desired_s3_uri=f\"{s3_key}/upload-test-file.txt\",\n", " sagemaker_session=sagemaker_session,\n", ")\n", "print(\"Success! We are all set to proceed with uploading to S3.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then upload the files to S3 so that they can be used by SageMaker." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model file has been uploaded to s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/ll-adult-prediction-model.tar.gz\n", "Train data is uploaded to: s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/validation-dataset.jsonl\n", "Test data is uploaded to: s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/test-dataset.jsonl\n" ] } ], "source": [ "model_url = sagemaker.s3.S3Uploader.upload(\n", " local_path=model_file,\n", " desired_s3_uri=s3_key,\n", " sagemaker_session=sagemaker_session,\n", ")\n", "print(f\"Model file has been uploaded to {model_url}\")\n", "\n", "train_data_s3_uri = sagemaker.s3.S3Uploader.upload(\n", " local_path=train_dataset_path,\n", " desired_s3_uri=s3_key,\n", " sagemaker_session=sagemaker_session,\n", ")\n", "print(f\"Train data is uploaded to: {train_data_s3_uri}\")\n", "test_data_s3_uri = sagemaker.s3.S3Uploader.upload(\n", " local_path=test_dataset_path,\n", " desired_s3_uri=s3_key,\n", " sagemaker_session=sagemaker_session,\n", ")\n", "print(f\"Test data is uploaded to: {test_data_s3_uri}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Real-time Inference Endpoint\n", "\n", "This section creates a SageMaker real-time inference endpoint to showcase the data capture capability in action. The model monitor will be scheduled for the endpoint and process the captured data.\n" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "### Deploy the model to an endpoint\n", "\n", "Start with deploying the pre-trained model. Here, create a SageMaker `Model` object with the inference image and model file. Then deploy the model with the data capture configuration and wait until the endpoint is ready to serve traffic.\n", "\n", "[DataCaptureConfig](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.data_capture_config.DataCaptureConfig) enables capturing the request payload and the response payload of the endpoint. Payloads are typically treated as binary data and encoded in BASE64 by default, allowing them to be stored in capture data files. However, by specifying the data format in the `json_content_types` parameter as shown below, the payloads can be captured as plain text instead." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SageMaker model name: DEMO-ll-adult-pred-model-monitor-1674106124-9611\n", "SageMaker endpoint name: DEMO-ll-adult-pred-model-monitor-1674106124-9611\n", "SageMaker Linear Learner image: 174872318107.dkr.ecr.us-west-2.amazonaws.com/linear-learner:1\n" ] } ], "source": [ "model_name = sagemaker.utils.unique_name_from_base(\"DEMO-ll-adult-pred-model-monitor\")\n", "endpoint_name = model_name\n", "print(f\"SageMaker model name: {model_name}\")\n", "print(f\"SageMaker endpoint name: {endpoint_name}\")\n", "\n", "image_uri = sagemaker.image_uris.retrieve(\"linear-learner\", region, \"1\")\n", "print(f\"SageMaker Linear Learner image: {image_uri}\")\n", "\n", "model = sagemaker.model.Model(\n", " role=role,\n", " name=model_name,\n", " image_uri=image_uri,\n", " model_data=model_url,\n", " sagemaker_session=sagemaker_session,\n", ")\n", "\n", "data_capture_config = sagemaker.model_monitor.DataCaptureConfig(\n", " enable_capture=True,\n", " sampling_percentage=100, # Capture 100% of the traffic\n", " destination_s3_uri=data_capture_s3_uri,\n", " json_content_types=[dataset_type],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**NOTE**: The following cell takes about 10 minutes to deploy the model." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deploying model DEMO-ll-adult-pred-model-monitor-1674106124-9611 to endpoint DEMO-ll-adult-pred-model-monitor-1674106124-9611\n", "------!" ] } ], "source": [ "print(f\"Deploying model {model_name} to endpoint {endpoint_name}\")\n", "model.deploy(\n", " initial_instance_count=1,\n", " instance_type=\"ml.m5.xlarge\",\n", " endpoint_name=endpoint_name,\n", " data_capture_config=data_capture_config,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Invoke the endpoint\n", "\n", "Now send data to this endpoint to get inferences in real time. The model supports mini-batch predictions, so you can put one or more records to a single request." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "with open(test_dataset_path, \"r\") as f:\n", " test_data = f.read().splitlines()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Example: Single record" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Request payload:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\"features\":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}\n" ] } ], "source": [ "request_payload = test_data[0]\n", "print(request_payload)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Response payload:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"predicted_label\":1,\"score\":0.989977359771728}\\n'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "response = sagemaker_session.sagemaker_runtime_client.invoke_endpoint(\n", " EndpointName=endpoint_name,\n", " ContentType=dataset_type,\n", " Accept=dataset_type,\n", " Body=request_payload,\n", ")\n", "response_payload = response[\"Body\"].read().decode(\"utf-8\")\n", "response_payload" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Example: Two records" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Request payload:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"features\":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}\\n{\"features\":[43,2,72338,12,14,2,12,0,1,1,0,0,40,37]}'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "request_payload = \"\\n\".join(test_data[:2])\n", "request_payload" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Response payload:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"predicted_label\":1,\"score\":0.989977359771728}\\n{\"predicted_label\":1,\"score\":0.504138827323913}\\n'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "response = sagemaker_session.sagemaker_runtime_client.invoke_endpoint(\n", " EndpointName=endpoint_name,\n", " ContentType=dataset_type,\n", " Accept=dataset_type,\n", " Body=request_payload,\n", ")\n", "response_payload = response[\"Body\"].read().decode(\"utf-8\")\n", "response_payload" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### View captured data\n", "\n", "Because data capture is enabled in the previous steps, the request and response payload, along with some additional metadata, are saved in the Amazon S3 location specified in the [DataCaptureConfig](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.data_capture_config.DataCaptureConfig).\n", "\n", "Now list the captured data files stored in Amazon S3. There should be different files from different time periods organized based on the hour in which the invocation occurred. The format of the Amazon S3 path is:\n", "\n", "`s3://{data_capture_s3_uri}/{endpoint_name}/{variant-name}/yyyy/mm/dd/hh/filename.jsonl`" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Waiting for captured data to show up............................................................\n", "Found capture data files:\n", "s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/data-capture/DEMO-ll-adult-pred-model-monitor-1674106124-9611/AllTraffic/2023/01/19/05/31-46-585-9ee7358c-33e7-467d-9133-624e448e6552.jsonl\n" ] } ], "source": [ "print(\"Waiting for captured data to show up\", end=\"\")\n", "for _ in range(120):\n", " captured_data_files = sorted(\n", " sagemaker.s3.S3Downloader.list(\n", " s3_uri=f\"{data_capture_s3_uri}/{endpoint_name}\",\n", " sagemaker_session=sagemaker_session,\n", " )\n", " )\n", " if captured_data_files:\n", " break\n", " print(\".\", end=\"\", flush=True)\n", " time.sleep(1)\n", "print()\n", "print(\"Found capture data files:\")\n", "print(\"\\n \".join(captured_data_files[-5:]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, view the content of a single capture file." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\"captureData\":{\"endpointInput\":{\"observedContentType\":\"application/jsonlines\",\"mode\":\"INPUT\",\"data\":\"{\\\"features\\\":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}\",\"encoding\":\"JSON\"},\"endpointOutput\":{\"observedContentType\":\"application/jsonlines\",\"mode\":\"OUTPUT\",\"data\":\"{\\\"predicted_label\\\":1,\\\"score\\\":0.989977359771728}\\n\",\"encoding\":\"JSON\"}},\"eventMetadata\":{\"eventId\":\"40394cfe-37c3-4abb-b22c-dd7accbe9608\",\"inferenceTime\":\"2023-01-19T05:31:46Z\"},\"eventVersion\":\"0\"}\n", "{\"captureData\":{\"endpointInput\":{\"observedContentType\":\"application/jsonlines\",\"mode\":\"INPUT\",\"data\":\"{\\\"features\\\":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}\\n{\\\"features\\\":[43,2,72338,12,14,2,12,0,1,1,0,0,40,37]}\",\"encoding\":\"JSON\"},\"endpointOutput\":{\"observedContentType\":\"application/jsonlines\",\"mode\":\"OUTPUT\",\"data\":\"{\\\"predicted_label\\\":1,\\\"score\\\":0.989977359771728}\\n{\\\"predicted_label\\\":1,\\\"score\\\":0.504138827323913}\\n\",\"encoding\":\"JSON\"}},\"eventMetadata\":{\"eventId\":\"32aaea1b-1a60-4870-b81d-40271f950c4a\",\"inferenceTime\":\"2023-01-19T05:31:46Z\"},\"eventVersion\":\"0\"}\n", "\n" ] } ], "source": [ "captured_data = sagemaker.s3.S3Downloader.read_file(\n", " s3_uri=captured_data_files[-1],\n", " sagemaker_session=sagemaker_session,\n", ")\n", "print(captured_data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, the contents of a single line is present below in formatted JSON to observe a little better.\n", "\n", "* `captureData` has two fields, `endpointInput` has the captured invocation request, and `endpointOutput` has the response.\n", "* `eventMetadata` has the inference ID and event ID." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"captureData\": {\n", " \"endpointInput\": {\n", " \"observedContentType\": \"application/jsonlines\",\n", " \"mode\": \"INPUT\",\n", " \"data\": \"{\\\"features\\\":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}\\n{\\\"features\\\":[43,2,72338,12,14,2,12,0,1,1,0,0,40,37]}\",\n", " \"encoding\": \"JSON\"\n", " },\n", " \"endpointOutput\": {\n", " \"observedContentType\": \"application/jsonlines\",\n", " \"mode\": \"OUTPUT\",\n", " \"data\": \"{\\\"predicted_label\\\":1,\\\"score\\\":0.989977359771728}\\n{\\\"predicted_label\\\":1,\\\"score\\\":0.504138827323913}\\n\",\n", " \"encoding\": \"JSON\"\n", " }\n", " },\n", " \"eventMetadata\": {\n", " \"eventId\": \"32aaea1b-1a60-4870-b81d-40271f950c4a\",\n", " \"inferenceTime\": \"2023-01-19T05:31:46Z\"\n", " },\n", " \"eventVersion\": \"0\"\n", "}\n" ] } ], "source": [ "print(json.dumps(json.loads(captured_data.splitlines()[-1]), indent=4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Start generating some artificial traffic\n", "The cell below starts a thread to send some traffic to the endpoint. If there is no traffic, the monitoring jobs are marked as `Failed` since there is no data to process.\n", "\n", "Notice the `InferenceId` attribute used to invoke, in this example, it will be used to join the captured data with the ground truth data. If it is not available, then the `eventId` will be used for the join operation." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "class WorkerThread(threading.Thread):\n", " def __init__(self, do_run, *args, **kwargs):\n", " super(WorkerThread, self).__init__(*args, **kwargs)\n", " self.__do_run = do_run\n", " self.__terminate_event = threading.Event()\n", "\n", " def terminate(self):\n", " self.__terminate_event.set()\n", "\n", " def run(self):\n", " while not self.__terminate_event.is_set():\n", " self.__do_run(self.__terminate_event)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "def invoke_endpoint(terminate_event):\n", " for index, record in enumerate(test_data):\n", " response = sagemaker_session.sagemaker_runtime_client.invoke_endpoint(\n", " EndpointName=endpoint_name,\n", " ContentType=dataset_type,\n", " Accept=dataset_type,\n", " Body=record,\n", " InferenceId=str(index), # unique ID per row\n", " )\n", " response[\"Body\"].read()\n", " time.sleep(1)\n", " if terminate_event.is_set():\n", " break\n", "\n", "\n", "# Keep invoking the endpoint with test data\n", "invoke_endpoint_thread = WorkerThread(do_run=invoke_endpoint)\n", "invoke_endpoint_thread.start()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Model Explainability Monitor\n", "\n", "Similar to the other monitoring types, the standard procedure of creating a [feature attribution drift monitor](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-feature-attribution-drift.html) is first run a baselining job, and then schedule the monitor." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "model_explainability_monitor = sagemaker.model_monitor.ModelExplainabilityMonitor(\n", " role=role,\n", " sagemaker_session=sagemaker_session,\n", " max_runtime_in_seconds=3600,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Baselining job\n", "\n", "A baselining job runs predictions on training dataset and suggests constraints. The `suggest_baseline()` method of `ModelExplainabilityMonitor` starts a SageMaker Clarify processing job to generate the constraints.\n", "\n", "The step is not mandatory, but providing constraints file to the monitor can enable violations file generation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Configurations\n", "\n", "Information about the input data need to be provided to the processor." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`DataConfig` stores information about the dataset to be analyzed. For example, the dataset file and its format (like JSON Lines), where to store the analysis results. Some special things to note about this configuration for the JSON Lines dataset,\n", "\n", "* The parameter value `\"features\"` or `\"label\"` is **NOT** a header string. Instead, it is a `JMESPath` expression ([refer to its specification](https://jmespath.org/specification.html)) that is used to locate the features list or the ground truth label in the dataset (the ground truth label is not needed for the explainability analysis, the parameter is specified so that the job knows it should be excluded from the dataset). In this example notebook they happen to be the same as the keys in the dataset. But for example, if the dataset has records like below, then the `features` parameter should use value `\"data.features.values\"`, and the `label` parameter should use value `\"data.label\"`.\n", "\n", " ```\n", " {\"data\": {\"features\": {\"values\": [25, 2, 226802, 1, 7, 4, 6, 3, 2, 1, 0, 0, 40, 37]}, \"label\": 0}}\n", " ```\n", "\n", "* SageMaker Clarify processing job will load the JSON Lines dataset into tabular representation for further analysis, and the parameter `headers` is the list of column names. **The label header shall be the last one in the headers list**, and the order of feature headers shall be the same as the order of features in a record." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "features_jmespath = \"features\"\n", "ground_truth_label_jmespath = \"label\"\n", "data_config = sagemaker.clarify.DataConfig(\n", " s3_data_input_path=train_data_s3_uri,\n", " s3_output_path=baselining_output_s3_uri,\n", " features=features_jmespath,\n", " label=ground_truth_label_jmespath,\n", " headers=all_headers,\n", " dataset_type=dataset_type,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`ModelConfig` is configuration related to model to be used for inferencing. In order to compute SHAP values, the SageMaker Clarify explainer generates synthetic dataset and then get its predictions for the SageMaker model. To accomplish this, the processing job will use the model to create an ephemeral endpoint (also known as \"shadow endpoint\"). The processing job will delete the shadow endpoint after the computations are completed. One special thing to note about this configuration for the JSON Lines model input and output,\n", "\n", "* `content_template` is used by SageMaker Clarify processing job to convert the tabular data to the request payload acceptable to the shadow endpoint. To be more specific, the placeholder `$features` will be replaced by **the features list** from records. The request payload of a record from the testing dataset happens to be similar to the record itself, like `{\"features\":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}`, because both the dataset and the model input conform to the same format." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "content_template = '{\"features\":$features}'\n", "model_config = sagemaker.clarify.ModelConfig(\n", " model_name=model_name, # The name of the SageMaker model\n", " instance_type=\"ml.m5.xlarge\", # The instance type of the shadow endpoint\n", " instance_count=1, # The instance count of the shadow endpoint\n", " content_type=dataset_type, # The data format of the model input\n", " accept_type=dataset_type, # The data format of the model output\n", " content_template=content_template,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Currently, the SageMaker Clarify explainer offers a scalable and efficient implementation of SHAP, so the explainability config is `SHAPConfig`, including\n", "\n", "* `baseline`: A list of records (at least one) to be used as the baseline dataset in the Kernel SHAP algorithm, each record is JSON object that includes a list of features. It can also be a S3 object URI, the S3 file should be in the same format as dataset.\n", "* `num_samples`: Number of samples to be used in the Kernel SHAP algorithm. This number determines the size of the generated synthetic dataset to compute the SHAP values.\n", "* `agg_method`: Aggregation method for global SHAP values. Valid values are\n", " * \"mean_abs\" (mean of absolute SHAP values for all instances),\n", " * \"median\" (median of SHAP values for all instances) and\n", " * \"mean_sq\" (mean of squared SHAP values for all instances).\n", "* `use_logit`: Indicator of whether the logit function is to be applied to the model predictions. Default is False. If \"use_logit\" is true then the SHAP values will have log-odds units.\n", "* `save_local_shap_values`: Indicator of whether to save the local SHAP values in the output location. Default is True." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SHAP baseline: [{'features': [39, 2, 184870, 10, 10, 3, 6, 1, 4, 1, 1597, 61, 41, 37]}]\n" ] } ], "source": [ "# Here use the mean value of train dataset as SHAP baseline\n", "dataset = []\n", "with open(train_dataset_path) as f:\n", " dataset = [json.loads(row)[\"features\"] for row in f]\n", "mean_values = pd.DataFrame(dataset).mean().round().astype(int).to_list()\n", "mean_record = {\"features\": mean_values}\n", "shap_baseline = [mean_record]\n", "print(f\"SHAP baseline: {shap_baseline}\")\n", "\n", "shap_config = sagemaker.clarify.SHAPConfig(\n", " baseline=shap_baseline,\n", " num_samples=100,\n", " agg_method=\"mean_abs\",\n", " save_local_shap_values=False,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Kick off baselining job\n", "\n", "Call the `suggest_baseline()` method to start the baselining job. The model output has a key \"score\" pointing to a confidence score value between `0` and `1`. So, the `model_scores` parameter is set to the `JMESPath` expression \"score\" which can locate the score in the model output." ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Job Name: baseline-suggestion-job-2023-01-19-05-32-51-896\n", "Inputs: [{'InputName': 'dataset', 'AppManaged': False, 'S3Input': {'S3Uri': 's3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/validation-dataset.jsonl', 'LocalPath': '/opt/ml/processing/input/data', 'S3DataType': 'S3Prefix', 'S3InputMode': 'File', 'S3DataDistributionType': 'FullyReplicated', 'S3CompressionType': 'None'}}, {'InputName': 'analysis_config', 'AppManaged': False, 'S3Input': {'S3Uri': 's3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/baselining-output/analysis_config.json', 'LocalPath': '/opt/ml/processing/input/config', 'S3DataType': 'S3Prefix', 'S3InputMode': 'File', 'S3DataDistributionType': 'FullyReplicated', 'S3CompressionType': 'None'}}]\n", "Outputs: [{'OutputName': 'analysis_result', 'AppManaged': False, 'S3Output': {'S3Uri': 's3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/baselining-output', 'LocalPath': '/opt/ml/processing/output', 'S3UploadMode': 'EndOfJob'}}]\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "confidence_score_jmespath = \"score\"\n", "model_explainability_monitor.suggest_baseline(\n", " explainability_config=shap_config,\n", " data_config=data_config,\n", " model_config=model_config,\n", " model_scores=confidence_score_jmespath, # The JMESPath to locate the confidence score in model output\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**NOTE**: The following cell waits until the baselining job is completed (in about 10 minutes). It then inspects the suggested constraints. This step can be skipped, because the monitor to be scheduled will automatically pick up baselining job name and wait for it before monitoring execution." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "..................................................................................................!\n", "Suggested constraints: s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/baselining-output/analysis.json\n", "{\n", " \"version\": \"1.0\",\n", " \"explanations\": {\n", " \"kernel_shap\": {\n", " \"label0\": {\n", " \"global_shap_values\": {\n", " \"Age\": 0.05962069398767555,\n", " \"Workclass\": 0.009340874120660063,\n", " \"fnlwgt\": 0.0010900750377509304,\n", " \"Education\": 0.014739126275038199,\n", " \"Education-Num\": 0.09891391226656666,\n", " \"Marital Status\": 0.05452765230404344,\n", " \"Occupation\": 0.0025392834714334667,\n", " \"Relationship\": 0.018169508641909988,\n", " \"Ethnic group\": 0.005295263900463686,\n", " \"Sex\": 0.032080828962127876,\n", " \"Capital Gain\": 0.09913318680892579,\n", " \"Capital Loss\": 0.013518474176382519,\n", " \"Hours per week\": 0.03641124946588507,\n", " \"Country\": 0.004894213349476741\n", " },\n", " \"expected_value\": 0.250623226165771\n", " }\n", " }\n", " }\n", "}\n" ] } ], "source": [ "model_explainability_monitor.latest_baselining_job.wait(logs=False)\n", "print()\n", "model_explainability_constraints = model_explainability_monitor.suggested_constraints()\n", "print(f\"Suggested constraints: {model_explainability_constraints.file_s3_uri}\")\n", "print(\n", " sagemaker.s3.S3Downloader.read_file(\n", " s3_uri=model_explainability_constraints.file_s3_uri,\n", " sagemaker_session=sagemaker_session,\n", " )\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Monitoring Schedule\n", "\n", "With above constraints collected, now call `create_monitoring_schedule()` method to schedule an hourly model explainability monitor." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a baselining job has been submitted, then the monitor object will automatically pick up the analysis configuration from the baselining job. But if the baselining step is skipped, or if the capture dataset has different nature than the training dataset, then analysis configuration has to be provided.\n", "\n", "`ModelConfig` is required by `ExplainabilityAnalysisConfig` for the same reason as it is required by the baselining job. Note that only features are required for computing feature attribution, so ground truth label should be excluded.\n", "\n", "Highlights,\n", "\n", "* From `endpoint_name` the monitor can figure out the location of data captured by the endpoint.\n", "* `features_attribute` is the `JMESPath` expression to locate the features in model input, similar to the `features` parameter of `DataConfig`.\n", "* `inference_attribute` stores the `JMESPath` expression to locate the confidence score in model output, similar to the `model_scores` parameter of the `suggest_baseline()` method." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "schedule_expression = sagemaker.model_monitor.CronExpressionGenerator.hourly()" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model explainability monitoring schedule: monitoring-schedule-2023-01-19-05-41-04-758\n" ] } ], "source": [ "# Remove label because only features are required for the analysis\n", "headers_without_label_header = copy.deepcopy(all_headers)\n", "headers_without_label_header.remove(label_header)\n", "model_explainability_analysis_config = sagemaker.model_monitor.ExplainabilityAnalysisConfig(\n", " explainability_config=shap_config,\n", " model_config=model_config,\n", " headers=headers_without_label_header,\n", ")\n", "model_explainability_monitor.create_monitoring_schedule(\n", " analysis_config=model_explainability_analysis_config,\n", " endpoint_input=sagemaker.model_monitor.EndpointInput(\n", " endpoint_name=endpoint_name,\n", " destination=\"/opt/ml/processing/input/endpoint\",\n", " features_attribute=features_jmespath,\n", " inference_attribute=confidence_score_jmespath,\n", " ),\n", " output_s3_uri=monitor_output_s3_uri,\n", " schedule_cron_expression=schedule_expression,\n", ")\n", "print(\n", " f\"Model explainability monitoring schedule: {model_explainability_monitor.monitoring_schedule_name}\"\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Wait for the first execution\n", "\n", "The schedule starts jobs at the previously specified intervals. Code below waits until time crosses the hour boundary (in UTC) to see executions kick off.\n", "\n", "Note: Even for an hourly schedule, Amazon SageMaker has a buffer period of 20 minutes to schedule executions. The execution might start in anywhere from zero to ~20 minutes from the hour boundary. This is expected and done for load balancing in the backend." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "def wait_for_execution_to_start(model_monitor):\n", " print(\n", " \"An hourly schedule was created above and it will kick off executions ON the hour (plus 0 - 20 min buffer).\"\n", " )\n", "\n", " print(\"Waiting for the first execution to happen\", end=\"\")\n", " schedule_desc = model_monitor.describe_schedule()\n", " while \"LastMonitoringExecutionSummary\" not in schedule_desc:\n", " schedule_desc = model_monitor.describe_schedule()\n", " print(\".\", end=\"\", flush=True)\n", " time.sleep(60)\n", " print()\n", " print(\"Done! Execution has been created\")\n", "\n", " print(\"Now waiting for execution to start\", end=\"\")\n", " while schedule_desc[\"LastMonitoringExecutionSummary\"][\"MonitoringExecutionStatus\"] in \"Pending\":\n", " schedule_desc = model_monitor.describe_schedule()\n", " print(\".\", end=\"\", flush=True)\n", " time.sleep(10)\n", "\n", " print()\n", " print(\"Done! Execution has started\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**NOTE**: The following cell waits until the first monitoring execution is started. As explained above, the wait could take more than 60 minutes." ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "An hourly schedule was created above and it will kick off executions ON the hour (plus 0 - 20 min buffer).\n", "Waiting for the first execution to happen........................\n", "Done! Execution has been created\n", "Now waiting for execution to start.\n", "Done! Execution has started\n" ] } ], "source": [ "wait_for_execution_to_start(model_explainability_monitor)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In real world, a monitoring schedule is supposed to be active all the time. But in this example, it can be stopped to avoid incurring extra charges. A stopped schedule will not trigger further executions, but the ongoing execution will continue. And if needed, the schedule can be restarted by `start_monitoring_schedule()`." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Stopping Monitoring Schedule with name: monitoring-schedule-2023-01-19-05-41-04-758\n" ] } ], "source": [ "model_explainability_monitor.stop_monitoring_schedule()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Wait for the execution to finish\n", "\n", "In the previous cell, the first execution has started. This section waits for the execution to finish so that its analysis results are available. Here are the possible terminal states and what each of them mean:\n", "\n", "* `Completed` - This means the monitoring execution completed, and no issues were found in the violations report.\n", "* `CompletedWithViolations` - This means the execution completed, but constraint violations were detected.\n", "* `Failed` - The monitoring execution failed, maybe due to client error (perhaps incorrect role permissions) or infrastructure issues. Further examination of `FailureReason` and `ExitMessage` is necessary to identify what exactly happened.\n", "* `Stopped` - job exceeded max runtime or was manually stopped." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "# Waits for the schedule to have last execution in a terminal status.\n", "def wait_for_execution_to_finish(model_monitor):\n", " schedule_desc = model_monitor.describe_schedule()\n", " execution_summary = schedule_desc.get(\"LastMonitoringExecutionSummary\")\n", " if execution_summary is not None:\n", " print(\"Waiting for execution to finish\", end=\"\")\n", " while execution_summary[\"MonitoringExecutionStatus\"] not in [\n", " \"Completed\",\n", " \"CompletedWithViolations\",\n", " \"Failed\",\n", " \"Stopped\",\n", " ]:\n", " print(\".\", end=\"\", flush=True)\n", " time.sleep(60)\n", " schedule_desc = model_monitor.describe_schedule()\n", " execution_summary = schedule_desc[\"LastMonitoringExecutionSummary\"]\n", " print()\n", " print(f\"Done! Execution Status: {execution_summary['MonitoringExecutionStatus']}\")\n", " else:\n", " print(\"Last execution not found\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**NOTE**: The following cell takes about 10 minutes." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Waiting for execution to finish........\n", "Done! Execution Status: Completed\n" ] } ], "source": [ "wait_for_execution_to_finish(model_explainability_monitor)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Inspect execution results\n", "\n", "List the generated reports,\n", "\n", "* analysis.json includes the global SHAP values.\n", "* report.* files are static report files to visualize the SHAP values." ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Report URI: s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/monitor-output/DEMO-ll-adult-pred-model-monitor-1674106124-9611/monitoring-schedule-2023-01-19-05-41-04-758/2023/01/19/06\n", "Found Report Files:\n", "s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/monitor-output/DEMO-ll-adult-pred-model-monitor-1674106124-9611/monitoring-schedule-2023-01-19-05-41-04-758/2023/01/19/06/analysis.json\n", " s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/monitor-output/DEMO-ll-adult-pred-model-monitor-1674106124-9611/monitoring-schedule-2023-01-19-05-41-04-758/2023/01/19/06/report.html\n", " s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/monitor-output/DEMO-ll-adult-pred-model-monitor-1674106124-9611/monitoring-schedule-2023-01-19-05-41-04-758/2023/01/19/06/report.ipynb\n", " s3://sagemaker-us-west-2-000000000000/sagemaker/DEMO-ClarifyModelMonitor-1674106123-4d04/monitor-output/DEMO-ll-adult-pred-model-monitor-1674106124-9611/monitoring-schedule-2023-01-19-05-41-04-758/2023/01/19/06/report.pdf\n" ] } ], "source": [ "schedule_desc = model_explainability_monitor.describe_schedule()\n", "execution_summary = schedule_desc.get(\"LastMonitoringExecutionSummary\")\n", "if execution_summary and execution_summary[\"MonitoringExecutionStatus\"] in [\n", " \"Completed\",\n", " \"CompletedWithViolations\",\n", "]:\n", " last_model_explainability_monitor_execution = model_explainability_monitor.list_executions()[-1]\n", " last_model_explainability_monitor_execution_report_uri = (\n", " last_model_explainability_monitor_execution.output.destination\n", " )\n", " print(f\"Report URI: {last_model_explainability_monitor_execution_report_uri}\")\n", " last_model_explainability_monitor_execution_report_files = sorted(\n", " sagemaker.s3.S3Downloader.list(\n", " s3_uri=last_model_explainability_monitor_execution_report_uri,\n", " sagemaker_session=sagemaker_session,\n", " )\n", " )\n", " print(\"Found Report Files:\")\n", " print(\"\\n \".join(last_model_explainability_monitor_execution_report_files))\n", "else:\n", " last_model_explainability_monitor_execution = None\n", " print(\n", " \"====STOP==== \\n No completed executions to inspect further. Please wait till an execution completes or investigate previously reported failures.\"\n", " )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If there are any violations compared to the baseline, they are listed here. See [Feature Attribution Drift Violations](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-model-attribution-drift-violations.html) for the schema of the file, and how violations are detected." ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "violations = model_explainability_monitor.latest_monitoring_constraint_violations()\n", "if violations is not None:\n", " pprint.PrettyPrinter(indent=4).pprint(violations.body_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, the analysis results are also published to CloudWatch, see [CloudWatch Metrics for Feature Attribution Drift Analysis](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-feature-attribute-drift-cw.html)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Cleanup\n", "\n", "The endpoint can keep running and capturing data, but if there is no plan to collect more data or use this endpoint further, it should be deleted to avoid incurring additional charges. Note that deleting endpoint does not delete the data that was captured during the model invocations." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First stop the worker thread," ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "invoke_endpoint_thread.terminate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then stop all monitors scheduled for the endpoint" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Stopping Monitoring Schedule with name: monitoring-schedule-2023-01-19-05-41-04-758\n", "Waiting for execution to finish\n", "Done! Execution Status: Completed\n", "\n", "Deleting Monitoring Schedule with name: monitoring-schedule-2023-01-19-05-41-04-758\n" ] } ], "source": [ "model_explainability_monitor.stop_monitoring_schedule()\n", "wait_for_execution_to_finish(model_explainability_monitor)\n", "model_explainability_monitor.delete_monitoring_schedule()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, delete the endpoint" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "sagemaker_session.delete_endpoint(endpoint_name=endpoint_name)\n", "sagemaker_session.delete_model(model_name=model_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Notebook CI Test Results\n", "\n", "This notebook was tested in multiple regions. The test results are as follows, except for us-west-2 which is shown at the top of the notebook.\n", "\n", "![This us-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-east-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This us-east-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-east-2/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This us-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-west-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This ca-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ca-central-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This sa-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/sa-east-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This eu-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This eu-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-2/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This eu-west-3 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-3/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This eu-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-central-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This eu-north-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-north-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This ap-southeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-southeast-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This ap-southeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-southeast-2/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This ap-northeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-northeast-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This ap-northeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-northeast-2/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n", "\n", "![This ap-south-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-south-1/sagemaker_model_monitor|fairness_and_explainability_jsonlines|SageMaker-Monitoring-Feature-Attribution-Drift-for-Endpoint.ipynb)\n" ] } ], "metadata": { "instance_type": "ml.t3.medium", "kernelspec": { "display_name": "Python 3 (Data Science 3.0)", "language": "python", "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/sagemaker-data-science-310-v1" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.6" }, "toc-autonumbering": false, "toc-showmarkdowntxt": false }, "nbformat": 4, "nbformat_minor": 5 }