Sm Clarify Model Bias Monitor For Endpoint
Amazon SageMaker Clarify Model Bias Monitor - JSON Lines Format
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.
Runtime
This notebook takes approximately 60 minutes to run.
Introduction
Amazon SageMaker Model Monitor 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.
Amazon SageMaker Clarify Model Bias Monitor is a model monitor that helps data scientists and ML engineers monitor predictions for bias on a regular basis. Bias can be introduced or exacerbated in deployed ML models when the training data differs from the data that the model sees during deployment (that is, the live data). These kinds of changes in the live data distribution might be temporary (for example, due to some short-lived, real-world events) or permanent. In either case, it might be important to detect these changes. For example, the outputs of a model for predicting home prices can become biased if the mortgage rates used to train the model differ from current, real-world mortgage rates. With bias drift detection capabilities in model monitor, when SageMaker detects bias beyond a certain threshold, it automatically generates metrics that you can view in SageMaker Studio and through Amazon CloudWatch alerts.
This notebook demonstrates the process for setting up a model monitor for continuous monitoring of bias drift of the data and model of a SageMaker real-time inference endpoint. The model input and output are in SageMaker JSON Lines dense format. SageMaker Clarify model monitor also supports analyzing CSV data, which is illustrated in another notebook.
In general, you can use the model bias monitor for real-time inference endpoint in this way,
- Enable the endpoint for data capture. Then, when the customer invokes the endpoint, the endpoint saves the invocations to a data capture S3 location.
- Schedule a model bias monitor to monitor the endpoint (to be more specific, the data capture S3 location) and a ground truth S3 location.
- You need to regularly fetch the captured data, label it, and then upload the ground truth labels to the ground truth S3 URI.
The monitor executes processing jobs regularly to merge the captured data and ground truth data, do bias analysis for the merged data, and then generate analysis reports and publish metrics to CloudWatch.
General Setup
The notebook uses the 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.
Imports
The following cell imports the APIs to be used by the notebook.
Handful of configuration
To begin, ensure that these prerequisites have been completed.
- Specify an AWS Region to host the model.
- Specify an IAM role to execute jobs.
- 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.
Model file and data files
This example includes a prebuilt SageMaker Linear Learner model trained by a SageMaker Clarify offline processing example notebook. The model supports SageMaker JSON Lines dense format (MIME type "application/jsonlines").
- 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,
{"features":[28,2,133937,9,13,2,0,0,4,1,15024,0,55,37]}
{"features":[43,2,72338,12,14,2,12,0,1,1,0,0,40,37]}
- 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,
{"predicted_label":1,"score":0.989977359771728}
{"predicted_label":1,"score":0.504138827323913}
This example includes two dataset files, both in the JSON Lines format. The data also originates from the SageMaker Clarify offline processing example notebook.
The train dataset has the features and the ground truth label (pointed to by the key "label"),
The test dataset only has features.
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.
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.
Then upload the files to S3 so that they can be used by SageMaker.
Real-time Inference Endpoint
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.
Deploy the model to an endpoint
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.
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.
NOTE: The following cell takes about 10 minutes to deploy the model.
Invoke the endpoint
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.
Example: Single record
Request payload:
Response payload:
Example: Two records
Request payload:
Response payload:
View captured data
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.
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:
s3://{destination-bucket-prefix}/{endpoint-name}/{variant-name}/yyyy/mm/dd/hh/filename.jsonl
Next, view the content of a single capture file.
Finally, the contents of a single line is present below in formatted JSON to observe a little better.
captureDatahas two fields,endpointInputhas the captured invocation request, andendpointOutputhas the response.eventMetadatahas the inference ID and event ID.
Start generating some artificial traffic
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.
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.
Ground Truth Data
Besides captured data, bias drift monitoring execution also requires ground truth data. In real use cases, you should regularly label the captured data, then upload the ground truth data (labels) to designated S3 location. For demonstration purpose, this example notebook generates fake ground truth data following this schema, and then uploads it to ground_truth_s3_uri which is another key input to the monitor. The bias drift monitoring execution will first merge the captured data and the ground truth data, and then do bias analysis for the merged data.
Notice the value of the data field in groundTruthData must be in the same format as how the ground truth labels are stored in the input dataset.
Model Bias Monitor
Similar to the other monitoring types, the standard procedure of creating a bias drift monitor is first run a baselining job, and then schedule the monitor.
A bias drift monitoring execution starts a merge job that joins the captured data and ground truth data together using the inference ID. Then a SageMaker Clarify bias analysis job is started to compute all the pre-training bias metrics and post-training bias metrics. on the merged data. The max execution time is divided equally between two jobs, the notebook is scheduling an hourly model bias monitor, so the max_runtime_in_seconds parameter should not exceed 1800 seconds.
Baselining job
A baselining job runs predictions on training dataset and suggests constraints. The suggest_baseline() method of ModelBiasMonitor starts a SageMaker Clarify processing job to generate the constraints.
The step is not mandatory, but providing constraints file to the monitor can enable violations file generation.
Configurations
Information about the input data need to be provided to the processor.
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,
-
The parameter value
"features"or"label"is NOT a header string. Instead, it is aJMESPathexpression (refer to its specification) that is used to locate the features list or the ground truth label in 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 thefeaturesparameter should use value"data.features.values", and thelabelparameter should use value"data.label".{"data": {"features": {"values": [25, 2, 226802, 1, 7, 4, 6, 3, 2, 1, 0, 0, 40, 37]}, "label": 0}} -
SageMaker Clarify processing job will load the JSON Lines dataset into tabular representation for further analysis, and the parameter
headersis 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.
ModelConfig is configuration related to model to be used for inferencing. In order to compute post-training bias metrics, the computation needs to get inferences 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,
content_templateis 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$featureswill 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.
ModelPredictedLabelConfig specifies how to extract predicted label from the model output. The example model returns the predicted label as well as the confidence score, so there are two ways to define this configuration,
- Set the
labelparameter to "predicted_label" which is theJMESPathexpression to locate the predicted label in the model output. This is the way used in this example. - Alternatively, you can set the
probabilityparameter to "score" which is theJMESPathexpression to locate the confidence score in the model output. And set theprobability_thresholdparameter to a floating number in between 0 and 1. The post-training analysis will use it to convert a score to binary predicted label (0or1). The default value is 0.5, which means a probability value > 0.5 indicates predicted label1.
BiasConfig is the configuration of the sensitive groups in the dataset. Typically, bias is measured by computing a metric and comparing it across groups.
- The group of interest is specified using the facet parameters. With the following configuration, the baselining job will check for bias in the model's predictions with respect to gender and income. Specifically, it is checking if the model is more likely to predict that males have an annual income of over $50,000 compared to females. Although not demonstrated in this example, a bias monitor can measure bias against multiple sensitive attributes, if you provide a list of facets.
- The
group_nameparameter is used to form subgroups for the measurement of Conditional Demographic Disparity in Labels (CDDL) and Conditional Demographic Disparity in Predicted Labels (CDDPL) with regard to Simpson’s paradox.
Kick off baselining job
Call the suggest_baseline() method to start the baselining job. The job computes all the pre-training bias metrics and post-training bias metrics.
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.
Monitoring Schedule
With above constraints collected, now call create_monitoring_schedule() method to schedule an hourly model bias monitor.
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.
BiasAnalysisConfig is a subset of the configuration of the baselining job, many options are not needed because,
- Model bias monitor will merge the captured data and the ground truth data, and then use the merged data as the dataset.
- Capture data already includes predictions, so there is no need to create shadow endpoint.
- Attributes like predicted label are provided as part of EndpointInput.
Highlights,
- From
endpoint_namethe monitor can figure out the location of data captured by the endpoint. ground_truth_s3_uriis the location of ground truth datafeatures_attributeis theJMESPathexpression to locate the features in model input, similar to thefeaturesparameter ofDataConfig.inference_attributeis theJMESPathexpression to locate the predicted label in model output, similar to thelabelparameter ofModelPredictedLabelConfig.
Wait for the first execution
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.
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.
NOTE: The following cell waits until the first monitoring execution is started. As explained above, the wait could take more than 60 minutes.
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().
Wait for the execution to finish
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:
Completed- This means the monitoring execution completed, and no issues were found in the violations report.CompletedWithViolations- This means the execution completed, but constraint violations were detected.Failed- The monitoring execution failed, maybe due to client error (perhaps incorrect role permissions) or infrastructure issues. Further examination ofFailureReasonandExitMessageis necessary to identify what exactly happened.Stopped- job exceeded max runtime or was manually stopped.
NOTE: The following cell takes about 10 minutes.
Merged data
Merged data is the intermediate results of bias drift monitoring execution. It is saved to JSON Lines files under the "merge" folder of monitor_output_s3_uri. Each line is a valid JSON object which combines the captured data and the ground truth data.
The following cell prints a single line of a merged data file.
eventIdis the inference ID from the captured data and the ground truth datagroundTruthDatais from the ground truth datacaptureDatais from the captured data.
Inspect execution results
List the generated reports,
- analysis.json includes all the bias metrics.
- report.* files are static report files to visualize the bias metrics
If there are any violations compared to the baseline, they are listed here. See Bias Drift Violations for the schema of the file, and how violations are detected.
By default, the analysis results are also published to CloudWatch, see CloudWatch Metrics for Bias Drift Analysis.
Cleanup
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.
First stop the worker threads,
Then stop all monitors scheduled for the endpoint
Finally, delete the endpoint
Notebook CI Test Results
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.