[AWS] SAFE MLOPS DEPLOYMENT PIPELINE WORKSHOP


들어가기 전


개인 계정으로 다른 리전에서 링크 진행 시 문제가 발생하여, 해당 글을 작성합니다.


반드시 Workshop Guide를 참고하여 진행하길 바랍니다.


이 글은 가이드에서 부족한 부분만 추가하였습니다.


IAM


역할 생성


SageMaker Studio 시작에 필요한 IAM 역할을 생성합니다.


IAM 역할 생성 (사용 사례 – SageMaker)

권한 > 정책연결 > S3 검색 > AmazonS3FullAccess 선택 > 정책연결

두 개의 정책이 연결된 IAM 역할


SageMaker Studio


생성


CloudFormation Stack 생성 전, SageMaker Studio를 시작합니다.


사용자 이름 입력

위에서 생성한 실행 역할 선택

전송 선택

CloudFormation


생성


실습에 사용할 CloudFormation Stack을 생성합니다.


스택 생성 선택

새 리소스 사용(표준) 선택

URL 입력

다음 선택


링크에 URL이 있습니다. 복사하여 사용합니다.

버지니아 북부를 포함하여, 어느 리전에서 사용하여도 가능하도록 수정했어요!


기존 템플릿에서 변화한 내용은 크게 두 가지입니다.


PipelineBucket은 북부 버지니아(us-east-1)에 있으므로, 지역에 따라 달라지지 않도록 리전을 고정합니다.

      ProvisioningArtifactParameters:
        - Description: "SageMaker Safe Deployment Pipeline Project Templates"
          DisableTemplateValidation: false
          Info:
            LoadTemplateFromURL: !Sub "https://${PipelineBucket}.s3.us-east-1.amazonaws.com/pipeline.yml"

또한 S3 리소스를 전체 허용으로 변경하여 객체를 정상적으로 불러올 수 있도록 합니다.

          - Effect: Allow
            Action:
            - "s3:*"
            Resource:
              - "*"

변경된 템플릿을 활용하여 스택 생성을 진행합니다.


스택 이름 입력

SageMakerStudioRoleName 입력 (Studio에 연결한 역할)

다음 선택

이 화면 이후 나머지 값은 기본으로 하여 진행, Stack 생성을 합니다.


SageMaker Studio (2)


실행


Open Studio 선택

링크를 참고하여 순서대로 진행합니다.


Project name 입력 (ex: sagemaker-safe-deployment-proj)

Email Address 입력

Create project 선택

프로젝트 생성이 정상적으로 됐다면, 링크를 따라 계속 진행해주세요.


Dependencies

# Import the latest sagemaker and boto3 SDKs.
import sys
!{sys.executable} -m pip install --upgrade pip
!{sys.executable} -m pip install -qU awscli boto3 "sagemaker>=2.1.0<3" tqdm
!{sys.executable} -m pip install -qU "stepfunctions==2.0.0"
!{sys.executable} -m pip show sagemaker stepfunctions

문제의 Cell


설치할 때 아래와 같은 에러가 발생하나요?

ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
aiobotocore 1.3.3 requires botocore<1.20.107,>=1.20.106, but you have botocore 1.21.15 which is incompatible.

그렇다면 문제의 Cell을 한번 더 실행해주세요.


프로젝트 이름


Notebook dependencies 설치 후 커널 재시작을 했다면, PROJECT_NAME 변수를 변경합니다.


이 때 이름은 위에서 입력했던 프로젝트 이름과 똑같이 입력합니다.


PROJECT_NAME 변수의 값 변경

# Replace `None` with the project name when creating SageMaker Project
# You can find it from the left panel in Studio
PROJECT_NAME = "sagemaker-safe-deployment-proj"

입력한 다음, 다시 링크로 돌아가 진행합니다.


두 개 Cell 실행

# Replace `None` with the project name when creating SageMaker Project
# You can find it from the left panel in Studio
PROJECT_NAME = "sagemaker-safe-deployment-pro"
assert PROJECT_NAME is not None and isinstance(
    PROJECT_NAME, str
), "Please specify the project name as string"

Cell을 누르고 Shift + Enter를 누르면 실행할 수 있어요.

import boto3
from IPython.core.display import HTML, display
def get_provisioned_product_name(project_name):
    region = boto3.Session().region_name
    sc = boto3.client("servicecatalog")
    products = sc.search_provisioned_products(
        Filters={
            "SearchQuery": [
                project_name,
            ]
        }
    )
    pp = products["ProvisionedProducts"]
    if len(pp) != 1:
        print("Invalid provisioned product name. Open the link below and search manually")
        display(
            HTML(
                f'<a target="_blank" href="https://{region}.console.aws.amazon.com/servicecatalog/home?region={region}#provisioned-products">Service Catalog</a>'
            )
        )
        raise ValueError("Invalid provisioned product")
    return pp[0]["Name"]
PROVISIONED_PRODUCT_NAME = get_provisioned_product_name(PROJECT_NAME)
print(
    f"The associated Service Catalog Provisioned Product Name to this SagaMaker project: {PROVISIONED_PRODUCT_NAME}"
)

마찬가지로 Shift + Enter 눌러 실행해주세요.


데이터셋 (Dataset)


링크만 봤을 때 내용이 없어 당황했다면, Studio로 돌아가 이어서 진행합니다. 모든 내용이 mlops.ipynb에 담겨있습니다.

!aws s3 cp 's3://nyc-tlc/trip data/green_tripdata_2018-02.csv' 'nyc-tlc.csv'

Cell을 실행하면서 순서에 맞춰 진행하세요.


시각화 (Visualization)

import seaborn as sns
sample_df = data_df.sample(1000)
sns.scatterplot(data=sample_df, x="duration_minutes", y="trip_distance")

문제의 Cell


혹시 이 Cell을 실행시켰더니 에러가 발생하나요?

/opt/conda/lib/python3.7/site-packages/pandas/core/dtypes/cast.py in construct_1d_arraylike_from_scalar(value, length, dtype)
   1459                 value = ensure_str(value)
   1460
-> 1461         subarr = np.empty(length, dtype=dtype)
   1462         subarr.fill(value)
   1463
TypeError: Cannot interpret '<attribute 'dtype' of 'numpy.generic' objects>' as a data type

그렇다면 Cell을 추가하여 라이브러리를 재설치합니다.


Cell 추가

내용 붙여넣기

Cell 실행

!conda uninstall pandas -y
!conda install pandas=1.2.0 -y
!conda install seaborn -y

설치가 끝나면 Kernel을 재시작합니다.


Kernel 재시작

첫번째 Cell부터 다시 순차적으로 실행합니다. 단, 아래 3개의 Cell은 건너뛰어주세요.

# Import the latest sagemaker and boto3 SDKs.
import sys
!{sys.executable} -m pip install --upgrade pip
!{sys.executable} -m pip install -qU awscli boto3 "sagemaker>=2.1.0<3" tqdm
!{sys.executable} -m pip install -qU "stepfunctions==2.0.0"
!{sys.executable} -m pip show sagemaker stepfunctions

최초 실행 시에만 실행해주세요. 이미 실행한 적이 있다면, 넘어가야합니다.

!aws s3 cp 's3://nyc-tlc/trip data/green_tripdata_2018-02.csv' 'nyc-tlc.csv'

Local에 csv파일을 이미 받았으니 넘어가주세요.

!conda uninstall pandas -y
!conda install pandas=1.2.0 -y
!conda install seaborn -y

이것도 넘어갑니다.


첫번째 Cell부터 순차적으로 실행

이것과 똑같이 나오셨나요?


데이터 분리 (Data Splitting)


학습(train), 검증(validation), 테스트(test) 데이터셋으로 분리합니다.

from sklearn.model_selection import train_test_split
train_df, val_df = train_test_split(data_df, test_size=0.20, random_state=42)
val_df, test_df = train_test_split(val_df, test_size=0.05, random_state=42)
# Reset the index for our test dataframe
test_df.reset_index(inplace=True, drop=True)
print(
    "Size ofn train: {},n val: {},n test: {} ".format(
        train_df.shape[0], val_df.shape[0], test_df.shape[0]
    )
)

sklearn 라이브러리를 활용하여 데이터를 분리합니다.


전체 데이터의 80%를 학습 데이터(0.8), 19%는 검증 데이터(0.2 X 0.95), 1%는 테스트 데이터(0.2 X 0.05)로 사용합니다.


분리한 후 결과(Output)로 크기(Size)를 알 수 있습니다.

Size of
 train: 603736,
 val: 143388,
 test: 7547 

일반적인 비율은 Validation Set과 Test Set를 비슷한 비율로 가져가는데 반해, 이번 workshop에서는 validation set의 비율을 크게 가져갑니다.


데이터 저장(Save)


분리한 데이터를 CSV 파일로 저장합니다.

train_cols = ["total_amount", "duration_minutes", "passenger_count", "trip_distance"]
train_df.to_csv("train.csv", index=False, header=False)
val_df.to_csv("validation.csv", index=False, header=False)

학습 데이터는 train.csv, baseline.csv 두 개의 파일로 저장을 합니다.

train_df.to_csv("train.csv", index=False, header=False)
# Save test and baseline with headers
train_df.to_csv("baseline.csv", index=False, header=True)

baseline 파일은 SageMaker Model Monitor에서 데이터 변화 감지할 때 사용합니다.


이후 진행은 mlops.ipynb 파일을 따라 진행합니다.


마지막으로,

끝까지 읽어주신 모든 분들께 감사드립니다.


다음 글 보기

이전 글 보기

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다