SagemakerでPySPHを使用してみる その1


概要

AmazonSageMakerでPySPHを使ってSPH法による流体シミュレーション計算をするために、AmazonSageMakerでPySPHのテストを行ってみる。
AmazonSageMakerの構成とか調べた記事はこちら
AmazonSageMaker周りの知識をいくらか前提とした構成になっています。

その1
その2
その3

手順

  1. AmazonSagemakerの使用準備を整える
  2. シミュレーションを実行する準備
  3. シミュレーションを実行

手順詳細

AmazonSagemakerの使用準備を整える

AmazonSagemakerのSetup

AmazonSagemakerのSetup の内容に沿ってAmazon Sagemakerを利用するための準備をしていく。

ステップ 1: AWS アカウントの作成

省略。いい感じに作る。

ステップ 2: IAM 管理者ユーザーおよびグループの作成

省略。いいかんじにしておく。

ステップ 3: Amazon S3 バケットの作成

SageMakerで使用するAmazon S3バケットを作成します。
Amazon S3はAmazon Web Serviseのストレージサービスです。バケットという単位で利用できます。
ポイント:

  • Sagemakerで使用できるS3バケットのリージョンは制限があったはずなので(要調査)、間違えない
  • 名前に必ずsagemakerを入れる

機械学習でAmazon Sagemakerを使う場合、以下の2つのAmazon S3バケットを作成します。

  • ”モデルトレーニングデータ"のバケット トレーニングジョブで使用するデータを入れる場所です。AIのトレーニング時には教師データをここに配置します。
  • "モデルトレーニング時に Amazon SageMaker が生成するモデルアーティファクト"のバケット トレーニングジョブで生成されるデータを入れる場所です。AIのトレーニング時にはここに生成したモデルが出力されます。

今回は流体シミュレーションを行うので、それぞれ以下のように考えます。

  • "モデルトレーニングデータ"のバケットは使用しない
  • "モデルトレーニング時に Amazon SageMaker が生成するモデルアーティファクト"のバケットは、シミュレーション結果の出力先として使用する

AmazonSagemakerノートブックンスタンスの作成

AmazonSagemakerノートブックインスタンスの作成を参考にしてNotebookインスタンスを作成する。

作成したNotebookインスタンスのJupyterかJupyterLabを開いておく。

シミュレーションを実行する準備

PySPHを使用して計算を行うDockerイメージを構築し、トレーニングアルゴリズムとして使用することでシミュレーションを行います。
機械学習でAmazon Sagemakerを使ってトレーニングを行う場合、既製のアルゴリズムを利用することができます。その場合も内部ではあらかじめ用意されているDockerイメージを参照しているはずです。

Dockerイメージを作成する

シミュレーションに使用するDockerイメージを構築します。

シミュレーションに使用するファイルの作成

trainという名前で、計算処理を行うシェルファイルを作成します。今回は動作確認のため、testを実行します。

train
#!/usr/bin/env bash
pysph test

Dockerファイルの作成

Dockerファイルを以下の内容で作成します。

(未推敲)(もっといい書き方募集してます)

# Build an image that can do training and inference in SageMaker
# This is a Python 2 image that uses the nginx, gunicorn, flask stack
# for serving inferences in a stable way.

FROM nvidia/opencl:devel-ubuntu16.04

MAINTAINER user-name <[email protected]>


RUN apt-get -y update && apt-get install -y\
         wget \
         python3 \
         python3-pip \
         ca-certificates \
         python3-dev 
RUN apt-get install -y build-essential 
RUN apt-get install -y python3-numpy
RUN apt-get install -y python3-pytest 
RUN apt-get install -y cython3

#For pysph
RUN pip3 install pytools
RUN pip3 install h5py
RUN pip3 install pysph

ENV PYTHONUNBUFFERED=TRUE
ENV PYTHONDONTWRITEBYTECODE=TRUE
ENV PATH="/opt/program:${PATH}"

# Set up the program in the image
COPY train /opt/program/
WORKDIR /opt/program

Dockerイメージを生成する準備

まず以下のshファイルを作成します。

(Amazon SageMaker公式のチュートリアルに存在する同名ファイルと同じ。)
(txt fileをクリックすることでファイルを新規作成して内容をコピペ、そのあとファイル名を変更するとよい)

build_and_push.sh
#!/usr/bin/env bash

# This script shows how to build the Docker image and push it to ECR to be ready for use
# by SageMaker.

# The argument to this script is the image name. This will be used as the image on the local
# machine and combined with the account and region to form the repository name for ECR.
image=$1

chmod +x train

if [ "$image" == "" ]
then
    echo "Usage: $0 <image-name>"
    exit 1
fi

# Get the account number associated with the current IAM credentials
account=$(aws sts get-caller-identity --query Account --output text)

if [ $? -ne 0 ]
then
    exit 255
fi


# Get the region defined in the current configuration (default to us-west-2 if none defined)
region=$(aws configure get region)
region=${region:-us-west-2}


fullname="${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest"

# If the repository doesn't exist in ECR, create it.

aws ecr describe-repositories --repository-names "${image}" > /dev/null 2>&1

if [ $? -ne 0 ]
then
    aws ecr create-repository --repository-name "${image}" > /dev/null
fi

# Get the login command from ECR and execute it directly
$(aws ecr get-login --region ${region} --no-include-email)



# Build the docker image locally with the image name and then push it to ECR
# with the full name.

docker build  -t ${image} -f Dockerfile .
docker tag ${image} ${fullname}

docker push ${fullname}

次にターミナルからこのファイルに実行権限を付与します。

なお、ターミナルの初期ワーキングディレクトリとjupyterlabから見えるディレクトリは違います。
jupyterlabを開いたとき最初に見えるディレクトリは、^/SageMaker/の下になっています。

Dockerイメージの生成

ここからJupyter・JupyterLab上のNotebook上で実行していきます。 新しいNotebookを作成しましょう。
conda_python3 のNotebookを作成します。
一行目は以下を入力し、実行します。

import subprocess
print (subprocess.check_output(['./build_and_push.sh', 'pysph-sagemaker']).decode('utf-8'))

先ほど作ったbuild_and_pushを実行しています。その内部では、dockerイメージを生成てECRというサービスにアップロードしています。
初回はかなり時間がかかります。(正確には、ノートブックインスタンスを起動してから最初の実行にかなり時間がかかります。)

(build_and_push時のエラーが見づらいので、もっといい方法を探してます。)

ここで、'pysph-sagemaker'というのが、このノートブックインスタンス上でのDockerイメージの名前になります。これも'sagemaker'が必須です。あとで問題が起こるので名前に'_'(アンダーバー)は使えません。

(一回error:content_checkingを食らいました。なぜかSageMakerフォルダ内にlost+foundというフォルダができていたので、削除したら問題なくdocker buildが通りました。)
(一回sagemakerが名前についてなかったのでECRへの送信がdeniedされました。)

計算処理を実行する

Notebook上で次を実行して、計算処理を実行します。

from sagemaker import get_execution_role
import sagemaker as sage
import os

sess = sage.Session()

imagename = 'pysph-sagemaker' #dockerイメージの名前を指定

account = sess.boto_session.client('sts').get_caller_identity()['Account']
region = sess.boto_session.region_name
image = '{}.dkr.ecr.{}.amazonaws.com/{}'.format(account, region, imagename)

# トレーニングジョブ
# 出力先、使用するインスタンスを指定
sph = sage.estimator.Estimator(image,
                       role, 1, 'ml.c5.4xlarge',
                       output_path="s3://sagemakerbucket-rk1/psph/output",
                       sagemaker_session=sess)

sph.fit()

testの内容が色々表示され、
20xx-xx-xx xx:xx:xx Completed - Training job completed
と表示されればOKです。

(一回imagenameに'_'を使っていたのでここでエラーが起きて先に進めませんでした。)

今回はここまでです。