{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SageMaker Pipelines workshop\n", "\n", "This workshop is based on the [amazon sagemaker drift detection project](https://github.com/aws-samples/amazon-sagemaker-drift-detection) on github, available in the aws-samples repository. \n", "\n", "Amazon SageMaker Model Building Pipelines offers machine learning (ML) application developers and operations engineers the ability to orchestrate SageMaker jobs and author reproducible ML pipelines. It also enables them to deploy custom-build models for inference in real-time with low latency, run offline inferences with Batch Transform, and track lineage of artifacts. They can institute sound operational practices in deploying and monitoring production workflows, deploying model artifacts, and tracking artifact lineage through a simple interface, adhering to safety and best practice paradigms for ML application development.\n", "\n", "The SageMaker Pipelines service supports a SageMaker Pipeline domain specific language (DSL), which is a declarative JSON specification. This DSL defines a directed acyclic graph (DAG) of pipeline parameters and SageMaker job steps. The SageMaker Python Software Developer Kit (SDK) streamlines the generation of the pipeline DSL using constructs that engineers and scientists are already familiar with." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## SageMaker Pipelines\n", "\n", "SageMaker Pipelines supports the following activities, which are demonstrated in this notebook:\n", "\n", "* Pipelines - A DAG of steps and conditions to orchestrate SageMaker jobs and resource creation.\n", "* Processing job steps - A simplified, managed experience on SageMaker to run data processing workloads, such as feature engineering, data validation, model evaluation, and model interpretation.\n", "* Training job steps - An iterative process that teaches a model to make predictions by presenting examples from a training dataset.\n", "* Conditional execution steps - A step that provides conditional execution of branches in a pipeline.\n", "* Register model steps - A step that creates a model package resource in the Model Registry that can be used to create deployable models in Amazon SageMaker.\n", "* Create model steps - A step that creates a model for use in transform steps or later publication as an endpoint.\n", "* Transform job steps - A batch transform to preprocess datasets to remove noise or bias that interferes with training or inference from a dataset, get inferences from large datasets, and run inference when a persistent endpoint is not needed.\n", "* Parametrized Pipeline executions - Enables variation in pipeline executions according to specified parameters." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Notebook Overview\n", "\n", "This notebook shows how to:\n", "\n", "* Define a set of Pipeline parameters that can be used to parametrize a SageMaker Pipeline.\n", "* Define a Processing step that performs cleaning, feature engineering, and splitting the input data into train and test data sets.\n", "* Define a Training step that trains a model on the preprocessed train data set.\n", "* Define a Processing step that evaluates the trained model's performance on the test dataset.\n", "* Define a Create Model step that creates a model from the model artifacts used in training.\n", "* Define a Transform step that performs batch transformation based on the model that was created.\n", "* Define a Register Model step that creates a model package from the estimator and model artifacts used to train the model.\n", "* Define a Conditional step that measures a condition based on output from prior steps and conditionally executes other steps.\n", "* Define and create a Pipeline definition in a DAG, with the defined parameters and steps.\n", "* Start a Pipeline execution and wait for execution to complete.\n", "* Download the model evaluation report from the S3 bucket for examination.\n", "* Start a second Pipeline execution." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will consider 3 teams in this scenario:\n", "* Engineering team - ML or data engineering\n", "* Data science team - developing the models\n", "* Dev ops team - automating and integrating the pipeline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A SageMaker Pipeline\n", "\n", "The pipeline that you create follows a typical machine learning (ML) application pattern of preprocessing, training, evaluation, model creation, batch transformation, and model registration:\n", "\n", "![A typical ML Application pipeline](https://raw.githubusercontent.com/aws/amazon-sagemaker-examples/a78c7255cbe7892408d8ea2b15a7a2117703befc/sagemaker-pipelines/tabular/abalone_build_train_deploy/img/pipeline-full.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dataset\n", "we use the publicly available [New York City Taxi and Limousine Commission (TLC) Trip Record Data](https://registry.opendata.aws/nyc-tlc-trip-records-pds/). This TLC record data contains the yellow and green taxi trip records include fields capturing pick-up and drop-off dates/times, pick-up and drop-off locations, tripc distances, itemized fares, rate types, payment types, and driver-reported passenger counts. The data used in the attached datasets were collected and provided to the NYC Taxi and Limousine Commission (TLC) by technology providers authorized under the Taxicab & Livery Passenger Enhancement Programs (TPEP/LPEP), please refer to [NYC documentation](https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
💡 Warning \n", " Please make sure to run the below prerequisites.ipynb notebook in the notebook folder to prepare data for the pipeline, or uncomment the below cell to download data before running the rest of the notebook\n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ">**Important**: [prerequisites.ipynb](files/../notebook/prerequisites.ipynb)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# # Uncomment the section to prepare data if the prerequisites.ipynb and the sagemaker_processing_job.ipynb notebooks are not executed\n", "# import sagemaker\n", "# bucket=sagemaker.Session().default_bucket()\n", "# prefix = 'sagemaker/DEMO-xgboost-tripfare'\n", "\n", "# # define the input data and input zone s3 location\n", "# input_source = f's3://{bucket}/{prefix}/input/'\n", "# input_data = input_source + 'data/green/'\n", "# input_zones = input_source + 'zones/'\n", "\n", "# # download the input data for the pipeline\n", "# !aws s3 cp --recursive 's3://nyc-tlc/trip data/' $input_data --exclude '*' --include 'green_tripdata_2018-1*'\n", "# !aws s3 cp 's3://nyc-tlc/misc/taxi_zones.zip' $input_zones\n", "\n", "# # confirm data is downloaded successfully\n", "# !aws s3 ls $input_data\n", "\n", "# %store input_data\n", "# %store input_zones" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install sagemaker==2.75.1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Preparation\n", "\n", "\n", "Let's start by specifying:\n", "\n", "- The S3 bucket and prefix that you want to use for training and model data. This should be within the same region as the Notebook Instance, training, and hosting.\n", "- The IAM role arn used to give training and hosting access to your data. See the documentation for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the boto regexp with a the appropriate full IAM role arn string(s)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import os\n", "\n", "import boto3\n", "import sagemaker\n", "import sagemaker.session\n", "from sagemaker import get_execution_role\n", "\n", "from sagemaker.estimator import Estimator\n", "from sagemaker.debugger import Rule, rule_configs\n", "from sagemaker.inputs import TrainingInput\n", "from sagemaker.model_monitor.dataset_format import DatasetFormat\n", "from sagemaker.model_metrics import (\n", " MetricsSource,\n", " ModelMetrics,\n", ")\n", "from sagemaker.processing import (\n", " ProcessingInput,\n", " ProcessingOutput,\n", " Processor,\n", " ScriptProcessor,\n", ")\n", "from sagemaker.sklearn.processing import SKLearnProcessor\n", "from sagemaker.s3 import S3Uploader\n", "from sagemaker.workflow.conditions import ConditionLessThanOrEqualTo\n", "from sagemaker.workflow.condition_step import ConditionStep\n", "from sagemaker.workflow.functions import JsonGet\n", "\n", "from sagemaker.workflow.parameters import (\n", " ParameterInteger,\n", " ParameterString,\n", ")\n", "from sagemaker.workflow.pipeline import Pipeline\n", "from sagemaker.workflow.properties import PropertyFile\n", "from sagemaker.workflow.steps import (\n", " ProcessingStep,\n", " TrainingStep,\n", " CacheConfig,\n", ")\n", "from sagemaker.workflow.step_collections import RegisterModel\n", "from sagemaker.utils import name_from_base\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "role = get_execution_role()\n", "\n", "region = boto3.Session().region_name\n", "\n", "sagemaker_session = sagemaker.Session()\n", "\n", "bucket=sagemaker.Session().default_bucket()\n", "prefix = 'sagemaker/DEMO-xgboost-tripfare'\n", "base_job_prefix = 'Demo-xgboost-tripfare'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define Parameters to Parametrize Pipeline Execution\n", "\n", "Define Pipeline parameters that you can use to parametrize the pipeline. Parameters enable custom pipeline executions and schedules without having to modify the Pipeline definition.\n", "\n", "The supported parameter types include:\n", "\n", "* `ParameterString` - represents a `str` Python type\n", "* `ParameterInteger` - represents an `int` Python type\n", "* `ParameterFloat` - represents a `float` Python type\n", "\n", "These parameters support providing a default value, which can be overridden on pipeline execution. The default value specified should be an instance of the type of the parameter.\n", "\n", "The parameters defined in this workflow include:\n", "\n", "* `processing_instance_type` - The `ml.*` instance type of the processing job.\n", "* `processing_instance_count` - The instance count of the processing job.\n", "* `training_instance_type` - The `ml.*` instance type of the training job.\n", "* `model_approval_status` - What approval status to register the trained model with for CI/CD purposes ( \"PendingManualApproval\" is the default).\n", "* `input_data` - The S3 bucket URI location of the input trip data\n", "* `input_zones` - The S3 bucket URI location of the input taxi zones data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Define Parameters](https://raw.githubusercontent.com/aws/amazon-sagemaker-examples/a78c7255cbe7892408d8ea2b15a7a2117703befc/sagemaker-pipelines/tabular/abalone_build_train_deploy/img/pipeline-1.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%store\n", "%store -r" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**You must have run the previous sequential notebooks to retrieve variables using the StoreMagic command.**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# checking if the input data and preprocessing script are already available, if not we need to define these variables\n", "if 'process_script' not in locals():\n", " \n", " process_script = '../preprocess/preprocess.py'\n", " %store process_script\n", " \n", "else:\n", " print(f'prcess script is available: {process_script}')\n", " \n", "if 'input_data' not in locals() or 'input_zones' not in locals():\n", " input_data = f\"s3://{bucket}/{prefix}/input/data/green/\"\n", " input_zones = f\"s3://{bucket}/{prefix}/input/zones/taxi_zones.zip\"\n", " %store input_data\n", " %store input_zones\n", "else:\n", " print(f'input data and input zones are available: \\n {input_data} \\n {input_zones}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# parameters for pipeline execution\n", " \n", "input_data = ParameterString(\n", " name=\"InputDataUrl\",\n", " default_value=input_data,\n", ")\n", "input_zones = ParameterString(\n", " name=\"InputZonesUrl\",\n", " default_value=input_zones,\n", ")\n", "\n", "processing_instance_count = ParameterInteger(\n", " name=\"ProcessingInstanceCount\", default_value=2\n", ")\n", "processing_instance_type = ParameterString(\n", " name=\"ProcessingInstanceType\", default_value=\"ml.m5.xlarge\"\n", ")\n", "training_instance_type = ParameterString(\n", " name=\"TrainingInstanceType\", default_value=\"ml.m5.xlarge\"\n", ")\n", "model_approval_status = ParameterString(\n", " name=\"ModelApprovalStatus\", default_value=\"PendingManualApproval\"\n", ")\n", "model_output = ParameterString(\n", " name=\"ModelOutputUrl\",\n", " default_value=f\"s3://{bucket}/{prefix}/model\",\n", ")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create cache configuration (Unable to pass parameter for expire_after value)\n", "cache_config = CacheConfig(enable_caching=True, expire_after=\"PT1H\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a Processing Step for Feature Engineering\n", "\n", "First, develop a preprocessing script that is specified in the Processing step.\n", "\n", "In the SageMaker Processing lab, we have already created the `preprocess.py`, which contains the preprocessing script, and stored the path to the script. You can use the following cell to load the stored value.\n", "\n", "The Processing step executes the script on the input data. The Training step uses the preprocessed training features and labels to train a model. The Evaluation step uses the trained model and preprocessed test features and labels to evaluate the model." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Define a Processing Step for Feature Engineering](https://raw.githubusercontent.com/aws/amazon-sagemaker-examples/a78c7255cbe7892408d8ea2b15a7a2117703befc/sagemaker-pipelines/tabular/abalone_build_train_deploy/img/pipeline-2.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, create an instance of an `SKLearnProcessor` processor and use that in our `ProcessingStep`.\n", "\n", "You also specify the `framework_version` to use throughout this notebook.\n", "\n", "Note the `processing_instance_type` and `processing_instance_count` parameters used by the processor instance." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# processing step for feature engineering\n", "sklearn_processor = SKLearnProcessor(\n", " framework_version=\"0.23-1\",\n", " instance_type=processing_instance_type,\n", " instance_count=processing_instance_count,\n", " base_job_name=f\"{base_job_prefix}-sklearn-preprocess\",\n", " sagemaker_session=sagemaker_session,\n", " role=role,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, use the processor instance to construct a `ProcessingStep`, along with the input and output channels, and the code that will be executed when the pipeline invokes pipeline execution. This is similar to a processor instance's `run` method in the Python SDK.\n", "\n", "Note the `input_data` parameters passed into `ProcessingStep` is the input data used in the step. This input data is used by the processor instance when it is run.\n", "\n", "Also, note the `\"train\"`, `\"validation\"` and `\"test\"` named channels specified in the output configuration for the processing job. Step `Properties` can be used in subsequent steps and resolve to their runtime values at execution. Specifically, this usage is called out when you define the training step." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "step_process = ProcessingStep(\n", " name=\"PreprocessData\",\n", " processor=sklearn_processor,\n", " inputs=[\n", " ProcessingInput(\n", " source=input_data,\n", " destination=\"/opt/ml/processing/input/data\",\n", " s3_data_distribution_type=\"ShardedByS3Key\",\n", " ),\n", " ProcessingInput(\n", " source=input_zones,\n", " destination=\"/opt/ml/processing/input/zones\",\n", " s3_data_distribution_type=\"FullyReplicated\",\n", " ),\n", " ],\n", " outputs=[\n", " ProcessingOutput(output_name=\"train\", source=\"/opt/ml/processing/train\"),\n", " ProcessingOutput(\n", " output_name=\"validation\", source=\"/opt/ml/processing/validation\"\n", " ),\n", " ProcessingOutput(output_name=\"test\", source=\"/opt/ml/processing/test\"),\n", " ],\n", " code=process_script,\n", "# If you have created the Feature Group for this dataset in Lab 1, \n", "# you can use the feature group name here replace False to include the feature ingestion in the processing job\n", " job_arguments=['--fs_ing', \"False\", \n", " '--region', region,\n", " '--bucket', bucket,\n", " ],\n", " cache_config=cache_config,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a Training Step to Train a Model\n", "\n", "In this section, use Amazon SageMaker's [XGBoost Algorithm](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html) to train on this dataset. Configure an Estimator for the XGBoost algorithm and the input dataset. A typical training script loads data from the input channels, configures training with hyperparameters, trains a model, and saves a model to `model_output` so that it can be hosted later. \n", "\n", "The model path where the models from training will be saved is also specified.\n", "\n", "Note the `training_instance_type` parameter may be used in multiple places in the pipeline. In this case, the `training_instance_type` is passed into the estimator." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Define a Training Step to Train a Model](https://raw.githubusercontent.com/aws/amazon-sagemaker-examples/a78c7255cbe7892408d8ea2b15a7a2117703befc/sagemaker-pipelines/tabular/abalone_build_train_deploy/img/pipeline-3.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define the XGBoost training report rules\n", "# see: https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-training-xgboost-report.html\n", "rules = [Rule.sagemaker(rule_configs.create_xgboost_report())]\n", "\n", "# training step for generating model artifacts\n", "image_uri = sagemaker.image_uris.retrieve(\n", " framework=\"xgboost\",\n", " region=region,\n", " version=\"1.2-2\",\n", " py_version=\"py3\",\n", " instance_type=training_instance_type,\n", ")\n", "xgb_train = Estimator(\n", " image_uri=image_uri,\n", " instance_type=training_instance_type,\n", " instance_count=1,\n", " output_path=model_output,\n", " base_job_name=f\"{base_job_prefix}-train\",\n", " sagemaker_session=sagemaker_session,\n", " role=role,\n", " disable_profiler=False, # Profile processing job\n", " rules=rules, # Report processing job\n", ")\n", "\n", "# Set some hyper parameters\n", "# https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost_hyperparameters.html\n", "xgb_train.set_hyperparameters(\n", " objective=\"reg:squarederror\",\n", " num_round=100,\n", " early_stopping_rounds=10,\n", " max_depth=9,\n", " eta=0.2,\n", " gamma=4,\n", " min_child_weight=300,\n", " subsample=0.8,\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, use the estimator instance to construct a `TrainingStep` as well as the `properties` of the prior `ProcessingStep` used as input in the `TrainingStep` inputs and the code that's executed when the pipeline invokes the pipeline execution. This is similar to an estimator's `fit` method in the Python SDK.\n", "\n", "Pass in the `S3Uri` of the `\"train\"` output channel to the `TrainingStep`. Also, use the other `\"validation\"` output channel for model evaluation in the pipeline. The `properties` attribute of a Pipeline step matches the object model of the corresponding response of a describe call. These properties can be referenced as placeholder values and are resolved at runtime. For example, the `ProcessingStep` `properties` attribute matches the object model of the [DescribeProcessingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeProcessingJob.html) response object." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "step_train = TrainingStep(\n", " name=\"TrainModel\",\n", " estimator=xgb_train,\n", " inputs={\n", " \"train\": TrainingInput(\n", " s3_data=step_process.properties.ProcessingOutputConfig.Outputs[\n", " \"train\"\n", " ].S3Output.S3Uri,\n", " content_type=\"text/csv\",\n", " ),\n", " \"validation\": TrainingInput(\n", " s3_data=step_process.properties.ProcessingOutputConfig.Outputs[\n", " \"validation\"\n", " ].S3Output.S3Uri,\n", " content_type=\"text/csv\",\n", " ),\n", " },\n", " cache_config=cache_config,\n", "\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a Model Evaluation Step to Evaluate the Trained Model\n", "\n", "First, develop an evaluation script that is specified in a Processing step that performs the model evaluation.\n", "\n", "After pipeline execution, you can examine the resulting `evaluation.json` for analysis.\n", "\n", "The evaluation script uses `xgboost` to do the following:\n", "\n", "* Load the model.\n", "* Read the test data.\n", "* Issue predictions against the test data.\n", "* Build a classification report, including mae, mse, rmse and r2 metrics.\n", "* Save the evaluation report to the evaluation directory." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Define a Model Evaluation Step to Evaluate the Trained Model](https://raw.githubusercontent.com/aws/amazon-sagemaker-examples/a78c7255cbe7892408d8ea2b15a7a2117703befc/sagemaker-pipelines/tabular/abalone_build_train_deploy/img/pipeline-4.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%writefile evaluation.py\n", "\"\"\"Evaluation script for measuring mean squared error.\"\"\"\n", "import json\n", "import logging\n", "import pathlib\n", "import pickle\n", "import tarfile\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import xgboost\n", "import glob\n", "\n", "from math import sqrt\n", "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", "\n", "logger = logging.getLogger()\n", "logger.setLevel(logging.INFO)\n", "logger.addHandler(logging.StreamHandler())\n", "\n", "if __name__ == \"__main__\":\n", " logger.debug(\"Starting evaluation.\")\n", " \n", " import os\n", " for file in os.listdir(\"/opt/ml/processing/model\"):\n", " logger.info(file)\n", " \n", " model_path = \"/opt/ml/processing/model/model.tar.gz\"\n", " with tarfile.open(model_path) as tar:\n", " tar.extractall(path=\".\")\n", " \n", " for file in os.listdir(\"/opt/ml/processing/model\"):\n", " logger.info(file)\n", " \n", " logger.debug(\"Loading xgboost model.\")\n", " model = pickle.load(open(\"xgboost-model\", \"rb\"))\n", "\n", " logger.debug(\"Reading test data.\")\n", " test_path = \"/opt/ml/processing/test/\"\n", " all_files = glob.glob(test_path + \"/*.csv\")\n", " tmp = []\n", " for filename in all_files:\n", " df_tmp = pd.read_csv(filename, index_col=None, header=None)\n", " tmp.append(df_tmp)\n", "\n", " df = pd.concat(tmp, axis=0, ignore_index=True)\n", "\n", " logger.debug(\"Reading test data.\")\n", " y_test = df.iloc[:, 0].values\n", " df.drop(df.columns[0], axis=1, inplace=True)\n", " X_test = xgboost.DMatrix(df.values)\n", "\n", " logger.info(\"Performing predictions against test data.\")\n", " predictions = model.predict(X_test)\n", "\n", " # See the regression metrics\n", " # see: https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-model-quality-metrics.html\n", " logger.debug(\"Calculating metrics.\")\n", " mae = mean_absolute_error(y_test, predictions)\n", " mse = mean_squared_error(y_test, predictions)\n", " rmse = sqrt(mse)\n", " r2 = r2_score(y_test, predictions)\n", " std = np.std(y_test - predictions)\n", " report_dict = {\n", " \"regression_metrics\": {\n", " \"mae\": {\n", " \"value\": mae,\n", " \"standard_deviation\": std,\n", " },\n", " \"mse\": {\n", " \"value\": mse,\n", " \"standard_deviation\": std,\n", " },\n", " \"rmse\": {\n", " \"value\": rmse,\n", " \"standard_deviation\": std,\n", " },\n", " \"r2\": {\n", " \"value\": r2,\n", " \"standard_deviation\": std,\n", " },\n", " },\n", " }\n", "\n", " output_dir = \"/opt/ml/processing/evaluation\"\n", " pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)\n", "\n", " logger.info(\"Writing out evaluation report with rmse: %f\", rmse)\n", " evaluation_path = f\"{output_dir}/evaluation.json\"\n", " with open(evaluation_path, \"w\") as f:\n", " f.write(json.dumps(report_dict))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, create an instance of a `ScriptProcessor` processor and use it in the `ProcessingStep`.\n", "\n", "Note the `processing_instance_type` parameter passed into the processor." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# processing step for evaluation\n", "script_eval = ScriptProcessor(\n", " image_uri=image_uri,\n", " command=[\"python3\"],\n", " instance_type=processing_instance_type,\n", " instance_count=1,\n", " base_job_name=f\"{base_job_prefix}/script-eval\",\n", " sagemaker_session=sagemaker_session,\n", " role=role,\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use the processor instance to construct a `ProcessingStep`, along with the input and output channels and the code that will be executed when the pipeline invokes pipeline execution. This is similar to a processor instance's `run` method in the Python SDK.\n", "\n", "Specifically, the `S3ModelArtifacts` from the `step_train` `properties` and the `S3Uri` of the `\"test\"` output channel of the `step_process` `properties` are passed into the inputs. The `TrainingStep` and `ProcessingStep` `properties` attribute matches the object model of the [DescribeTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html) and [DescribeProcessingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeProcessingJob.html) response objects, respectively." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "evaluation_report = PropertyFile(\n", " name=\"EvaluationReport\",\n", " output_name=\"evaluation\",\n", " path=\"evaluation.json\",\n", ")\n", "step_eval = ProcessingStep(\n", " name=\"EvaluateModel\",\n", " processor=script_eval,\n", " inputs=[\n", " ProcessingInput(\n", " source=step_train.properties.ModelArtifacts.S3ModelArtifacts,\n", " destination=\"/opt/ml/processing/model\",\n", " ),\n", " ProcessingInput(\n", " source=step_process.properties.ProcessingOutputConfig.Outputs[\n", " \"test\"\n", " ].S3Output.S3Uri,\n", " destination=\"/opt/ml/processing/test\",\n", " ),\n", " ],\n", " outputs=[\n", " ProcessingOutput(\n", " output_name=\"evaluation\", source=\"/opt/ml/processing/evaluation\"\n", " ),\n", " ],\n", " code=\"evaluation.py\",\n", " property_files=[evaluation_report],\n", " cache_config=cache_config,\n", "\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a Create Model Step to Create a Model\n", "\n", "In order to perform batch transformation using the example model, create a SageMaker model. \n", "\n", "Specifically, pass in the `S3ModelArtifacts` from the `TrainingStep`, `step_train` properties. The `TrainingStep` `properties` attribute matches the object model of the [DescribeTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html) response object." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Define a Create Model Step and Batch Transform to Process Data in Batch at Scale](https://raw.githubusercontent.com/aws/amazon-sagemaker-examples/a78c7255cbe7892408d8ea2b15a7a2117703befc/sagemaker-pipelines/tabular/abalone_build_train_deploy/img/pipeline-5.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sagemaker.inputs import CreateModelInput\n", "from sagemaker.workflow.steps import CreateModelStep\n", "from sagemaker.model import Model\n", "\n", "\n", "model = Model(\n", " image_uri=image_uri,\n", " model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,\n", " sagemaker_session=sagemaker_session,\n", " role=role,\n", ")\n", "\n", "inputs = CreateModelInput(\n", " instance_type=\"ml.m5.xlarge\",\n", ")\n", "step_create_model = CreateModelStep(\n", " name=\"TripFareCreateModel\",\n", " model=model,\n", " inputs=inputs,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a Transform Step to Perform Batch Transformation\n", "\n", "Now that a model instance is defined, create a `Transformer` instance with the appropriate model type, compute instance type, and desired output S3 URI.\n", "\n", "Specifically, pass in the `ModelName` from the `CreateModelStep`, `step_create_model` properties. The `CreateModelStep` `properties` attribute matches the object model of the [DescribeModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeModel.html) response object." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sagemaker.transformer import Transformer\n", "\n", "batch_output = f\"s3://{bucket}/{prefix}/batchtransform\"\n", "transformer = Transformer(\n", " model_name=step_create_model.properties.ModelName,\n", " instance_type=\"ml.m5.xlarge\",\n", " instance_count=1,\n", " output_path=batch_output,\n", " accept=\"text/csv\",\n", " assemble_with=\"Line\"\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pass in the transformer instance and the `TransformInput` with the `batch_data` pipeline parameter defined earlier. More details of the `TransformInput` can be found [here](https://github.com/aws/sagemaker-python-sdk/blob/2594ffb3eaefaf55936b71ea0c38442135223602/src/sagemaker/inputs.py#L140). We use `input_filter` to filter out the first column, which is the label column, in the test data. We also set the batch job to join the input source with the batch job output. Please check the document about [associating inference with input record](https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform-data-processing.html) for more details" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sagemaker.inputs import TransformInput\n", "from sagemaker.workflow.steps import TransformStep\n", "\n", "\n", "step_transform = TransformStep(\n", " name=\"TripFareTransform\",\n", " transformer=transformer,\n", " inputs=TransformInput(\n", " data=step_process.properties.ProcessingOutputConfig.Outputs[\n", " \"test\"\n", " ].S3Output.S3Uri,\n", " content_type=\"text/csv\", \n", " split_type=\"Line\",\n", " input_filter=\"$[1:]\",\n", " join_source=\"Input\",\n", " ),\n", " cache_config=cache_config,\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a Register Model Step to Create a Model Package\n", "\n", "Use the estimator instance specified in the training step to construct an instance of `RegisterModel`. The result of executing `RegisterModel` in a pipeline is a model package. A model package is a reusable model artifacts abstraction that packages all ingredients required for inference. Primarily, it consists of an inference specification that defines the inference image to use along with an optional model weights location.\n", "\n", "A model package group is a collection of model packages. A model package group can be created for a specific ML business problem, and new versions of the model packages can be added to it. Typically, customers are expected to create a ModelPackageGroup for a SageMaker pipeline so that model package versions can be added to the group for every SageMaker Pipeline run.\n", "\n", "The construction of `RegisterModel` is similar to an estimator instance's `register` method in the Python SDK.\n", "\n", "Specifically, pass in the `S3ModelArtifacts` from the `TrainingStep`, `step_train` properties. The `TrainingStep` `properties` attribute matches the object model of the [DescribeTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html) response object.\n", "\n", "Note that the specific model package group name provided in this notebook can be used in the model registry and CI/CD work with SageMaker Projects." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# register model step that will be conditionally executed\n", "model_metrics = ModelMetrics(\n", " model_statistics=MetricsSource(\n", " s3_uri=\"{}/evaluation.json\".format(\n", " step_eval.arguments[\"ProcessingOutputConfig\"][\"Outputs\"][0][\"S3Output\"][\n", " \"S3Uri\"\n", " ]\n", " ),\n", " content_type=\"application/json\",\n", " )\n", ")\n", "model_package_group_name = \"TripFareDemoModelPackage\"\n", "step_register = RegisterModel(\n", " name=\"RegisterModel\",\n", " estimator=xgb_train,\n", " model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,\n", " content_types=[\"text/csv\"],\n", " response_types=[\"text/csv\"],\n", " inference_instances=[\"ml.t2.medium\", \"ml.t2.large\", \"ml.m5.large\"],\n", " transform_instances=[\"ml.m5.large\"],\n", " model_package_group_name=model_package_group_name,\n", " approval_status=model_approval_status,\n", " model_metrics=model_metrics,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a Condition Step to Check Accuracy and Conditionally Create a Model and Run a Batch Transformation and Register a Model in the Model Registry\n", "\n", "In this step, the model is registered only if the accuracy of the model, as determined by the evaluation step `step_eval`, exceeded a specified value. A `ConditionStep` enables pipelines to support conditional execution in the pipeline DAG based on the conditions of the step properties. \n", "\n", "In the following section, you:\n", "\n", "* Define a `ConditionLessThanOrEqualTo` on the accuracy value found in the output of the evaluation step, `step_eval`.\n", "* Use the condition in the list of conditions in a `ConditionStep`.\n", "* Pass the `CreateModelStep` and `TransformStep` steps, and the `RegisterModel` step collection into the `if_steps` of the `ConditionStep`, which are only executed, if the condition evaluates to `True`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Define a Condition Step to Check Accuracy and Conditionally Execute Steps](https://raw.githubusercontent.com/aws/amazon-sagemaker-examples/a78c7255cbe7892408d8ea2b15a7a2117703befc/sagemaker-pipelines/tabular/abalone_build_train_deploy/img/pipeline-6.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# condition step for evaluating model quality and branching execution\n", "cond_lte = ConditionLessThanOrEqualTo(\n", " left=JsonGet(\n", " step_name=step_eval.name,\n", " property_file=evaluation_report,\n", " json_path=\"regression_metrics.rmse.value\",\n", " ),\n", " right=8.0,\n", ")\n", "step_cond = ConditionStep(\n", " name=\"CheckEvaluation\",\n", " conditions=[cond_lte],\n", " if_steps=[step_register, step_create_model, step_transform],\n", " else_steps=[],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define a Pipeline of Parameters, Steps, and Conditions\n", "\n", "In this section, combine the steps into a Pipeline so it can be executed.\n", "\n", "A pipeline requires a `name`, `parameters`, and `steps`. Names must be unique within an `(account, region)` pair.\n", "\n", "Note:\n", "\n", "* All of the parameters used in the definitions must be present.\n", "* Steps passed into the pipeline do not have to be listed in the order of execution. The SageMaker Pipeline service resolves the _data dependency_ DAG as steps for the execution to complete.\n", "* Steps must be unique to across the pipeline step list and all condition step if/else lists." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Define a Pipeline of Parameters, Steps, and Conditions](https://raw.githubusercontent.com/aws/amazon-sagemaker-examples/a78c7255cbe7892408d8ea2b15a7a2117703befc/sagemaker-pipelines/tabular/abalone_build_train_deploy/img/pipeline-7.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# pipeline instance\n", "pipeline = Pipeline(\n", " name=\"test-Demo-pipeline-tripfare\",\n", " parameters=[\n", " input_data,\n", " input_zones,\n", " processing_instance_type,\n", " processing_instance_count,\n", " training_instance_type,\n", " model_approval_status,\n", " model_output,\n", " ],\n", " steps=[step_process, step_train, step_eval, step_cond],\n", " sagemaker_session=sagemaker_session,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### (Optional) Examining the pipeline definition\n", "\n", "The JSON of the pipeline definition can be examined to confirm the pipeline is well-defined and the parameters and step properties resolve correctly." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "\n", "\n", "definition = json.loads(pipeline.definition())\n", "definition" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Submit the pipeline to SageMaker and start execution\n", "\n", "Submit the pipeline definition to the Pipeline service. The role passed in will be used by the Pipeline service to create all the jobs defined in the steps." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pipeline.upsert(role_arn=role)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Pipeline Operations: Examining and Waiting for Pipeline Execution\n", "\n", "Describe the pipeline execution." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "execution = pipeline.start()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "execution.describe()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Wait for the execution to complete.\n", "execution.wait()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Examining the Evalution\n", "\n", "Examine the resulting model evaluation after the pipeline completes. Download the resulting `evaluation.json` file from S3 and print the report." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pprint import pprint\n", "\n", "\n", "evaluation_json = sagemaker.s3.S3Downloader.read_file(\"{}/evaluation.json\".format(\n", " step_eval.arguments[\"ProcessingOutputConfig\"][\"Outputs\"][0][\"S3Output\"][\"S3Uri\"]\n", "))\n", "pprint(json.loads(evaluation_json))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lineage\n", "\n", "Review the lineage of the artifacts generated by the pipeline." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import time\n", "from sagemaker.lineage.visualizer import LineageTableVisualizer\n", "\n", "\n", "viz = LineageTableVisualizer(sagemaker.session.Session())\n", "for execution_step in reversed(execution.list_steps()):\n", " print(execution_step)\n", " display(viz.show(pipeline_execution_step=execution_step))\n", " time.sleep(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Parametrized Executions\n", "\n", "You can run additional executions of the pipeline and specify different pipeline parameters. The parameters argument is a dictionary containing parameter names, and where the values are used to override the defaults values.\n", "\n", "Based on the performance of the model, you might want to kick off another pipeline execution on a compute-optimized instance type and set the model approval status to \"Approved\" automatically. This means that the model package version generated by the `RegisterModel` step is automatically ready for deployment through CI/CD pipelines, such as with SageMaker Projects." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "execution = pipeline.start(\n", " parameters=dict(\n", " ProcessingInstanceType=\"ml.c5.xlarge\",\n", " ModelApprovalStatus=\"Approved\",\n", " )\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "execution.wait()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "execution.list_steps()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "instance_type": "ml.t3.medium", "kernelspec": { "display_name": "Python 3 (Data Science)", "language": "python", "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-east-1:081325390199:image/datascience-1.0" }, "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.7.10" } }, "nbformat": 4, "nbformat_minor": 4 }