|
| 1 | +import json |
| 2 | +import random |
| 3 | +import time |
| 4 | + |
| 5 | +import boto3 |
| 6 | +import httpx |
| 7 | +import numpy as np |
| 8 | +from mypy_boto3_s3 import S3Client |
| 9 | +from mypy_boto3_sagemaker import SageMakerClient |
| 10 | +from mypy_boto3_sagemaker_runtime import SageMakerRuntimeClient |
| 11 | + |
| 12 | +from mnist import mnist_to_numpy, normalize |
| 13 | + |
| 14 | +LOCALSTACK_ENDPOINT = "http://localhost.localstack.cloud:4566" |
| 15 | +MODEL_BUCKET = "models" |
| 16 | +MODEL_TAR = "./data/model.tar.gz" |
| 17 | +MODEL_NAME = "sample" |
| 18 | +CONFIG_NAME = "sample-cf" |
| 19 | +ENDPOINT_NAME = "sample-ep" |
| 20 | +CONTAINER_IMAGE = "763104351884.dkr.ecr.us-east-1.amazonaws.com/pytorch-inference:1.5.0-cpu-py3" |
| 21 | +EXECUTION_ROLE_ARN = "arn:aws:iam::0000000000000:role/sagemaker-role" |
| 22 | + |
| 23 | +sagemaker: SageMakerClient = boto3.client("sagemaker", endpoint_url=LOCALSTACK_ENDPOINT) |
| 24 | +sagemaker_runtime: SageMakerRuntimeClient = boto3.client("sagemaker-runtime", endpoint_url=LOCALSTACK_ENDPOINT) |
| 25 | +s3: S3Client = boto3.client("s3", endpoint_url=LOCALSTACK_ENDPOINT) |
| 26 | + |
| 27 | + |
| 28 | +def deploy_model(run_id: str = "0"): |
| 29 | + # Put the Model into the correct bucket |
| 30 | + s3.create_bucket(Bucket=f"{MODEL_BUCKET}-{run_id}") |
| 31 | + s3.upload_file(MODEL_TAR, f"{MODEL_BUCKET}-{run_id}", f"{MODEL_NAME}.tar.gz") |
| 32 | + |
| 33 | + # Create the model in sagemaker |
| 34 | + sagemaker.create_model(ModelName=f"{MODEL_NAME}-{run_id}", ExecutionRoleArn=EXECUTION_ROLE_ARN, |
| 35 | + PrimaryContainer={"Image": CONTAINER_IMAGE, |
| 36 | + "ModelDataUrl": f"s3://{MODEL_BUCKET}-{run_id}/{MODEL_NAME}.tar.gz"}) |
| 37 | + sagemaker.create_endpoint_config(EndpointConfigName=f"{CONFIG_NAME}-{run_id}", ProductionVariants=[{ |
| 38 | + "VariantName": f"var-{run_id}", "ModelName": f"{MODEL_NAME}-{run_id}", "InitialInstanceCount": 1, |
| 39 | + "InstanceType": "ml.m5.large" |
| 40 | + }]) |
| 41 | + sagemaker.create_endpoint(EndpointName=f"{ENDPOINT_NAME}-{run_id}", EndpointConfigName=f"{CONFIG_NAME}-{run_id}") |
| 42 | + |
| 43 | + |
| 44 | +def _get_input_dict(): |
| 45 | + X, Y = mnist_to_numpy("data/mnist", train=False) |
| 46 | + mask = random.sample(range(X.shape[0]), 2) |
| 47 | + samples = X[mask] |
| 48 | + |
| 49 | + samples = normalize(samples.astype(np.float32), axis=(1, 2)) |
| 50 | + return { |
| 51 | + "inputs": np.expand_dims(samples, axis=1).tolist() |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | +def _show_predictions(response): |
| 56 | + predictions = np.argmax(np.array(response, dtype=np.float32), axis=1).tolist() |
| 57 | + print(f"Predicted digits: {predictions}") |
| 58 | + |
| 59 | + |
| 60 | +def inference_model_container(run_id: str = "0"): |
| 61 | + ep = sagemaker.describe_endpoint(EndpointName=f"{ENDPOINT_NAME}-{run_id}") |
| 62 | + arn = ep["EndpointArn"] |
| 63 | + tag_list = sagemaker.list_tags(ResourceArn=arn) |
| 64 | + port = "4510" |
| 65 | + for tag in tag_list["Tags"]: |
| 66 | + if tag["Key"] == "_LS_ENDPOINT_PORT_": |
| 67 | + port = tag["Value"] |
| 68 | + inputs = _get_input_dict() |
| 69 | + response = httpx.post(f"http://localhost.localstack.cloud:{port}/invocations", json=inputs, |
| 70 | + headers={"Content-Type": "application/json", "Accept": "application/json"}) |
| 71 | + _show_predictions(json.loads(response.text)) |
| 72 | + |
| 73 | + |
| 74 | +def inference_model_boto3(run_id: str = "0"): |
| 75 | + inputs = _get_input_dict() |
| 76 | + response = sagemaker_runtime.invoke_endpoint(EndpointName=f"{ENDPOINT_NAME}-{run_id}", Body=json.dumps(inputs), |
| 77 | + Accept="application/json", |
| 78 | + ContentType="application/json") |
| 79 | + _show_predictions(json.loads(response["Body"].read())) |
| 80 | + |
| 81 | + |
| 82 | +def _short_uid(): |
| 83 | + import uuid |
| 84 | + |
| 85 | + return str(uuid.uuid4())[:8] |
| 86 | + |
| 87 | + |
| 88 | +if __name__ == '__main__': |
| 89 | + test_run = _short_uid() |
| 90 | + deploy_model(test_run) |
| 91 | + # wait some time to avoid connection resets in log output |
| 92 | + # -> not essential as the container spins up quickly enough within the retries of boto |
| 93 | + time.sleep(2) |
| 94 | + inference_model_boto3(test_run) |
| 95 | + inference_model_container(test_run) |
0 commit comments