|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). You |
| 4 | +# may not use this file except in compliance with the License. A copy of |
| 5 | +# the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "license" file accompanying this file. This file is |
| 10 | +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
| 11 | +# ANY KIND, either express or implied. See the License for the specific |
| 12 | +# language governing permissions and limitations under the License. |
| 13 | +from __future__ import absolute_import |
| 14 | + |
| 15 | +import pytest |
| 16 | + |
| 17 | +from sagemaker import get_execution_role |
| 18 | +from sklearn.datasets import load_iris |
| 19 | +from sklearn.model_selection import train_test_split |
| 20 | + |
| 21 | +import os |
| 22 | + |
| 23 | +from sagemaker_core.main.shapes import ( |
| 24 | + AlgorithmSpecification, |
| 25 | + Channel, |
| 26 | + DataSource, |
| 27 | + S3DataSource, |
| 28 | + OutputDataConfig, |
| 29 | + ResourceConfig, |
| 30 | + StoppingCondition, |
| 31 | +) |
| 32 | +import uuid |
| 33 | +from sagemaker.serve.builder.model_builder import ModelBuilder |
| 34 | +import pandas as pd |
| 35 | +import numpy as np |
| 36 | +from sagemaker.serve import InferenceSpec, SchemaBuilder |
| 37 | +from sagemaker_core.main.resources import TrainingJob |
| 38 | +from xgboost import XGBClassifier |
| 39 | + |
| 40 | +from sagemaker.serverless.serverless_inference_config import ServerlessInferenceConfig |
| 41 | + |
| 42 | +from sagemaker.s3_utils import s3_path_join |
| 43 | +from sagemaker.async_inference import AsyncInferenceConfig |
| 44 | +from tests.integ.utils import cleanup_model_resources |
| 45 | + |
| 46 | + |
| 47 | +@pytest.fixture(scope="module") |
| 48 | +def xgboost_model_builder(mb_sagemaker_session): |
| 49 | + sagemaker_session = mb_sagemaker_session |
| 50 | + role = get_execution_role(sagemaker_session=sagemaker_session) |
| 51 | + bucket = sagemaker_session.default_bucket() |
| 52 | + |
| 53 | + # Get IRIS Data |
| 54 | + iris = load_iris() |
| 55 | + iris_df = pd.DataFrame(iris.data, columns=iris.feature_names) |
| 56 | + iris_df["target"] = iris.target |
| 57 | + |
| 58 | + # Prepare Data |
| 59 | + os.makedirs("data", exist_ok=True) |
| 60 | + |
| 61 | + iris_df = iris_df[["target"] + [col for col in iris_df.columns if col != "target"]] |
| 62 | + |
| 63 | + train_data, test_data = train_test_split(iris_df, test_size=0.2, random_state=42) |
| 64 | + |
| 65 | + train_data.to_csv("data/train.csv", index=False, header=False) |
| 66 | + test_data.to_csv("data/test.csv", index=False, header=False) |
| 67 | + |
| 68 | + # Remove the target column from the testing data. We will use this to call invoke_endpoint later |
| 69 | + test_data.drop("target", axis=1) |
| 70 | + |
| 71 | + prefix = "DEMO-scikit-iris" |
| 72 | + TRAIN_DATA = "train.csv" |
| 73 | + DATA_DIRECTORY = "data" |
| 74 | + |
| 75 | + sagemaker_session.upload_data( |
| 76 | + DATA_DIRECTORY, bucket=bucket, key_prefix="{}/{}".format(prefix, DATA_DIRECTORY) |
| 77 | + ) |
| 78 | + |
| 79 | + s3_input_path = "s3://{}/{}/data/{}".format(bucket, prefix, TRAIN_DATA) |
| 80 | + s3_output_path = "s3://{}/{}/output".format(bucket, prefix) |
| 81 | + |
| 82 | + print(s3_input_path) |
| 83 | + print(s3_output_path) |
| 84 | + |
| 85 | + image = "433757028032.dkr.ecr.us-west-2.amazonaws.com/xgboost:1" |
| 86 | + |
| 87 | + class XGBoostSpec(InferenceSpec): |
| 88 | + def load(self, model_dir: str): |
| 89 | + print(model_dir) |
| 90 | + model = XGBClassifier() |
| 91 | + model.load_model(model_dir + "/xgboost-model") |
| 92 | + return model |
| 93 | + |
| 94 | + def invoke(self, input_object: object, model: object): |
| 95 | + prediction_probabilities = model.predict_proba(input_object) |
| 96 | + predictions = np.argmax(prediction_probabilities, axis=1) |
| 97 | + return predictions |
| 98 | + |
| 99 | + data = {"Name": ["Alice", "Bob", "Charlie"]} |
| 100 | + df = pd.DataFrame(data) |
| 101 | + training_job_name = str(uuid.uuid4()) |
| 102 | + schema_builder = SchemaBuilder(sample_input=df, sample_output=df) |
| 103 | + |
| 104 | + training_job = TrainingJob.create( |
| 105 | + training_job_name=training_job_name, |
| 106 | + hyper_parameters={ |
| 107 | + "objective": "multi:softmax", |
| 108 | + "num_class": "3", |
| 109 | + "num_round": "10", |
| 110 | + "eval_metric": "merror", |
| 111 | + }, |
| 112 | + algorithm_specification=AlgorithmSpecification( |
| 113 | + training_image=image, training_input_mode="File" |
| 114 | + ), |
| 115 | + role_arn=role, |
| 116 | + input_data_config=[ |
| 117 | + Channel( |
| 118 | + channel_name="train", |
| 119 | + content_type="csv", |
| 120 | + compression_type="None", |
| 121 | + record_wrapper_type="None", |
| 122 | + data_source=DataSource( |
| 123 | + s3_data_source=S3DataSource( |
| 124 | + s3_data_type="S3Prefix", |
| 125 | + s3_uri=s3_input_path, |
| 126 | + s3_data_distribution_type="FullyReplicated", |
| 127 | + ) |
| 128 | + ), |
| 129 | + ) |
| 130 | + ], |
| 131 | + output_data_config=OutputDataConfig(s3_output_path=s3_output_path), |
| 132 | + resource_config=ResourceConfig( |
| 133 | + instance_type="ml.m4.xlarge", instance_count=1, volume_size_in_gb=30 |
| 134 | + ), |
| 135 | + stopping_condition=StoppingCondition(max_runtime_in_seconds=600), |
| 136 | + ) |
| 137 | + training_job.wait() |
| 138 | + |
| 139 | + xgboost_model_builder = ModelBuilder( |
| 140 | + name="ModelBuilderTest", |
| 141 | + model_path=training_job.model_artifacts.s3_model_artifacts, |
| 142 | + role_arn=role, |
| 143 | + inference_spec=XGBoostSpec(), |
| 144 | + image_uri=image, |
| 145 | + schema_builder=schema_builder, |
| 146 | + instance_type="ml.c6i.xlarge", |
| 147 | + ) |
| 148 | + xgboost_model_builder.build() |
| 149 | + return xgboost_model_builder |
| 150 | + |
| 151 | + |
| 152 | +def test_real_time_deployment(xgboost_model_builder): |
| 153 | + real_time_predictor = xgboost_model_builder.deploy( |
| 154 | + endpoint_name="test", initial_instance_count=1 |
| 155 | + ) |
| 156 | + |
| 157 | + assert real_time_predictor is not None |
| 158 | + cleanup_model_resources( |
| 159 | + sagemaker_session=xgboost_model_builder.sagemaker_session, |
| 160 | + model_name=xgboost_model_builder.built_model.name, |
| 161 | + endpoint_name=xgboost_model_builder.built_model.endpoint_name, |
| 162 | + ) |
| 163 | + |
| 164 | + |
| 165 | +def test_serverless_deployment(xgboost_model_builder): |
| 166 | + serverless_predictor = xgboost_model_builder.deploy( |
| 167 | + endpoint_name="test1", inference_config=ServerlessInferenceConfig() |
| 168 | + ) |
| 169 | + |
| 170 | + assert serverless_predictor is not None |
| 171 | + cleanup_model_resources( |
| 172 | + sagemaker_session=xgboost_model_builder.sagemaker_session, |
| 173 | + model_name=xgboost_model_builder.built_model.name, |
| 174 | + endpoint_name=xgboost_model_builder.built_model.endpoint_name, |
| 175 | + ) |
| 176 | + |
| 177 | + |
| 178 | +def test_async_deployment(xgboost_model_builder, mb_sagemaker_session): |
| 179 | + async_predictor = xgboost_model_builder.deploy( |
| 180 | + endpoint_name="test2", |
| 181 | + inference_config=AsyncInferenceConfig( |
| 182 | + output_path=s3_path_join( |
| 183 | + "s3://", mb_sagemaker_session.default_bucket(), "async_inference/output" |
| 184 | + ) |
| 185 | + ), |
| 186 | + ) |
| 187 | + |
| 188 | + assert async_predictor is not None |
| 189 | + cleanup_model_resources( |
| 190 | + sagemaker_session=xgboost_model_builder.sagemaker_session, |
| 191 | + model_name=xgboost_model_builder.built_model.name, |
| 192 | + endpoint_name=xgboost_model_builder.built_model.endpoint_name, |
| 193 | + ) |
0 commit comments