{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# [모듈 5.1] 고급 모델 빌딩 파이프라인 개발 \n", "\n", "이 노트북은 아래와 같은 목차로 진행 됩니다. 전체를 모두 실행시에 완료 시간은 **약 30분** 소요 됩니다.\n", "\n", "- 1. SageMaker 모델 빌드 파이프라인을 이용한 모델 빌드 오케스트레이션\n", "- 2. 파이프라인 개발자 가이드\n", "- 3. 기본 라이브러리 로딩\n", "- 4. 모델 빌딩 파이프라인 의 스텝(Step) 생성\n", " - 4.1 모델 빌딩 파이프라인 변수 생성\n", " - 4.2 캐싱 정의\n", " - 4.3 전처리 스텝 단계 정의\n", " - 4.4 모델 학습을 위한 학습단계 정의\n", " - 4.5 모델 평가 단계\n", " - 4.6 모델 등록 스텝\n", " - 4.7 세이지 메이커 모델 스텝 생성\n", " - 4.8 HPO 스텝\n", " - 4.9 조건 스텝\n", "- 5. 파리마터, 단계, 조건을 조합하여 최종 파이프라인 정의 및 실행\n", "- 6. 세이지 메이커 스튜디오에서 실행 확인 하기\n", "- 7. Pipeline 캐싱 및 파라미터 이용한 실행\n", "- 8. 계보(Lineage)\n", " \n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. SageMaker 모델 빌드 파이프라인을 이용한 모델 빌드 오케스트레이션\n", "\n", "Amazon SageMaker Model building pipeline은 머신러닝 워크플로우를 개발하는 데이터 과학자, 엔지니어들에게 SageMaker작업과 재생산가능한 머신러닝 파이프라인을 오케스트레이션하는 기능을 제공합니다. 또한 커스텀빌드된 모델을 실시간 추론환경이나 배치변환을 통한 추론 실행환경으로 배포하거나, 생성된 아티팩트의 계보(lineage)를 추적하는 기능을 제공합니다. 이 기능들을 통해 모델 아티팩트를 배포하고, 업무환경에서의 워크플로우를 배포/모니터링하고, 간단한 인터페이스를 통해 아티팩트의 계보 추적하고, 머신러닝 애플리케이션 개발의 베스트 프렉티스를 도입하여, 보다 안정적인 머신러닝 애플리케이션 운영환경을 구현할 수 있습니다. \n", "\n", "SageMaker pipeline 서비스는 JSON 선언으로 구현된 SageMaker Pipeline DSL(Domain Specific Language, 도메인종속언어)를 지원합니다. 이 DSL은 파이프라인 파라마터와 SageMaker 작업단계의 DAG(Directed Acyclic Graph)를 정의합니다. SageMaker Python SDK를 이용하면 이 파이프라인 DSL의 생성을 보다 간편하게 할 수 있습니다. \n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. 파이프라인 개발자 가이드\n", "## SageMaker 파이프라인 소개\n", "\n", "![mdp_how_it_works.png](../img/mdp_how_it_works.png)\n", "\n", "\n", "\n", "SageMaker 파이프라인은 다음 기능을 지원하며 본 lab_03_pipelinie 에서 일부를 다루게 됩니다. \n", "\n", "* Processing job steps - 데이터처러 워크로드를 실행하기 위한 SageMaker의 관리형 기능. Feature engineering, 데이터 검증, 모델 평가, 모델 해석 등에 주로 사용됨 \n", "* Training job steps - 학습작업. 모델에게 학습데이터셋을 이용하여 모델에게 예측을 하도록 학습시키는 작업 \n", "* Conditional execution steps - 조건별 실행분기. 파이프라인을 분기시키는 역할.\n", "* Register model steps - 학습이 완료된 모델패키지 리소스를 이후 배포를 위한 모델 레지스트리에 등록하기 \n", "* Create model steps - 추론 엔드포인트 또는 배치 추론을 위한 모델의 생성 \n", "* Transform job steps - 배치추론 작업. 배치작업을 이용하여 노이즈, bias의 제거 등 데이터셋을 전처리하고 대량데이터에 대해 추론을 실행하는 단계\n", "* Pipelines - Workflow DAG. SageMaker 작업과 리소스 생성을 조율하는 단계와 조건을 가짐\n", "* Parametrized Pipeline executions - 특정 파라미터에 따라 파이프라인 실행방식을 변화시키기 \n", "\n", "\n", "- 상세한 개발자 가이드는 아래 참조 하세요.\n", " - [세이지 메이커 모델 빌딩 파이프라인의 개발자 가이드](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines.html)\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. 기본 라이브러리 로딩\n", "\n", "세이지 메이커 관련 라이브러리를 로딩 합니다." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import boto3\n", "import sagemaker\n", "import pandas as pd\n", "import os\n", "\n", "sagemaker_session = sagemaker.session.Session()\n", "role = sagemaker.get_execution_role()\n", "sm_client = boto3.client(\"sagemaker\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.1 노트북 변수 로딩\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "저장된 변수를 확인 합니다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Stored variables and their in-db values:\n", "bucket -> 'sagemaker-us-east-1-057716757052'\n", "claims_data_uri -> 's3://sagemaker-us-east-1-057716757052/sagemaker-w\n", "customers_data_uri -> 's3://sagemaker-us-east-1-057716757052/sagemaker-w\n", "input_data_uri -> 's3://sagemaker-us-east-1-057716757052/sagemaker-w\n", "input_preproc_data_uri -> 's3://sagemaker-us-east-1-057716757052/sagemaker-w\n", "project_prefix -> 'sagemaker-webinar-pipeline-advanced'\n", "test_preproc_data_uri -> 's3://sagemaker-us-east-1-057716757052/sagemaker-w\n", "train_preproc_data_uri -> 's3://sagemaker-us-east-1-057716757052/sagemaker-w\n" ] } ], "source": [ "%store" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "기존 노트북에서 저장한 변수를 로딩 합니다." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "%store -r" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. 모델 빌딩 파이프라인 의 스텝(Step) 생성\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.1 모델 빌딩 파이프라인 변수 생성\n", "\n", "\n", "본 노트북에서 사용하는 파라미터는 다음과 같습니다.\n", "\n", "* `processing_instance_type` - 프로세싱 작업에서 사용할 `ml.*` 인스턴스 타입 \n", "* `processing_instance_count` - 프로세싱 작업에서 사용할 인스턴스 개수 \n", "* `training_instance_type` - 학습작업에서 사용할 `ml.*` 인스턴스 타입\n", "* `model_approval_status` - 학습된 모델을 CI/CD를 목적으로 등록할 때의 승인 상태 (디폴트는 \"PendingManualApproval\")\n", "* `input_data` - 입력데이터에 대한 S3 버킷 URI\n", "\n", "\n", "\n", "파이프라인의 각 스텝에서 사용할 변수를 파라미터 변수로서 정의 합니다.\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "from sagemaker.workflow.parameters import (\n", " ParameterInteger,\n", " ParameterString,\n", " ParameterFloat,\n", ")\n", "\n", "processing_instance_count = ParameterInteger(\n", " name=\"ProcessingInstanceCount\",\n", " default_value=1\n", ")\n", "processing_instance_type = ParameterString(\n", " name=\"ProcessingInstanceType\",\n", " default_value=\"ml.m5.xlarge\"\n", ")\n", "\n", "training_instance_type = ParameterString(\n", " name=\"TrainingInstanceType\",\n", " default_value=\"ml.m5.xlarge\"\n", ")\n", "\n", "training_instance_count = ParameterInteger(\n", " name=\"TrainingInstanceCount\",\n", " default_value=1\n", ")\n", "\n", "model_eval_threshold = ParameterFloat(\n", " name=\"model2eval2threshold\",\n", " default_value=0.85\n", ")\n", "\n", "input_data = ParameterString(\n", " name=\"InputData\",\n", " default_value=input_data_uri,\n", ")\n", "\n", "model_approval_status = ParameterString(\n", " name=\"ModelApprovalStatus\", default_value=\"PendingManualApproval\"\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.2 캐싱 정의\n", "\n", "- 참고: 캐싱 파이프라인 단계: [Caching Pipeline Steps](https://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/pipelines-caching.html)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "from sagemaker.workflow.steps import CacheConfig\n", "\n", "cache_config = CacheConfig(enable_caching=True, \n", " expire_after=\"7d\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.3 전처리 스텝 단계 정의\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "The input argument instance_type of function (sagemaker.image_uris.retrieve) is a pipeline variable (), which is not allowed. The default_value of this Parameter object will be used to override it. Please make sure the default_value is valid.\n" ] } ], "source": [ "from sagemaker.sklearn.processing import SKLearnProcessor\n", "\n", "split_rate = 0.2\n", "framework_version = \"0.23-1\"\n", "\n", "sklearn_processor = SKLearnProcessor(\n", " framework_version=framework_version,\n", " instance_type=processing_instance_type,\n", " instance_count=processing_instance_count,\n", " base_job_name=\"sklearn-fraud-process\",\n", " role=role,\n", ")\n", "# print(\"input_data: \\n\", input_data)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "from sagemaker.processing import ProcessingInput, ProcessingOutput\n", "from sagemaker.workflow.steps import ProcessingStep\n", " \n", "step_process = ProcessingStep(\n", " name=\"Fraud-Advance-Preprocess\",\n", " processor=sklearn_processor,\n", " inputs=[\n", " ProcessingInput(source=input_data, destination='/opt/ml/processing/input'), \n", " ],\n", " outputs=[ProcessingOutput(output_name=\"train\",\n", " source='/opt/ml/processing/output/train'),\n", " ProcessingOutput(output_name=\"test\",\n", " source='/opt/ml/processing/output/test')],\n", " job_arguments=[\"--split_rate\", f\"{split_rate}\"], \n", " code= 'src/preprocessing.py',\n", " cache_config = cache_config, # 캐시 정의\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.4 모델 학습을 위한 학습단계 정의 \n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 하이퍼파라미터 세팅" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "base_hyperparameters = {\n", " \"scale_pos_weight\" : \"29\", \n", " \"max_depth\": \"6\",\n", " \"alpha\" : \"0\", \n", " \"eta\": \"0.3\",\n", " \"min_child_weight\": \"1\",\n", " \"objective\": \"binary:logistic\",\n", " \"num_round\": \"100\",\n", "}\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Estimator 생성\n", "\n", "Estimator 생성시에 인자가 필요 합니다. 주요한 인자만 보겠습니다.\n", "- 사용자 훈련 코드 \"\"xgboost_script.py\"\n", "- 훈련이 끝난 후에 결과인 모델 아티펙트의 경로 \"estimator_output_path\" 지정 합니다. 지정 안할 시에는 디폴트 경로로 저장 됩니다.\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "The input argument instance_type of function (sagemaker.image_uris.retrieve) is a pipeline variable (), which is not allowed. The default_value of this Parameter object will be used to override it. Please make sure the default_value is valid.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "estimator_output_path: \n", " s3://sagemaker-us-east-1-057716757052/sagemaker-webinar-pipeline-advanced/training_jobs\n" ] } ], "source": [ "from sagemaker.xgboost.estimator import XGBoost\n", "\n", "estimator_output_path = f's3://{bucket}/{project_prefix}/training_jobs'\n", "print(\"estimator_output_path: \\n\", estimator_output_path)\n", "\n", "\n", "xgb_train = XGBoost(\n", " entry_point = \"xgboost_script.py\",\n", " source_dir = \"src\",\n", " output_path = estimator_output_path,\n", " hyperparameters = base_hyperparameters,\n", " role = role,\n", " instance_count = training_instance_count,\n", " instance_type = training_instance_type,\n", " framework_version = \"1.0-1\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 모델 훈련 스탭 생성\n", "스텝 생성시에 위에서 생성한 Estimator 입력 및 입력 데이타로서 전처리 데이터가 존재하는 S3 경로를 제공합니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "훈련의 입력이 이전 전처리의 결과가 제공됩니다.\n", "- `step_process.properties.ProcessingOutputConfig.Outputs[\"train\"].S3Output.S3Uri`" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages/sagemaker/workflow/steps.py:445: UserWarning: Profiling is enabled on the provided estimator. The default profiler rule includes a timestamp which will change each time the pipeline is upserted, causing cache misses. If profiling is not needed, set disable_profiler to True on the estimator.\n", " warnings.warn(msg)\n" ] } ], "source": [ "from sagemaker.inputs import TrainingInput\n", "from sagemaker.workflow.steps import TrainingStep\n", "\n", "\n", "step_train = TrainingStep(\n", " name= \"Fraud-Advance-Train\",\n", " estimator=xgb_train,\n", " inputs={\n", " \"train\": TrainingInput(\n", " s3_data=step_process.properties.ProcessingOutputConfig.Outputs[\n", " \"train\"\n", " ].S3Output.S3Uri,\n", " # s3_data= train_preproc_dir_artifact, \n", " content_type=\"text/csv\"\n", " ),\n", " },\n", " cache_config = cache_config, # 캐시 정의 \n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.5 모델 평가 단계" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### SKLearn Processor 생성\n", "\n", "SKLearn Processor 생성시에 인자가 필요 합니다.\n", "\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "The input argument instance_type of function (sagemaker.image_uris.retrieve) is a pipeline variable (), which is not allowed. The default_value of this Parameter object will be used to override it. Please make sure the default_value is valid.\n" ] } ], "source": [ "from sagemaker.processing import ScriptProcessor\n", "\n", "\n", "script_eval = SKLearnProcessor(\n", " framework_version= \"0.23-1\",\n", " role=role,\n", " instance_type=processing_instance_type,\n", " instance_count=1,\n", " base_job_name=\"script-fraud-scratch-eval\",\n", " )\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Property 파일 정의\n", "\n", "- PropertyFile 은 step_eval 단계가 실행 한 후에 모델 평가 지표의 결과 파일 내용을 정의하는데 사용 됩니다.\n", "\n", "```\n", "형식:\n", " = PropertyFile(\n", " name=\"\",\n", " output_name=\"\",\n", " path=\"\"\n", ")\n", "예시:\n", "evaluation_report = PropertyFile(\n", " name=\"EvaluationReport\",\n", " output_name=\"evaluation\",\n", " path=\"evaluation.json\"\n", ")\n", "```\n", "\n", "\n", "- 위의 PropertyFile 의 output_name=\"evaluation\" 이고, 파일 이름은 evaluation.json\" 라는 것을 의미 합니다. \"evaluation.json\" 파일 안에는 아래의 값이 저장이 됩니다.\n", "\n", "```\n", " report_dict = {\n", " \"binary_classification_metrics\": {\n", " \"auc\": {\n", " \"value\": ,\n", " \"standard_deviation\" : \"NaN\",\n", " },\n", " },\n", " }\n", "```\n", "\n", "\n", "- 최종적으로 evaluation.json 안의 \\ 값이 추후 (조건 스텝) 에 사용이 됩니다.\n", "- step_eval 이 실행이 되면 `evaluation.json` 이 S3에 저장이 됩니다.\n", "\n", "\n", "\n", "#### 참고\n", "- 참고 자료: [Property Files and JsonGet](https://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/build-and-manage-propertyfile.html)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "from sagemaker.workflow.properties import PropertyFile\n", "from sagemaker.workflow.steps import ProcessingStep\n", "\n", "from sagemaker.workflow.properties import PropertyFile\n", "\n", "\n", "evaluation_report = PropertyFile(\n", " name=\"EvaluationReport\",\n", " output_name=\"evaluation\",\n", " path=\"evaluation.json\"\n", ")\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 모델 평가 스텝 정의" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "\n", "\n", "step_eval = ProcessingStep(\n", " name= \"Fraud-Advance-Evaluation\",\n", " processor=script_eval,\n", " inputs=[\n", " ProcessingInput(\n", " source= step_train.properties.ModelArtifacts.S3ModelArtifacts,\n", " destination=\"/opt/ml/processing/model\"\n", " ),\n", " ProcessingInput(\n", " source=step_process.properties.ProcessingOutputConfig.Outputs[\n", " \"test\"\n", " ].S3Output.S3Uri,\n", " destination=\"/opt/ml/processing/test\"\n", " )\n", " ],\n", " outputs=[\n", " ProcessingOutput(output_name=\"evaluation\", source=\"/opt/ml/processing/evaluation\"),\n", " ],\n", " code=\"src/evaluation.py\",\n", " cache_config = cache_config, # 캐시 정의 \n", " property_files=[evaluation_report], # 현재 이 라인을 넣으면 에러 발생\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.6 모델 등록 스텝" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 모델 그룹 생성\n", "\n", "- 참고\n", " - 모델 그룹 릭스팅 API: [ListModelPackageGroups](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListModelPackageGroups.html)\n", " - 모델 지표 등록: [Model Quality Metrics](https://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/model-monitor-model-quality-metrics.html)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No model group exists\n", "Create model group\n", "ModelPackageGroup Arn : arn:aws:sagemaker:us-east-1:057716757052:model-package-group/sagemaker-webinar-pipeline-advanced\n" ] } ], "source": [ "model_package_group_name = f\"{project_prefix}\"\n", "model_package_group_input_dict = {\n", " \"ModelPackageGroupName\" : model_package_group_name,\n", " \"ModelPackageGroupDescription\" : \"Sample model package group\"\n", "}\n", "response = sm_client.list_model_package_groups(NameContains=model_package_group_name)\n", "if len(response['ModelPackageGroupSummaryList']) == 0:\n", " print(\"No model group exists\")\n", " print(\"Create model group\") \n", " \n", " create_model_pacakge_group_response = sm_client.create_model_package_group(**model_package_group_input_dict)\n", " print('ModelPackageGroup Arn : {}'.format(create_model_pacakge_group_response['ModelPackageGroupArn'])) \n", "else:\n", " print(f\"{model_package_group_name} exitss\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 모델 평가 메트릭 정의" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "from sagemaker.workflow.step_collections import RegisterModel\n", "\n", "from sagemaker.model_metrics import MetricsSource, ModelMetrics \n", "\n", "\n", "model_metrics = ModelMetrics(\n", " model_statistics=MetricsSource(\n", " s3_uri=\"{}/evaluation.json\".format(\n", " step_eval.arguments[\"ProcessingOutputConfig\"][\"Outputs\"][0][\"S3Output\"][\"S3Uri\"]\n", " ),\n", " content_type=\"application/json\"\n", " )\n", ")\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 모델 등록 스텝 정의" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "step_register = RegisterModel(\n", " name= \"Fraud-Advance-Model_Register\",\n", " estimator=xgb_train,\n", " image_uri= step_train.properties.AlgorithmSpecification.TrainingImage,\n", " model_data= step_train.properties.ModelArtifacts.S3ModelArtifacts,\n", " content_types=[\"text/csv\"],\n", " response_types=[\"text/csv\"],\n", " inference_instances=[\"ml.t2.medium\", \"ml.m5.xlarge\"],\n", " transform_instances=[\"ml.m5.xlarge\"],\n", " model_package_group_name=model_package_group_name,\n", " approval_status=model_approval_status,\n", " model_metrics=model_metrics,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.7 세이지 메이커 모델 스텝 생성\n", "- 아래 두 파리미터의 입력이 이전 스텝의 결과가 제공됩니다.\n", " - image_uri= step_train.properties.AlgorithmSpecification.TrainingImage,\n", " - model_data= step_train.properties.ModelArtifacts.S3ModelArtifacts,\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 세이지 메이커 모델 생성" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "from sagemaker.model import Model\n", " \n", "model = Model(\n", " image_uri= step_train.properties.AlgorithmSpecification.TrainingImage,\n", " model_data= step_train.properties.ModelArtifacts.S3ModelArtifacts,\n", " sagemaker_session=sagemaker_session,\n", " role=role,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 세이지 메이커 모델 스탭 정의" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "from sagemaker.inputs import CreateModelInput\n", "from sagemaker.workflow.steps import CreateModelStep\n", "\n", "\n", "inputs = CreateModelInput(\n", " instance_type=\"ml.m5.large\",\n", " # accelerator_type=\"ml.eia1.medium\",\n", ")\n", "step_create_model = CreateModelStep(\n", " name= \"Fraud-Advance-Create-SageMaker-Model\",\n", " model=model,\n", " inputs=inputs,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.8 HPO 스텝" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 튜닝할 하이퍼파라미터 범위 설정\n", "여기서는 `eta, min_child_weight, alpha, max_depth` 를 튜닝 합니다." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "from sagemaker.tuner import (\n", " IntegerParameter,\n", " CategoricalParameter,\n", " ContinuousParameter,\n", " HyperparameterTuner,\n", ")\n", "\n", "hyperparameter_ranges = {\n", " \"eta\": ContinuousParameter(0, 1),\n", " \"min_child_weight\": ContinuousParameter(1, 10),\n", " \"alpha\": ContinuousParameter(0, 2),\n", " \"max_depth\": IntegerParameter(1, 10),\n", "}\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 튜너 설정 및 생성\n", "- xbg_estimator 정의된 estimator 기술\n", "- `objective_metric_name = \"validation:auc\"` 튜닝을 하고자 하는 지표 기술\n", " - 이 지표의 경우는 훈련 코드에서 정의 및 기록을 해야만 합니다.\n", "- `hyperparameter_ranges` 튜닝하고자 하는 파라미터의 범위 설정\n", "- `max_jobs` 기술\n", " - 총 훈련잡의 갯수 입니다.\n", "- `max_parallel_jobs` 기술\n", " - 병렬로 실행할 훈련잡의 개수 (리소스 제한에 따라서 에러가 발생할 수 있습니다. 이 경우에 줄여 주세요.)\n" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "objective_metric_name = \"validation:auc\"\n", "\n", "tuner = HyperparameterTuner(\n", " xgb_train, objective_metric_name, hyperparameter_ranges, \n", " max_jobs=5,\n", " max_parallel_jobs=5,\n", ")\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 튜닝 단계 정의 \n", "\n" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "from sagemaker.workflow.steps import TuningStep\n", " \n", "step_tuning = TuningStep(\n", " name = \"Fraud-Advance-HPO\",\n", " tuner = tuner,\n", " inputs={\n", " \"train\": TrainingInput(\n", " s3_data=step_process.properties.ProcessingOutputConfig.Outputs[\n", " \"train\"\n", " ].S3Output.S3Uri,\n", " # s3_data= train_preproc_dir_artifact, \n", " content_type=\"text/csv\"\n", " ),\n", " }, \n", " cache_config = cache_config, # 캐시 정의 \n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.9 조건 스텝" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 조건 단계 정의\n", "- 조건 단계에서 사용하는 ConditionLessThanOrEqualTo 에서 evaluation.json 을 로딩하여 내용을 확인\n", "\n", "```\n", "\n", "형식:\n", "cond_lte = ConditionLessThanOrEqualTo(\n", " left=JsonGet(\n", " step=step_eval,\n", " property_file=,\n", " json_path=\"test_metrics.roc.value\",\n", " ),\n", " right=6.0\n", ")\n", "\n", "에시:\n", "cond_lte = ConditionLessThanOrEqualTo(\n", " left=JsonGet(\n", " step=step_eval,\n", " property_file=evaluation_report,\n", " json_path=\"binary_classification_metrics.auc.value\",\n", " ),\n", " right=6.0\n", ")\n", "\n", "\n", "```\n", "\n", "- property_file=evaluation_report 는 위의 모델 평가 스텝에서 정의한 PropertyFile-evaluation_report 를 사용합니다. evaluation_report 에서 정의한 evaluation.json 파일 안의 \"binary_classification_metrics.auc.value\" 의 값을 사용한다는 것을 의미 합니다.\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "The class JsonGet has been renamed in sagemaker>=2.\n", "See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.\n" ] } ], "source": [ "from sagemaker.workflow.conditions import ConditionLessThanOrEqualTo\n", "from sagemaker.workflow.condition_step import (\n", " ConditionStep,\n", " JsonGet,\n", ")\n", "\n", "\n", "cond_lte = ConditionLessThanOrEqualTo(\n", " left=JsonGet(\n", " step=step_eval,\n", " property_file=evaluation_report,\n", " json_path=\"binary_classification_metrics.auc.value\",\n", " ),\n", " # right=8.0\n", " right = model_eval_threshold\n", ")\n", "\n", "step_cond = ConditionStep(\n", " name= \"Fraud-Advance-Condition\",\n", " conditions=[cond_lte],\n", " if_steps=[step_tuning], \n", " else_steps=[step_register, step_create_model], \n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 5. 파리마터, 단계, 조건을 조합하여 최종 파이프라인 정의 및 실행\n", "\n", "\n", "이제 지금까지 생성한 단계들을 하나의 파이프라인으로 조합하고 실행하도록 하겠습니다.\n", "\n", "파이프라인은 name, parameters, steps 속성이 필수적으로 필요합니다. \n", "여기서 파이프라인의 이름은 (account, region) 조합에 대하여 유일(unique))해야 합니다.\n", "우리는 또한 여기서 Experiment 설정을 추가 하여, 실험에 등록 합니다.\n", "\n", "주의:\n", "\n", "- 정의에 사용한 모든 파라미터가 존재해야 합니다.\n", "- 파이프라인으로 전달된 단계(step)들은 실행순서와는 무관합니다. SageMaker Pipeline은 단계가 실행되고 완료될 수 있도록 의존관계를를 해석합니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.1 파이프라인 정의\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "위에서 정의한 아래의 4개의 스텝으로 파이프라인 정의를 합니다.\n", "- steps=[step_process, step_train, step_create_model, step_deploy],\n", "- 아래는 약 20분 정도 소요 됩니다." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "from sagemaker.workflow.pipeline import Pipeline\n", "\n", "project_prefix = 'sagemaker-pipeline-phase2-step-by-step'\n", "\n", "pipeline_name = project_prefix\n", "pipeline = Pipeline(\n", " name=pipeline_name,\n", " parameters=[\n", " processing_instance_type, \n", " processing_instance_count,\n", " training_instance_type, \n", " training_instance_count, \n", " input_data,\n", " model_eval_threshold,\n", " model_approval_status, \n", " ],\n", "# steps=[step_process, step_train, step_register, step_eval, step_cond],\n", " steps=[step_process, step_train, step_eval, step_cond],\n", ")\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.2 파이프라인 정의 확인\n", "위에서 정의한 파이프라인 정의는 Json 형식으로 정의 되어 있습니다." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using provided s3_resource\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "Popping out 'CertifyForMarketplace' from the pipeline definition since it will be overridden in pipeline execution time.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Using provided s3_resource\n" ] }, { "data": { "text/plain": [ "{'Version': '2020-12-01',\n", " 'Metadata': {},\n", " 'Parameters': [{'Name': 'ProcessingInstanceType',\n", " 'Type': 'String',\n", " 'DefaultValue': 'ml.m5.xlarge'},\n", " {'Name': 'ProcessingInstanceCount', 'Type': 'Integer', 'DefaultValue': 1},\n", " {'Name': 'TrainingInstanceType',\n", " 'Type': 'String',\n", " 'DefaultValue': 'ml.m5.xlarge'},\n", " {'Name': 'TrainingInstanceCount', 'Type': 'Integer', 'DefaultValue': 1},\n", " {'Name': 'InputData',\n", " 'Type': 'String',\n", " 'DefaultValue': 's3://sagemaker-us-east-1-057716757052/sagemaker-webinar-pipeline-advanced/input'},\n", " {'Name': 'model2eval2threshold', 'Type': 'Float', 'DefaultValue': 0.85},\n", " {'Name': 'ModelApprovalStatus',\n", " 'Type': 'String',\n", " 'DefaultValue': 'PendingManualApproval'}],\n", " 'PipelineExperimentConfig': {'ExperimentName': {'Get': 'Execution.PipelineName'},\n", " 'TrialName': {'Get': 'Execution.PipelineExecutionId'}},\n", " 'Steps': [{'Name': 'Fraud-Advance-Preprocess',\n", " 'Type': 'Processing',\n", " 'Arguments': {'ProcessingResources': {'ClusterConfig': {'InstanceType': {'Get': 'Parameters.ProcessingInstanceType'},\n", " 'InstanceCount': {'Get': 'Parameters.ProcessingInstanceCount'},\n", " 'VolumeSizeInGB': 30}},\n", " 'AppSpecification': {'ImageUri': '683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-scikit-learn:0.23-1-cpu-py3',\n", " 'ContainerArguments': ['--split_rate', '0.2'],\n", " 'ContainerEntrypoint': ['python3',\n", " '/opt/ml/processing/input/code/preprocessing.py']},\n", " 'RoleArn': 'arn:aws:iam::057716757052:role/sagemaker-notebook-special-webina-SageMakerIamRole-1S4XY7NSZM5CZ',\n", " 'ProcessingInputs': [{'InputName': 'input-1',\n", " 'AppManaged': False,\n", " 'S3Input': {'S3Uri': {'Get': 'Parameters.InputData'},\n", " 'LocalPath': '/opt/ml/processing/input',\n", " 'S3DataType': 'S3Prefix',\n", " 'S3InputMode': 'File',\n", " 'S3DataDistributionType': 'FullyReplicated',\n", " 'S3CompressionType': 'None'}},\n", " {'InputName': 'code',\n", " 'AppManaged': False,\n", " 'S3Input': {'S3Uri': 's3://sagemaker-us-east-1-057716757052/Fraud-Advance-Preprocess-9eb3e47661f2f1f3db35bb21017985f2/input/code/preprocessing.py',\n", " 'LocalPath': '/opt/ml/processing/input/code',\n", " 'S3DataType': 'S3Prefix',\n", " 'S3InputMode': 'File',\n", " 'S3DataDistributionType': 'FullyReplicated',\n", " 'S3CompressionType': 'None'}}],\n", " 'ProcessingOutputConfig': {'Outputs': [{'OutputName': 'train',\n", " 'AppManaged': False,\n", " 'S3Output': {'S3Uri': {'Std:Join': {'On': '/',\n", " 'Values': ['s3:/',\n", " 'sagemaker-us-east-1-057716757052',\n", " 'sagemaker-pipeline-phase2-step-by-step',\n", " {'Get': 'Execution.PipelineExecutionId'},\n", " 'Fraud-Advance-Preprocess',\n", " 'output',\n", " 'train']}},\n", " 'LocalPath': '/opt/ml/processing/output/train',\n", " 'S3UploadMode': 'EndOfJob'}},\n", " {'OutputName': 'test',\n", " 'AppManaged': False,\n", " 'S3Output': {'S3Uri': {'Std:Join': {'On': '/',\n", " 'Values': ['s3:/',\n", " 'sagemaker-us-east-1-057716757052',\n", " 'sagemaker-pipeline-phase2-step-by-step',\n", " {'Get': 'Execution.PipelineExecutionId'},\n", " 'Fraud-Advance-Preprocess',\n", " 'output',\n", " 'test']}},\n", " 'LocalPath': '/opt/ml/processing/output/test',\n", " 'S3UploadMode': 'EndOfJob'}}]}},\n", " 'CacheConfig': {'Enabled': True, 'ExpireAfter': '7d'}},\n", " {'Name': 'Fraud-Advance-Train',\n", " 'Type': 'Training',\n", " 'Arguments': {'AlgorithmSpecification': {'TrainingInputMode': 'File',\n", " 'TrainingImage': '683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-xgboost:1.0-1-cpu-py3'},\n", " 'OutputDataConfig': {'S3OutputPath': 's3://sagemaker-us-east-1-057716757052/sagemaker-webinar-pipeline-advanced/training_jobs'},\n", " 'StoppingCondition': {'MaxRuntimeInSeconds': 86400},\n", " 'ResourceConfig': {'VolumeSizeInGB': 30,\n", " 'InstanceCount': {'Get': 'Parameters.TrainingInstanceCount'},\n", " 'InstanceType': {'Get': 'Parameters.TrainingInstanceType'}},\n", " 'RoleArn': 'arn:aws:iam::057716757052:role/sagemaker-notebook-special-webina-SageMakerIamRole-1S4XY7NSZM5CZ',\n", " 'InputDataConfig': [{'DataSource': {'S3DataSource': {'S3DataType': 'S3Prefix',\n", " 'S3Uri': {'Get': \"Steps.Fraud-Advance-Preprocess.ProcessingOutputConfig.Outputs['train'].S3Output.S3Uri\"},\n", " 'S3DataDistributionType': 'FullyReplicated'}},\n", " 'ContentType': 'text/csv',\n", " 'ChannelName': 'train'}],\n", " 'HyperParameters': {'scale_pos_weight': '\"29\"',\n", " 'max_depth': '\"6\"',\n", " 'alpha': '\"0\"',\n", " 'eta': '\"0.3\"',\n", " 'min_child_weight': '\"1\"',\n", " 'objective': '\"binary:logistic\"',\n", " 'num_round': '\"100\"',\n", " 'sagemaker_submit_directory': '\"s3://sagemaker-us-east-1-057716757052/Fraud-Advance-Train-91c608db27fc3448ae323b46aa94e5ae/source/sourcedir.tar.gz\"',\n", " 'sagemaker_program': '\"xgboost_script.py\"',\n", " 'sagemaker_container_log_level': '20',\n", " 'sagemaker_region': '\"us-east-1\"'},\n", " 'DebugHookConfig': {'S3OutputPath': 's3://sagemaker-us-east-1-057716757052/sagemaker-webinar-pipeline-advanced/training_jobs',\n", " 'CollectionConfigurations': []},\n", " 'ProfilerConfig': {'S3OutputPath': 's3://sagemaker-us-east-1-057716757052/sagemaker-webinar-pipeline-advanced/training_jobs',\n", " 'DisableProfiler': False}},\n", " 'CacheConfig': {'Enabled': True, 'ExpireAfter': '7d'}},\n", " {'Name': 'Fraud-Advance-Evaluation',\n", " 'Type': 'Processing',\n", " 'Arguments': {'ProcessingResources': {'ClusterConfig': {'InstanceType': {'Get': 'Parameters.ProcessingInstanceType'},\n", " 'InstanceCount': 1,\n", " 'VolumeSizeInGB': 30}},\n", " 'AppSpecification': {'ImageUri': '683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-scikit-learn:0.23-1-cpu-py3',\n", " 'ContainerEntrypoint': ['python3',\n", " '/opt/ml/processing/input/code/evaluation.py']},\n", " 'RoleArn': 'arn:aws:iam::057716757052:role/sagemaker-notebook-special-webina-SageMakerIamRole-1S4XY7NSZM5CZ',\n", " 'ProcessingInputs': [{'InputName': 'input-1',\n", " 'AppManaged': False,\n", " 'S3Input': {'S3Uri': {'Get': 'Steps.Fraud-Advance-Train.ModelArtifacts.S3ModelArtifacts'},\n", " 'LocalPath': '/opt/ml/processing/model',\n", " 'S3DataType': 'S3Prefix',\n", " 'S3InputMode': 'File',\n", " 'S3DataDistributionType': 'FullyReplicated',\n", " 'S3CompressionType': 'None'}},\n", " {'InputName': 'input-2',\n", " 'AppManaged': False,\n", " 'S3Input': {'S3Uri': {'Get': \"Steps.Fraud-Advance-Preprocess.ProcessingOutputConfig.Outputs['test'].S3Output.S3Uri\"},\n", " 'LocalPath': '/opt/ml/processing/test',\n", " 'S3DataType': 'S3Prefix',\n", " 'S3InputMode': 'File',\n", " 'S3DataDistributionType': 'FullyReplicated',\n", " 'S3CompressionType': 'None'}},\n", " {'InputName': 'code',\n", " 'AppManaged': False,\n", " 'S3Input': {'S3Uri': 's3://sagemaker-us-east-1-057716757052/Fraud-Advance-Evaluation-955a33142036ab10f5b2dc96b96cd633/input/code/evaluation.py',\n", " 'LocalPath': '/opt/ml/processing/input/code',\n", " 'S3DataType': 'S3Prefix',\n", " 'S3InputMode': 'File',\n", " 'S3DataDistributionType': 'FullyReplicated',\n", " 'S3CompressionType': 'None'}}],\n", " 'ProcessingOutputConfig': {'Outputs': [{'OutputName': 'evaluation',\n", " 'AppManaged': False,\n", " 'S3Output': {'S3Uri': 's3://sagemaker-us-east-1-057716757052/Fraud-Advance-Evaluation-955a33142036ab10f5b2dc96b96cd633/output/evaluation',\n", " 'LocalPath': '/opt/ml/processing/evaluation',\n", " 'S3UploadMode': 'EndOfJob'}}]}},\n", " 'CacheConfig': {'Enabled': True, 'ExpireAfter': '7d'},\n", " 'PropertyFiles': [{'PropertyFileName': 'EvaluationReport',\n", " 'OutputName': 'evaluation',\n", " 'FilePath': 'evaluation.json'}]},\n", " {'Name': 'Fraud-Advance-Condition',\n", " 'Type': 'Condition',\n", " 'Arguments': {'Conditions': [{'Type': 'LessThanOrEqualTo',\n", " 'LeftValue': {'Std:JsonGet': {'PropertyFile': {'Get': 'Steps.Fraud-Advance-Evaluation.PropertyFiles.EvaluationReport'},\n", " 'Path': 'binary_classification_metrics.auc.value'}},\n", " 'RightValue': {'Get': 'Parameters.model2eval2threshold'}}],\n", " 'IfSteps': [{'Name': 'Fraud-Advance-HPO',\n", " 'Type': 'Tuning',\n", " 'Arguments': {'HyperParameterTuningJobConfig': {'Strategy': 'Bayesian',\n", " 'ResourceLimits': {'MaxNumberOfTrainingJobs': 5,\n", " 'MaxParallelTrainingJobs': 5},\n", " 'TrainingJobEarlyStoppingType': 'Off',\n", " 'HyperParameterTuningJobObjective': {'Type': 'Maximize',\n", " 'MetricName': 'validation:auc'},\n", " 'ParameterRanges': {'ContinuousParameterRanges': [{'Name': 'eta',\n", " 'MinValue': '0',\n", " 'MaxValue': '1',\n", " 'ScalingType': 'Auto'},\n", " {'Name': 'min_child_weight',\n", " 'MinValue': '1',\n", " 'MaxValue': '10',\n", " 'ScalingType': 'Auto'},\n", " {'Name': 'alpha',\n", " 'MinValue': '0',\n", " 'MaxValue': '2',\n", " 'ScalingType': 'Auto'}],\n", " 'CategoricalParameterRanges': [],\n", " 'IntegerParameterRanges': [{'Name': 'max_depth',\n", " 'MinValue': '1',\n", " 'MaxValue': '10',\n", " 'ScalingType': 'Auto'}]}},\n", " 'TrainingJobDefinition': {'StaticHyperParameters': {'scale_pos_weight': '\"29\"',\n", " 'objective': '\"binary:logistic\"',\n", " 'num_round': '\"100\"',\n", " 'sagemaker_submit_directory': '\"s3://sagemaker-us-east-1-057716757052/sagemaker-xgboost-2023-05-01-12-49-48-887/source/sourcedir.tar.gz\"',\n", " 'sagemaker_program': '\"xgboost_script.py\"',\n", " 'sagemaker_container_log_level': '20',\n", " 'sagemaker_job_name': '\"sagemaker-xgboost-2023-05-01-12-49-48-887\"',\n", " 'sagemaker_region': '\"us-east-1\"',\n", " 'sagemaker_estimator_class_name': '\"XGBoost\"',\n", " 'sagemaker_estimator_module': '\"sagemaker.xgboost.estimator\"'},\n", " 'RoleArn': 'arn:aws:iam::057716757052:role/sagemaker-notebook-special-webina-SageMakerIamRole-1S4XY7NSZM5CZ',\n", " 'OutputDataConfig': {'S3OutputPath': 's3://sagemaker-us-east-1-057716757052/sagemaker-webinar-pipeline-advanced/training_jobs'},\n", " 'StoppingCondition': {'MaxRuntimeInSeconds': 86400},\n", " 'HyperParameterTuningResourceConfig': {'InstanceCount': {'Get': 'Parameters.TrainingInstanceCount'},\n", " 'InstanceType': {'Get': 'Parameters.TrainingInstanceType'},\n", " 'VolumeSizeInGB': 30},\n", " 'AlgorithmSpecification': {'TrainingInputMode': 'File',\n", " 'TrainingImage': '683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-xgboost:1.0-1-cpu-py3'},\n", " 'InputDataConfig': [{'DataSource': {'S3DataSource': {'S3DataType': 'S3Prefix',\n", " 'S3Uri': {'Get': \"Steps.Fraud-Advance-Preprocess.ProcessingOutputConfig.Outputs['train'].S3Output.S3Uri\"},\n", " 'S3DataDistributionType': 'FullyReplicated'}},\n", " 'ContentType': 'text/csv',\n", " 'ChannelName': 'train'}]}},\n", " 'CacheConfig': {'Enabled': True, 'ExpireAfter': '7d'}}],\n", " 'ElseSteps': [{'Name': 'Fraud-Advance-Model_Register-RegisterModel',\n", " 'Type': 'RegisterModel',\n", " 'Arguments': {'ModelPackageGroupName': 'sagemaker-webinar-pipeline-advanced',\n", " 'ModelMetrics': {'ModelQuality': {'Statistics': {'ContentType': 'application/json',\n", " 'S3Uri': 's3://sagemaker-us-east-1-057716757052/Fraud-Advance-Evaluation-955a33142036ab10f5b2dc96b96cd633/output/evaluation/evaluation.json'}},\n", " 'Bias': {},\n", " 'Explainability': {}},\n", " 'InferenceSpecification': {'Containers': [{'Image': {'Get': 'Steps.Fraud-Advance-Train.AlgorithmSpecification.TrainingImage'},\n", " 'ModelDataUrl': {'Get': 'Steps.Fraud-Advance-Train.ModelArtifacts.S3ModelArtifacts'}}],\n", " 'SupportedContentTypes': ['text/csv'],\n", " 'SupportedResponseMIMETypes': ['text/csv'],\n", " 'SupportedRealtimeInferenceInstanceTypes': ['ml.t2.medium',\n", " 'ml.m5.xlarge'],\n", " 'SupportedTransformInstanceTypes': ['ml.m5.xlarge']},\n", " 'ModelApprovalStatus': {'Get': 'Parameters.ModelApprovalStatus'}}},\n", " {'Name': 'Fraud-Advance-Create-SageMaker-Model',\n", " 'Type': 'Model',\n", " 'Arguments': {'ExecutionRoleArn': 'arn:aws:iam::057716757052:role/sagemaker-notebook-special-webina-SageMakerIamRole-1S4XY7NSZM5CZ',\n", " 'PrimaryContainer': {'Image': {'Get': 'Steps.Fraud-Advance-Train.AlgorithmSpecification.TrainingImage'},\n", " 'Environment': {},\n", " 'ModelDataUrl': {'Get': 'Steps.Fraud-Advance-Train.ModelArtifacts.S3ModelArtifacts'}}}}]}}]}" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import json\n", "\n", "definition = json.loads(pipeline.definition())\n", "definition" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.3 파이프라인 정의를 제출하고 실행하기 \n", "\n", "파이프라인 정의를 파이프라인 서비스에 제출합니다. 함께 전달되는 역할(role)을 이용하여 AWS에서 파이프라인을 생성하고 작업의 각 단계를 실행할 것입니다. " ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "Popping out 'CertifyForMarketplace' from the pipeline definition since it will be overridden in pipeline execution time.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Using provided s3_resource\n", "Using provided s3_resource\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "No finished training job found associated with this estimator. Please make sure this estimator is only used for building workflow config\n", "Popping out 'CertifyForMarketplace' from the pipeline definition since it will be overridden in pipeline execution time.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Using provided s3_resource\n", "Using provided s3_resource\n" ] } ], "source": [ "pipeline.upsert(role_arn=role)\n", "execution = pipeline.start()" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'PipelineArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step',\n", " 'PipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf',\n", " 'PipelineExecutionDisplayName': 'execution-1682945391089',\n", " 'PipelineExecutionStatus': 'Executing',\n", " 'CreationTime': datetime.datetime(2023, 5, 1, 12, 49, 50, 974000, tzinfo=tzlocal()),\n", " 'LastModifiedTime': datetime.datetime(2023, 5, 1, 12, 49, 50, 974000, tzinfo=tzlocal()),\n", " 'CreatedBy': {},\n", " 'LastModifiedBy': {},\n", " 'ResponseMetadata': {'RequestId': 'db3ce70f-0eea-47bb-bb74-4e01b7620688',\n", " 'HTTPStatusCode': 200,\n", " 'HTTPHeaders': {'x-amzn-requestid': 'db3ce70f-0eea-47bb-bb74-4e01b7620688',\n", " 'content-type': 'application/x-amz-json-1.1',\n", " 'content-length': '441',\n", " 'date': 'Mon, 01 May 2023 12:49:51 GMT'},\n", " 'RetryAttempts': 0}}" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "execution.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.4 파이프라인 실행 기다리기" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "execution.wait()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "실행이 완료될 때까지 기다립니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "실행된 단계들을 리스트업합니다. 파이프라인의 단계실행 서비스에 의해 시작되거나 완료된 단계를 보여줍니다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.5 파이프라인 실행 단계 기록 보기" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'StepName': 'Fraud-Advance-HPO',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 1, 5, 173000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 4, 34, 432000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'TuningJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:hyper-parameter-tuning-job/ptk818ucwlgf-fraud-a-hseaxwn5ad'}}},\n", " {'StepName': 'Fraud-Advance-Condition',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 1, 3, 998000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 1, 4, 430000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'Condition': {'Outcome': 'True'}}},\n", " {'StepName': 'Fraud-Advance-Evaluation',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 12, 56, 27, 189000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 1, 3, 314000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'ProcessingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:processing-job/pipelines-ptk818ucwlgf-Fraud-Advance-Evalua-XPz31rfC8Q'}}},\n", " {'StepName': 'Fraud-Advance-Train',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 12, 54, 5, 739000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 12, 56, 26, 583000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'TrainingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:training-job/pipelines-ptk818ucwlgf-Fraud-Advance-Train-GozJPnx0HC'}}},\n", " {'StepName': 'Fraud-Advance-Preprocess',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 12, 49, 52, 98000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 12, 54, 4, 603000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'ProcessingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:processing-job/pipelines-ptk818ucwlgf-Fraud-Advance-Prepro-VgEV6kr5Gt'}}}]" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "execution.list_steps()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 6. 세이지 메이커 스튜디오에서 실행 확인 하기\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![hpo-pipeline.png](img/hpo-pipeline.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 7. Pipeline 캐싱 및 파라미터 이용한 실행\n", "- 캐싱은 2021년 7월 현재 Training, Processing, Transform 의 Step에 적용이 되어 있습니다.\n", "- 상세 사항은 여기를 확인하세요. --> [캐싱 파이프라인 단계](https://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/pipelines-caching.html)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7.1 캐싱을 이용한 파이프라인 실행\n", "생성한 파이프라인을 다른 파라미터값을 이용하여 다시 실행할 수 있습니다. 파라미터정보는 딕셔너리 형태로 파라미터이름과 값을 지정하여 전달하면 디폴트값을 오버라이드하게 됩니다. \n", "\n", "모델의 성능에 따라 이번에는 컴퓨팅최적화된 인스턴스 타입을 이용하여 파이프라인을 실행하고 승인 상태를 자동으로 \"Approved\"로 설정하고 싶다면 다음 셀의 코드를 실행할 수 있습니다. 모델의 승인상태가 \"Approved\"라는 의미는 `RegisterModel` 단계에서 패키지버전이 등록될 때 자동으로 CI/CD 파이프라인에 의해 배포가능한 상태가 된다는 것을 의미합니다. 이후 배포파이프라인 프로세스는 SageMaker project를 통하여 자동화할 수 있습니다. \n", "\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "is_cache = True" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'StepName': 'Fraud-Advance-Model_Register-RegisterModel',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 4, 603000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 5, 748000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'RegisterModel': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:model-package/sagemaker-webinar-pipeline-advanced/1'}}},\n", " {'StepName': 'Fraud-Advance-Create-SageMaker-Model',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 4, 603000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 6, 73000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'Model': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:model/pipelines-a2prwtopeob6-fraud-advance-create-cscljotkob'}}},\n", " {'StepName': 'Fraud-Advance-Condition',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 2, 652000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 3, 292000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'Condition': {'Outcome': 'False'}}},\n", " {'StepName': 'Fraud-Advance-Evaluation',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 1, 98000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 1, 839000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'},\n", " 'AttemptCount': 0,\n", " 'Metadata': {'ProcessingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:processing-job/pipelines-ptk818ucwlgf-Fraud-Advance-Evalua-XPz31rfC8Q'}}},\n", " {'StepName': 'Fraud-Advance-Train',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 4, 59, 634000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 0, 284000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'},\n", " 'AttemptCount': 0,\n", " 'Metadata': {'TrainingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:training-job/pipelines-ptk818ucwlgf-Fraud-Advance-Train-GozJPnx0HC'}}},\n", " {'StepName': 'Fraud-Advance-Preprocess',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 4, 57, 841000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 4, 58, 558000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'},\n", " 'AttemptCount': 0,\n", " 'Metadata': {'ProcessingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:processing-job/pipelines-ptk818ucwlgf-Fraud-Advance-Prepro-VgEV6kr5Gt'}}}]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 9.87 ms, sys: 3.88 ms, total: 13.8 ms\n", "Wall time: 10.5 s\n" ] } ], "source": [ "%%time \n", "\n", "from IPython.display import display as dp\n", "import time\n", "\n", "if is_cache:\n", " execution = pipeline.start(\n", " parameters=dict(\n", " model2eval2threshold=0.8,\n", " )\n", " ) \n", " \n", " # execution = pipeline.start()\n", " time.sleep(10)\n", " dp(execution.list_steps()) \n", " execution.wait()\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'StepName': 'Fraud-Advance-Model_Register-RegisterModel',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 4, 603000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 5, 748000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'RegisterModel': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:model-package/sagemaker-webinar-pipeline-advanced/1'}}},\n", " {'StepName': 'Fraud-Advance-Create-SageMaker-Model',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 4, 603000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 6, 73000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'Model': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:model/pipelines-a2prwtopeob6-fraud-advance-create-cscljotkob'}}},\n", " {'StepName': 'Fraud-Advance-Condition',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 2, 652000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 3, 292000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'AttemptCount': 0,\n", " 'Metadata': {'Condition': {'Outcome': 'False'}}},\n", " {'StepName': 'Fraud-Advance-Evaluation',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 1, 98000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 1, 839000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'},\n", " 'AttemptCount': 0,\n", " 'Metadata': {'ProcessingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:processing-job/pipelines-ptk818ucwlgf-Fraud-Advance-Evalua-XPz31rfC8Q'}}},\n", " {'StepName': 'Fraud-Advance-Train',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 4, 59, 634000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 0, 284000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'},\n", " 'AttemptCount': 0,\n", " 'Metadata': {'TrainingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:training-job/pipelines-ptk818ucwlgf-Fraud-Advance-Train-GozJPnx0HC'}}},\n", " {'StepName': 'Fraud-Advance-Preprocess',\n", " 'StartTime': datetime.datetime(2023, 5, 1, 13, 4, 57, 841000, tzinfo=tzlocal()),\n", " 'EndTime': datetime.datetime(2023, 5, 1, 13, 4, 58, 558000, tzinfo=tzlocal()),\n", " 'StepStatus': 'Succeeded',\n", " 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'},\n", " 'AttemptCount': 0,\n", " 'Metadata': {'ProcessingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:processing-job/pipelines-ptk818ucwlgf-Fraud-Advance-Prepro-VgEV6kr5Gt'}}}]" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "if is_cache:\n", " dp(execution.list_steps())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7.1 캐싱을 이용한 파이프라인 실행 결과 보기" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![cache-pipeline-result.png](img/cache-pipeline-result.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 8. 계보(Lineage)\n", "\n", "파이프라인에 의해 생성된 아티팩트의 계보를 살펴봅니다." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'StepName': 'Fraud-Advance-Preprocess', 'StartTime': datetime.datetime(2023, 5, 1, 13, 4, 57, 841000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2023, 5, 1, 13, 4, 58, 558000, tzinfo=tzlocal()), 'StepStatus': 'Succeeded', 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'}, 'AttemptCount': 0, 'Metadata': {'ProcessingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:processing-job/pipelines-ptk818ucwlgf-Fraud-Advance-Prepro-VgEV6kr5Gt'}}}\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Name/SourceDirectionTypeAssociation TypeLineage Type
0s3://...bb21017985f2/input/code/preprocessing.pyInputDataSetContributedToartifact
1s3://...agemaker-webinar-pipeline-advanced/inputInputDataSetContributedToartifact
268331...om/sagemaker-scikit-learn:0.23-1-cpu-py3InputImageContributedToartifact
3s3://...lgf/Fraud-Advance-Preprocess/output/testOutputDataSetProducedartifact
4s3://...gf/Fraud-Advance-Preprocess/output/trainOutputDataSetProducedartifact
\n", "
" ], "text/plain": [ " Name/Source Direction Type \\\n", "0 s3://...bb21017985f2/input/code/preprocessing.py Input DataSet \n", "1 s3://...agemaker-webinar-pipeline-advanced/input Input DataSet \n", "2 68331...om/sagemaker-scikit-learn:0.23-1-cpu-py3 Input Image \n", "3 s3://...lgf/Fraud-Advance-Preprocess/output/test Output DataSet \n", "4 s3://...gf/Fraud-Advance-Preprocess/output/train Output DataSet \n", "\n", " Association Type Lineage Type \n", "0 ContributedTo artifact \n", "1 ContributedTo artifact \n", "2 ContributedTo artifact \n", "3 Produced artifact \n", "4 Produced artifact " ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "{'StepName': 'Fraud-Advance-Train', 'StartTime': datetime.datetime(2023, 5, 1, 13, 4, 59, 634000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 0, 284000, tzinfo=tzlocal()), 'StepStatus': 'Succeeded', 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'}, 'AttemptCount': 0, 'Metadata': {'TrainingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:training-job/pipelines-ptk818ucwlgf-Fraud-Advance-Train-GozJPnx0HC'}}}\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Name/SourceDirectionTypeAssociation TypeLineage Type
0s3://...gf/Fraud-Advance-Preprocess/output/trainInputDataSetContributedToartifact
168331...naws.com/sagemaker-xgboost:1.0-1-cpu-py3InputImageContributedToartifact
2s3://...nce-Train-GozJPnx0HC/output/model.tar.gzOutputModelProducedartifact
\n", "
" ], "text/plain": [ " Name/Source Direction Type \\\n", "0 s3://...gf/Fraud-Advance-Preprocess/output/train Input DataSet \n", "1 68331...naws.com/sagemaker-xgboost:1.0-1-cpu-py3 Input Image \n", "2 s3://...nce-Train-GozJPnx0HC/output/model.tar.gz Output Model \n", "\n", " Association Type Lineage Type \n", "0 ContributedTo artifact \n", "1 ContributedTo artifact \n", "2 Produced artifact " ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "{'StepName': 'Fraud-Advance-Evaluation', 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 1, 98000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 1, 839000, tzinfo=tzlocal()), 'StepStatus': 'Succeeded', 'CacheHitResult': {'SourcePipelineExecutionArn': 'arn:aws:sagemaker:us-east-1:057716757052:pipeline/sagemaker-pipeline-phase2-step-by-step/execution/ptk818ucwlgf'}, 'AttemptCount': 0, 'Metadata': {'ProcessingJob': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:processing-job/pipelines-ptk818ucwlgf-Fraud-Advance-Evalua-XPz31rfC8Q'}}}\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Name/SourceDirectionTypeAssociation TypeLineage Type
0s3://...5b2dc96b96cd633/input/code/evaluation.pyInputDataSetContributedToartifact
1s3://...lgf/Fraud-Advance-Preprocess/output/testInputDataSetContributedToartifact
2s3://...nce-Train-GozJPnx0HC/output/model.tar.gzInputModelContributedToartifact
368331...om/sagemaker-scikit-learn:0.23-1-cpu-py3InputImageContributedToartifact
4s3://...36ab10f5b2dc96b96cd633/output/evaluationOutputDataSetProducedartifact
\n", "
" ], "text/plain": [ " Name/Source Direction Type \\\n", "0 s3://...5b2dc96b96cd633/input/code/evaluation.py Input DataSet \n", "1 s3://...lgf/Fraud-Advance-Preprocess/output/test Input DataSet \n", "2 s3://...nce-Train-GozJPnx0HC/output/model.tar.gz Input Model \n", "3 68331...om/sagemaker-scikit-learn:0.23-1-cpu-py3 Input Image \n", "4 s3://...36ab10f5b2dc96b96cd633/output/evaluation Output DataSet \n", "\n", " Association Type Lineage Type \n", "0 ContributedTo artifact \n", "1 ContributedTo artifact \n", "2 ContributedTo artifact \n", "3 ContributedTo artifact \n", "4 Produced artifact " ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "{'StepName': 'Fraud-Advance-Condition', 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 2, 652000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 3, 292000, tzinfo=tzlocal()), 'StepStatus': 'Succeeded', 'AttemptCount': 0, 'Metadata': {'Condition': {'Outcome': 'False'}}}\n" ] }, { "data": { "text/plain": [ "None" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "{'StepName': 'Fraud-Advance-Create-SageMaker-Model', 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 4, 603000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 6, 73000, tzinfo=tzlocal()), 'StepStatus': 'Succeeded', 'AttemptCount': 0, 'Metadata': {'Model': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:model/pipelines-a2prwtopeob6-fraud-advance-create-cscljotkob'}}}\n" ] }, { "data": { "text/plain": [ "None" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "{'StepName': 'Fraud-Advance-Model_Register-RegisterModel', 'StartTime': datetime.datetime(2023, 5, 1, 13, 5, 4, 603000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2023, 5, 1, 13, 5, 5, 748000, tzinfo=tzlocal()), 'StepStatus': 'Succeeded', 'AttemptCount': 0, 'Metadata': {'RegisterModel': {'Arn': 'arn:aws:sagemaker:us-east-1:057716757052:model-package/sagemaker-webinar-pipeline-advanced/1'}}}\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Name/SourceDirectionTypeAssociation TypeLineage Type
0s3://...nce-Train-GozJPnx0HC/output/model.tar.gzInputModelContributedToartifact
168331...naws.com/sagemaker-xgboost:1.0-1-cpu-py3InputImageContributedToartifact
2sagemaker-webinar-pipeline-advanced-1-PendingM...InputApprovalContributedToaction
3sagemaker-webinar-pipeline-advanced-1682945375...OutputModelGroupAssociatedWithcontext
\n", "
" ], "text/plain": [ " Name/Source Direction Type \\\n", "0 s3://...nce-Train-GozJPnx0HC/output/model.tar.gz Input Model \n", "1 68331...naws.com/sagemaker-xgboost:1.0-1-cpu-py3 Input Image \n", "2 sagemaker-webinar-pipeline-advanced-1-PendingM... Input Approval \n", "3 sagemaker-webinar-pipeline-advanced-1682945375... Output ModelGroup \n", "\n", " Association Type Lineage Type \n", "0 ContributedTo artifact \n", "1 ContributedTo artifact \n", "2 ContributedTo action \n", "3 AssociatedWith context " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import time\n", "from sagemaker.lineage.visualizer import LineageTableVisualizer\n", "\n", "\n", "viz = LineageTableVisualizer(sagemaker.session.Session())\n", "for execution_step in reversed(execution.list_steps()):\n", " print(execution_step)\n", " display(viz.show(pipeline_execution_step=execution_step))\n", " time.sleep(1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "instance_type": "ml.m5.large", "kernelspec": { "display_name": "conda_python3", "language": "python", "name": "conda_python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.8" } }, "nbformat": 4, "nbformat_minor": 4 }