2
3

More than 3 years have passed since last update.

Terraformを用いたSageMaker Endpointの構築

Last updated at Posted at 2019-12-31

はじめに

こちらのブログを参考に以下のようなSageMaker EndpointをInvokeするEndpointを構築してみました。

sagemaker_endpoint.png

API Gateway EndpointからSageMaker Endpointを呼び出すLambda関数をトリガーし、予測を行います。

コードはGitHubに上げてあります。
https://github.com/suaaa7/iris-data-endpoint

動作環境

  • macOS Mojave (10.14.6)
  • Terraform (0.12.6)

ファイル構成

$ tree
.
├── LICENSE
├── Makefile
├── README.md
├── config.tf
├── main.tf
├── modules
│   ├── apigateway
│   │   └── main.tf
│   ├── iam
│   │   └── main.tf
│   ├── lambda
│   │   ├── main.tf
│   │   ├── src
│   │   │   └── lambda_function.py
│   │   └── upload
│   │       └── lambda_function.zip
│   └── sagemaker
│       └── main.tf
├── request.sh
├── test.csv
└── variables.tf

本当はmain.tf

  • main.tf
  • variables.tf
  • outputs.tf

に分けるべきだと思うのですが、分けるほどのコード量ではなかったので、main.tfにまとめてしまっています。

SageMaker Endpointについて

推論用インスタンスを立てるために設定が必要な項目はModel・EndpointConfig・Endpointの3つです。
ModelはどのS3のデータをロードするのかと、どのECRのイメージを利用するのかを保持します。

今回は、Irisデータセットのサンプルとしてすでに構築してあるモデル、Dockerイメージを利用します。

  • Location of model artifacts
    • s3://aws-machine-learning-blog/artifacts/decision-trees/model.tar.gz
  • Location of inference code image
    • 305705277353.dkr.ecr.us-east-1.amazonaws.com/decision-trees-sample:latest

参考

TerraformでSageMakerのデプロイ・モデルの更新をする
https://medium.com/mixi-developers/terraformでsagemakerのデプロイ-モデルの更新をする-c1340fa0340d

API Gateway + Lambdaついて

API GatewayとLambdaのモジュールをまとめるか悩みましたが、分けてみました。
このあたりのベストプラクティスが分かっていないので、毎回悩みます。

参考

Serverless Applications with AWS Lambda and API Gateway
https://learn.hashicorp.com/terraform/aws/lambda-api-gateway

動作確認

初期化

$ terraform init

構築

SageMaker EndpointのCreatingには10分ほどかかります。

$ terraform apply

予測

csvには以下のような推論データを含めます。

  • Sepal Length
  • Sepal Width
  • Petal Length
  • Petal Width
test.csv
10,10,10,10

<base_url>には、TerraformのOutputsに出力されるbase_urlを指定してください。

$ curl -X POST -H "Content-Type: text/csv" -d "@test.csv" <base_url>
{"code": 200, "variant": "variant-a", "prediction": "virginica"}

後片付け

$ terraform destroy
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3