

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Autopilot 모델 배포 및 예측
<a name="autopilot-deploy-models"></a>

이 Amazon SageMaker Autopilot 안내서는 모델을 배포하고, 실시간 추론을 설정하고, 배치 작업으로 추론을 실행하는 단계를 포함하고 있습니다.

Autopilot 모델을 훈련한 후, 다음 두 가지 방법 중 하나로 모델을 배포하여 예측을 가져올 수 있습니다.

1. [실시간 추론을 위한 모델 배포](autopilot-deploy-models-realtime.md)을 이용해 엔드포인트를 설정하고 대화형 방식으로 예측을 획득합니다. 실시간 추론은 실시간, 대화형, 짧은 지연 시간이 요구되는 추론 워크로드에 적합합니다.

1. [배치 추론 작업 실행](autopilot-deploy-models-batch.md)을 이용해 전체 데이터세트의 배치 관찰에서 병렬로 예측합니다. 대규모 데이터세트나 모델 예측 요청에 대한 즉각적인 응답이 필요하지 않은 경우 배치 추론을 사용하는 것이 좋습니다.

**참고**  
불필요한 비용 발생을 방지하려면: 모델 배포를 통해 생성된 엔드포인트와 리소스가 더 이상 필요하지 않은 후에는 해당 엔드포인트와 리소스를 삭제할 수 있습니다. 리전별 인스턴스 요금에 대한 자세한 내용은 [Amazon SageMaker 요금](https://aws.amazon.com/sagemaker/pricing/)을 참고하세요.

# 실시간 추론을 위한 모델 배포
<a name="autopilot-deploy-models-realtime"></a>

실시간 추론은 실시간, 대화형, 짧은 지연 시간이 요구되는 추론 워크로드에 적합합니다. 이 섹션에서는 실시간 추론을 사용하여 모델에서 대화형 방식으로 예측을 얻는 방법을 보여줍니다.

Autopilot 실험에서 최상의 검증 지표를 생성한 모델을 배포하기 위한 몇 가지 옵션이 있습니다. 예를 들어 SageMaker Studio Classic에서 Autopilot을 사용하는 경우 모델을 자동 또는 수동으로 배포할 수 있습니다. SageMaker API를 사용하여 Autopilot 모델을 수동으로 배포할 수도 있습니다.

다음 탭은 모델 배포를 위한 세 가지 옵션을 보여줍니다. 이 지침에서는 Autopilot으로 모델을 이미 생성했다고 가정합니다. 모델이 없는 경우 [AutoML API를 사용하여 테이블 형식 데이터에 대한 회귀 또는 분류 작업 생성](autopilot-automate-model-development-create-experiment.md) 섹션을 참조하세요. 각 옵션의 예를 보려면 각 탭을 여세요.

## Autopilot 사용자 인터페이스 (UI)를 사용하여 배포
<a name="autopilot-deploy-models-realtime-ui"></a>

Autopilot UI에는 모델 배포를 탐색하는 데 도움이 되는 유용한 드롭다운 메뉴, 토글, 툴팁 등이 포함되어 있습니다. 자동 또는 수동 절차 중 하나를 이용하여 배포할 수 있습니다.
+ **자동 배포**: Autopilot 실험에서 나온 최적의 모델을 엔드포인트에 자동으로 배포

  1. SageMaker Studio Classic에서 [실험을 생성합니다](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-automate-model-development-create-experiment.html).

  1. **자동 배포** 값을 **예**로 전환합니다.
**참고**  
**리전 내 엔드포인트 인스턴스에 대한 기본 리소스 할당량이나 고객 할당량이 너무 제한적일 경우 자동 배포가 실패합니다.** 하이퍼파라미터 최적화(HPO) 모드에서는 ml.m5.2xlarge 인스턴스가 2개 이상 있어야 합니다. 앙상블링 모드에서는 ml.m5.12xlarge 인스턴스가 하나 이상 있어야 합니다. 할당량과 관련된 오류가 발생하는 경우 SageMaker AI 엔드포인트 인스턴스에 대한 [서비스 한도 증가를 요청](https://docs.aws.amazon.com/servicequotas/latest/userguide/request-quota-increase.html)할 수 있습니다.
+ **자동 배포**: Autopilot 실험에서 나온 최적의 모델을 엔드포인트에 수동으로 배포

  1. SageMaker Studio Classic에서 [실험을 생성합니다](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-automate-model-development-create-experiment.html).

  1. **자동 배포** 값을 **아니요**로 전환합니다.

  1. **모델** 이름에서 배포하려는 모델을 선택합니다.

  1. 리더보드 오른쪽에 있는 주황색 **배포 및 고급 설정** 버튼을 선택합니다. 그러면 새 탭이 열립니다.

  1. 엔드포인트 이름, 인스턴스 유형 및 기타 선택적 정보를 구성합니다.

  1.  엔드포인트에 배포할 주황색 **배포 모델**을 선택합니다.

  1. 엔드포인트 섹션으로 이동하여 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/)에서 엔드포인트 생성 프로세스의 진행 상황을 확인하세요. 해당 섹션은 탐색 패널의 **추론** 드롭다운 메뉴에 있습니다.

  1. 아래와 같이 엔드포인트 상태가 **생성 중**에서 **서비스 중**으로 변경되면 Studio Classic으로 돌아가 엔드포인트를 간접적으로 호출합니다.  
![\[SageMaker AI 콘솔: 엔드포인트를 만들거나 엔드포인트 상태를 확인할 수 있는 엔드포인트 페이지.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/autopilot/autopilot-check-progress.PNG)

## SageMaker API를 사용하여 배포하기
<a name="autopilot-deploy-models-api"></a>

**API 직접 호출**을 사용하여 모델을 배포하여 실시간 추론을 얻을 수도 있습니다. 이 섹션에서는 AWS Command Line Interface (AWS CLI) 코드 조각을 사용하는이 프로세스의 5단계를 보여줍니다.

 AWS CLI 명령과 AWS SDK for Python(boto3) 모두에 대한 전체 코드 예제를 보려면 다음 단계에 따라 탭을 직접 엽니다.

1. **후보 정의 가져오기**

   [추론 컨테이너](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-InferenceContainers)에서 후보 컨테이너 정의를 가져옵니다. 이러한 후보 정의는 SageMaker AI 모델을 만드는 데 사용됩니다.

   다음 예제에서는 [DescribeAutoMLJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAutoMLJob.html) API를 사용하여 최적의 모델 후보에 대한 후보 정의를 얻습니다. 다음 AWS CLI 명령을 예제로 참조하세요.

   ```
   aws sagemaker describe-auto-ml-job --auto-ml-job-name <job-name> --region <region>
   ```

1. **후보 나열**

   다음 예제에서는 [ListCandidatesForAutoMLJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListCandidatesForAutoMLJob.html) API를 사용하여 모든 후보를 나열합니다. 예제로서 다음 AWS CLI 명령을 참조하세요.

   ```
   aws sagemaker list-candidates-for-auto-ml-job --auto-ml-job-name <job-name> --region <region>
   ```

1. **SageMaker AI 모델 만들기**

   이전 단계의 컨테이너 정의를 사용하여 [CreateModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) API로 SageMaker AI 모델을 만듭니다. 다음 AWS CLI 명령을 예제로 참조하세요.

   ```
   aws sagemaker create-model --model-name '<your-custom-model-name>' \
                       --containers ['<container-definition1>, <container-definition2>, <container-definition3>]' \
                       --execution-role-arn '<execution-role-arn>' --region '<region>
   ```

1. **엔드포인트 구성 생성** 

   다음 예제에서는 [CreateEndpointConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) API를 사용하여 엔드포인트 구성을 생성합니다. 다음 AWS CLI 명령을 예제로 참조하세요.

   ```
   aws sagemaker create-endpoint-config --endpoint-config-name '<your-custom-endpoint-config-name>' \
                       --production-variants '<list-of-production-variants>' \
                       --region '<region>'
   ```

1. **엔드포인트 생성** 

   다음 AWS CLI 예제에서는 [CreateEndpoint](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html) API를 사용하여 엔드포인트를 생성합니다.

   ```
   aws sagemaker create-endpoint --endpoint-name '<your-custom-endpoint-name>' \
                       --endpoint-config-name '<endpoint-config-name-you-just-created>' \
                       --region '<region>'
   ```

   [DescribeEndpoint](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeEndpoint.html) API를 사용하여 엔드포인트 배포 진행 상황을 확인합니다. 다음 AWS CLI 명령을 예제로 참조하세요.

   ```
   aws sagemaker describe-endpoint —endpoint-name '<endpoint-name>' —region <region>
   ```

   `EndpointStatus`가 `InService`로 변경되면 엔드포인트를 실시간 추론에 사용할 수 있습니다.

1. **API 엔드포인트 호출** 

   다음 명령 구조는 실시간 추론을 위해 엔드포인트를 간접적으로 호출합니다.

   ```
   aws sagemaker invoke-endpoint --endpoint-name '<endpoint-name>' \ 
                     --region '<region>' --body '<your-data>' [--content-type] '<content-type>' <outfile>
   ```

다음 탭에는 Python용 AWS SDK(boto3) 또는 AWS CLI를 사용하여 모델을 배포하기 위한 전체 코드 예제가 포함되어 있습니다.

------
#### [ AWS SDK for Python (boto3) ]

1. 다음 코드 예제를 사용하여 **후보 정의를 확보하세요**.

   ```
   import sagemaker 
   import boto3
   
   session = sagemaker.session.Session()
   
   sagemaker_client = boto3.client('sagemaker', region_name='us-west-2')
   job_name = 'test-auto-ml-job'
   
   describe_response = sm_client.describe_auto_ml_job(AutoMLJobName=job_name)
   # extract the best candidate definition from DescribeAutoMLJob response
   best_candidate = describe_response['BestCandidate']
   # extract the InferenceContainers definition from the caandidate definition
   inference_containers = best_candidate['InferenceContainers']
   ```

1. 다음 코드 예제를 사용하여 **모델을 생성합니다**.

   ```
   # Create Model
   model_name = 'test-model' 
   sagemaker_role = 'arn:aws:iam:444455556666:role/sagemaker-execution-role'
   create_model_response = sagemaker_client.create_model(
      ModelName = model_name,
      ExecutionRoleArn = sagemaker_role,
      Containers = inference_containers 
   )
   ```

1. 다음 코드 예제를 사용하여 **엔드포인트 구성을 생성합니다**.

   ```
   endpoint_config_name = 'test-endpoint-config'
                                                           
   instance_type = 'ml.m5.2xlarge' 
   # for all supported instance types, see 
   # https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProductionVariant.html#sagemaker-Type-ProductionVariant-InstanceType    # Create endpoint config
   
   endpoint_config_response = sagemaker_client.create_endpoint_config(
      EndpointConfigName=endpoint_config_name, 
      ProductionVariants=[
          {
              "VariantName": "variant1",
              "ModelName": model_name, 
              "InstanceType": instance_type,
              "InitialInstanceCount": 1
          }
      ]
   )
   
   print(f"Created EndpointConfig: {endpoint_config_response['EndpointConfigArn']}")
   ```

1. **엔드포인트를 생성하고** 다음 코드 예제를 사용하여 모델을 배포합니다.

   ```
   # create endpoint and deploy the model
   endpoint_name = 'test-endpoint'
   create_endpoint_response = sagemaker_client.create_endpoint(
                                               EndpointName=endpoint_name, 
                                               EndpointConfigName=endpoint_config_name)
   print(create_endpoint_response)
   ```

   다음 코드 예제를 사용하여 **엔드포인트 생성 상태를 확인합니다**.

   ```
   # describe endpoint creation status
   status = sagemaker_client.describe_endpoint(EndpointName=endpoint_name)["EndpointStatus"]
   ```

1. 다음 명령 구조를 사용하여 실시간 추론을 위해 **엔드포인트를 호출합니다**.

   ```
   # once endpoint status is InService, you can invoke the endpoint for inferencing
   if status == "InService":
     sm_runtime = boto3.Session().client('sagemaker-runtime')
     inference_result = sm_runtime.invoke_endpoint(EndpointName='test-endpoint', ContentType='text/csv', Body='1,2,3,4,class')
   ```

------
#### [ AWS Command Line Interface (AWS CLI) ]

1. 다음 코드 예제를 사용하여 **후보 정의를 확보하세요**.

   ```
   aws sagemaker describe-auto-ml-job --auto-ml-job-name 'test-automl-job' --region us-west-2
   ```

1. 다음 코드 예제를 사용하여 **모델을 생성합니다**.

   ```
   aws sagemaker create-model --model-name 'test-sagemaker-model'
   --containers '[{
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-sklearn-automl:2.5-1-cpu-py3", amzn-s3-demo-bucket1
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/output/model.tar.gz",
       "Environment": {
           "AUTOML_SPARSE_ENCODE_RECORDIO_PROTOBUF": "1",
           "AUTOML_TRANSFORM_MODE": "feature-transform",
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "application/x-recordio-protobuf",
           "SAGEMAKER_PROGRAM": "sagemaker_serve",
           "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code"
       }
   }, {
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-xgboost:1.3-1-cpu-py3",
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/output/model.tar.gz",
       "Environment": {
           "MAX_CONTENT_LENGTH": "20971520",
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv",
           "SAGEMAKER_INFERENCE_OUTPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_SUPPORTED": "predicted_label,probability,probabilities" 
       }
   }, {
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-sklearn-automl:2.5-1-cpu-py3", aws-region
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/output/model.tar.gz", 
       "Environment": { 
           "AUTOML_TRANSFORM_MODE": "inverse-label-transform", 
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv", 
           "SAGEMAKER_INFERENCE_INPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_OUTPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_SUPPORTED": "predicted_label,probability,labels,probabilities", 
           "SAGEMAKER_PROGRAM": "sagemaker_serve", 
           "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code"
       } 
   }]' \
   --execution-role-arn 'arn:aws:iam::1234567890:role/sagemaker-execution-role' \ 
   --region 'us-west-2'
   ```

   자세한 내용은 [모델 생성](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sagemaker/create-model.html)을 참조하세요.

   `create model` 명령은 다음과 같은 형식의 응답을 반환합니다.

   ```
   {
       "ModelArn": "arn:aws:sagemaker:us-west-2:1234567890:model/test-sagemaker-model"
   }
   ```

1. 다음 코드 예제를 사용하여 **엔드포인트 구성을 생성합니다**.

   ```
   aws sagemaker create-endpoint-config --endpoint-config-name 'test-endpoint-config' \
   --production-variants '[{"VariantName": "variant1", 
                           "ModelName": "test-sagemaker-model",
                           "InitialInstanceCount": 1,
                           "InstanceType": "ml.m5.2xlarge"
                          }]' \
   --region us-west-2
   ```

   `create endpoint` 구성 명령은 다음과 같은 형식의 응답을 반환합니다.

   ```
   {
       "EndpointConfigArn": "arn:aws:sagemaker:us-west-2:1234567890:endpoint-config/test-endpoint-config"
   }
   ```

1. 다음 코드 예제를 사용하여 **엔드포인트를 생성합니다**.

   ```
   aws sagemaker create-endpoint --endpoint-name 'test-endpoint' \    
   --endpoint-config-name 'test-endpoint-config' \                 
   --region us-west-2
   ```

   `create endpoint` 명령은 다음과 같은 형식의 응답을 반환합니다.

   ```
   {
       "EndpointArn": "arn:aws:sagemaker:us-west-2:1234567890:endpoint/test-endpoint"
   }
   ```

   다음 [describe-endpoint](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/describe-endpoint.html) CLI 코드 예제를 사용하여 엔드포인트 배포의 진행 상황을 확인합니다.

   ```
   aws sagemaker describe-endpoint --endpoint-name 'test-endpoint' --region us-west-2
   ```

   이전 진행 상황 확인에서는 다음 형식으로 응답을 반환합니다.

   ```
   {
       "EndpointName": "test-endpoint",
       "EndpointArn": "arn:aws:sagemaker:us-west-2:1234567890:endpoint/test-endpoint",
       "EndpointConfigName": "test-endpoint-config",
       "EndpointStatus": "Creating",
       "CreationTime": 1660251167.595,
       "LastModifiedTime": 1660251167.595
   }
   ```

   `EndpointStatus`가 `InService`로 변경되면 엔드포인트를 실시간 추론에 사용할 수 있습니다.

1. 다음 명령 구조를 사용하여 실시간 추론을 위해 **엔드포인트를 호출합니다**.

   ```
   aws sagemaker-runtime invoke-endpoint --endpoint-name 'test-endpoint' \
   --region 'us-west-2' \
   --body '1,51,3.5,1.4,0.2' \
   --content-type 'text/csv' \
   '/tmp/inference_output'
   ```

   자세한 옵션은 [엔드포인트 호출](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sagemaker-runtime/invoke-endpoint.html)을 참조하세요.

------

## 다양한 계정의 모델 배포
<a name="autopilot-deploy-models-realtime-across-accounts"></a>

모델을 생성한 원래 계정이 아닌 다른 계정에서 Autopilot 모델을 배포할 수 있습니다. 교차 계정 모델 배포를 구현하기 위해 이 섹션에서는 다음을 수행하는 방법을 보여줍니다.   (생성 계정)에서 배포하려는 계정에 역할을 맡을 권한을 부여하세요.   배포 계정에서 `DescribeAutoMLJob`을 호출하여 모델 정보를 얻으세요.   생성 계정의 모델 아티팩트에 대한 액세스 권한을 부여합니다.   

1. **배포 계정에 권한 부여** 

   생성 계정에서 역할을 맡으려면 배포 계정에 권한을 부여해야 합니다. 이렇게 하면 배포 계정이 생성 계정의 Autopilot 작업을 설명할 수 있습니다.

   다음 예시에서는 신뢰할 수 있는 `sagemaker-role` 엔터티를 가진 생성 계정을 사용합니다. 이 예제는 ID가 111122223333인 배포 계정에 생성 계정 역할을 맡을 수 있는 권한을 부여하는 방법을 보여줍니다.

   ```
   "Statement": [
           {
               "Effect": "Allow",
               "Principal": {
                   "Service": [
                       "sagemaker.amazonaws.com"
                   ],
                   "AWS": [ "111122223333"]
               },
               "Action": "sts:AssumeRole"
           }
   ```

   ID가 111122223333인 새 계정이 이제 생성 계정 역할을 맡을 수 있습니다.

   그런 다음, 배포 계정에서 `DescribeAutoMLJob` API를 호출하여 생성 계정으로 생성된 작업에 대한 설명을 가져옵니다.

   다음 코드 예제는 배포 계정의 모델을 설명합니다.

   ```
   import sagemaker 
   import boto3
   session = sagemaker.session.Session()
   
   sts_client = boto3.client('sts')
   sts_client.assume_role
   
   role = 'arn:aws:iam::111122223333:role/sagemaker-role'
   role_session_name = "role-session-name"
   _assumed_role = sts_client.assume_role(RoleArn=role, RoleSessionName=role_session_name)
   
   credentials = _assumed_role["Credentials"]
   access_key = credentials["AccessKeyId"]
   secret_key = credentials["SecretAccessKey"]
   session_token = credentials["SessionToken"]
   
   session = boto3.session.Session()
           
   sm_client = session.client('sagemaker', region_name='us-west-2', 
                              aws_access_key_id=access_key,
                               aws_secret_access_key=secret_key,
                               aws_session_token=session_token)
   
   # now you can call describe automl job created in account A 
   
   job_name = "test-job"
   response= sm_client.describe_auto_ml_job(AutoMLJobName=job_name)
   ```

1. 생성 계정의 모델 아티팩트에 **배포 계정에 대한 액세스 권한을 부여합니다**.

   배포 계정에는 생성 계정의 모델 아티팩트에 대한 액세스 권한만 있으면 배포할 수 있습니다. 이러한 정보는 모델 생성 중에 원래 `CreateAutoMLJob` API 직접 호출에 지정된 [S3OutputPath](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLOutputDataConfig.html#sagemaker-Type-AutoMLOutputDataConfig-S3OutputPath)에 있습니다.

   배포 계정에 모델 아티팩트에 대한 액세스 권한을 부여하려면 다음 옵션 중 하나를 선택합니다.

   1. 생성 계정에서 배포 계정에 `ModelDataUrl`에 대한 [액세스 권한을 부여하세요](https://aws.amazon.com/premiumsupport/knowledge-center/cross-account-access-s3/).

      다음으로 배포 계정에 역할을 맡을 권한을 부여해야 합니다. [실시간 추론 단계](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-deploy-models.html#autopilot-deploy-models-realtime)에 따라 배포하세요.

   1. 생성 계정의 원래 [S3OutputPath](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLOutputDataConfig.html#sagemaker-Type-AutoMLOutputDataConfig-S3OutputPath)에서 생성 계정으로 [모델 아티팩트를 복사합니다](https://aws.amazon.com/premiumsupport/knowledge-center/copy-s3-objects-account/).

      모델 아티팩트에 대한 액세스 권한을 부여하려면 `best_candidate` 모델을 정의하고 모델 컨테이너를 새 계정에 재할당해야 합니다.

      다음 예제에서는 `best_candidate` 모델을 정의하고 `ModelDataUrl`을 재할당하는 방법을 보여줍니다.

      ```
      best_candidate = automl.describe_auto_ml_job()['BestCandidate']
      
      # reassigning ModelDataUrl for best_candidate containers below
      new_model_locations = ['new-container-1-ModelDataUrl', 'new-container-2-ModelDataUrl', 'new-container-3-ModelDataUrl']
      new_model_locations_index = 0
      for container in best_candidate['InferenceContainers']:
          container['ModelDataUrl'] = new_model_locations[new_model_locations_index++]
      ```

      컨테이너를 할당한 후에는 [SageMaker API를 사용하여 배포하기](#autopilot-deploy-models-api)의 단계를 따라 배포합니다.

실시간 추론으로 페이로드를 구축하려면 노트북 예제를 참조하여 [테스트 페이로드를 정의하세요](https://aws.amazon.com/getting-started/hands-on/machine-learning-tutorial-automatically-create-models). CSV 파일에서 페이로드를 생성하고 엔드포인트를 간접적으로 호출하려면 [기계 학습 모델 자동 생성](https://aws.amazon.com/getting-started/hands-on/create-machine-learning-model-automatically-sagemaker-autopilot/#autopilot-cr-room)의 **모델로 예측** 섹션을 참조하세요.

# 배치 추론 작업 실행
<a name="autopilot-deploy-models-batch"></a>

오프라인 추론이라고도 하는 배치 추론은 배치 관찰에서 모델 예측을 생성합니다. 대규모 데이터세트나 모델 예측 요청에 대한 즉각적인 응답이 필요하지 않은 경우 배치 추론을 사용하는 것이 좋습니다. 반면, 온라인 추론([실시간 추론](https://docs.aws.amazon.com/sagemaker/latest/dg/autopilot-deploy-models.html#autopilot-deploy-models-realtime))은 실시간으로 예측을 생성합니다. [SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/), Autopilot 사용자 인터페이스(UI), [AWS Python용 SDK(boto3)](https://aws.amazon.com/sdk-for-python/) 또는 AWS Command Line Interface ()를 사용하여 Autopilot 모델에서 배치 추론을 수행할 수 있습니다[AWS CLI](https://docs.aws.amazon.com/cli/).

다음 탭에는 모델을 배포하기 위한 세 가지 옵션, 즉 API 사용, Autopilot UI 또는 API를 사용하여 다른 계정에서 배포하는 옵션이 표시됩니다. 이 지침에서는 Autopilot으로 모델을 이미 생성했다고 가정합니다. 모델이 없는 경우 [AutoML API를 사용하여 테이블 형식 데이터에 대한 회귀 또는 분류 작업 생성](autopilot-automate-model-development-create-experiment.md) 섹션을 참조하세요. 각 옵션의 예를 보려면 각 탭을 여세요.

## Autopilot UI를 사용하여 모델 배포하기
<a name="autopilot-deploy-models-batch-ui"></a>

Autopilot UI에는 모델 배포를 탐색하는 데 도움이 되는 유용한 드롭다운 메뉴, 토글, 툴팁 등이 포함되어 있습니다.

다음 단계에서는 배치 예측을 위해 Autopilot 실험에서 모델을 배포하는 방법을 보여줍니다.

1. [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/)에서 로그인하고 탐색 창에서 **Studio**를 선택합니다.

1. 왼쪽 탐색 창에서 **Studio**를 선택합니다.

1. **시작하기**에서 Studio 애플리케이션을 시작하려는 도메인을 선택합니다. 사용자 프로파일이 한 도메인에만 속하는 경우 도메인 선택 옵션이 표시되지 않습니다.

1. Studio Classic 애플리케이션을 시작하려는 사용자 프로필을 선택합니다. 도메인에 사용자 프로필이 없는 경우 **사용자 프로필 생성**을 선택합니다. 자세한 내용은 [사용자 프로필 추가](https://docs.aws.amazon.com/sagemaker/latest/dg/domain-user-profile-add.html) 섹션을 참조하세요.

1. **Studio 실행**을 선택합니다. 사용자 프로필이 공유 공간에 속하는 경우 **오픈 스페이스**를 선택합니다.

1. SageMaker Studio Classic 콘솔이 열리면 **SageMaker Studio 실행** 버튼을 선택합니다.

1. 왼쪽 탐색 창에서 **AutoML**을 선택합니다.

1. **이름**에서 배포하려는 모델에 해당하는 Autopilot 실험을 선택합니다. 그러면 새 **AUTOPILOT 작업** 탭이 열립니다.

1. **모델 이름**에서 배포하려는 모델을 선택합니다.

1. **Deploy model(모델 배포)**을 선택합니다. 그러면 새 탭이 열립니다.

1. 페이지 상단의 **배치 예측 만들기**를 선택합니다.

1. **배치 변환 작업 구성**의 경우, **인스턴스 유형**, **인스턴스 수** 및 기타 선택적 정보를 입력합니다.

1. **입력 데이터 구성** 섹션에서 드롭다운 메뉴를 엽니다.

   1. **S3 데이터 유형**의 경우 **ManifestFile** 또는 **S3Profix**를 선택합니다.

   1. **분할 유형**의 경우 **라인**, **RecordIO**, **TFRecord** 또는 **없음**을 선택합니다.

   1. **압축**의 경우 **Gzip** 또는 **없음**을 선택합니다.

1. **S3 위치**의 경우 입력 데이터의 Amazon S3 버킷 위치와 기타 선택적 정보를 입력합니다.

1. **출력 데이터 구성**에서 출력 데이터용 S3 버킷을 입력하고 작업의 [출력을 어셈블](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_TransformOutput.html#sagemaker-Type-TransformOutput-AssembleWith)하는 방법을 선택합니다.

   1. **추가 구성(선택 사항)**의 경우 MIME 유형과 **S3 암호화 키**를 입력할 수 있습니다.

1. **입력/출력 필터링 및 데이터 조인(선택 사항)**의 경우 JSONPath 식을 입력하여 입력 데이터를 필터링하고, 입력 소스 데이터를 출력 데이터와 조인하고, JSONPath 식을 입력하여 출력 데이터를 필터링합니다.

   1. 각 필터 유형에 대한 예는 [DataProcessing API](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataProcessing.html#sagemaker-Type-DataProcessing-InputFilter)를 참조하세요.

1. 입력 데이터세트에 대한 배치 예측을 수행하려면 **배치 변환 작업 만들기** 선택합니다. 새 **배치 변환 작업** 탭이 나타납니다.

1. **배치 변환 작업** 탭의 **상태** 섹션에서 작업 이름을 찾습니다. 그런 다음 작업 진행 상황을 확인합니다.

## SageMaker API를 사용하여 배포하기
<a name="autopilot-deploy-models-batch-steps"></a>

SageMaker API를 배치 추론에 사용하려면 다음 세 단계를 거쳐야 합니다.

1. **후보 정의 가져오기** 

   [InferenceContainers](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AutoMLCandidate.html#sagemaker-Type-AutoMLCandidate-InferenceContainers)의 후보 정의는 SageMaker AI 모델을 만드는 데 사용됩니다.

   다음 예제는 [DescribeAutoMLJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeAutoMLJob.html) API를 사용하여 최적의 모델 후보에 대한 후보 정의를 얻는 방법을 보여줍니다. 다음 AWS CLI 명령을 예제로 참조하세요.

   ```
   aws sagemaker describe-auto-ml-job --auto-ml-job-name <job-name> --region <region>
   ```

   [ListCandidatesForAutoMLJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListCandidatesForAutoMLJob.html) API를 사용하여 모든 후보를 나열할 수 있습니다. 예제로서 다음 AWS CLI 명령을 참조하세요.

   ```
   aws sagemaker list-candidates-for-auto-ml-job --auto-ml-job-name <job-name> --region <region>
   ```

1. **SageMaker AI 모델 만들기**

   [CreateModel](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) API를 사용하여 SageMaker AI 모델을 만들려면 이전 단계의 컨테이너 정의를 사용합니다. 예제로서 다음 AWS CLI 명령을 참조하세요.

   ```
   aws sagemaker create-model --model-name '<your-custom-model-name>' \
                       --containers ['<container-definition1>, <container-definition2>, <container-definition3>]' \
                       --execution-role-arn '<execution-role-arn>' --region '<region>
   ```

1. **SageMaker AI 변환 작업 만들기** 

   다음 예시에서는 [CreateTransformJob](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-transform-job.html) API를 사용하여 SageMaker AI 변환 작업을 만듭니다. 다음 AWS CLI 명령을 예제로 참조하세요.

   ```
   aws sagemaker create-transform-job --transform-job-name '<your-custom-transform-job-name>' --model-name '<your-custom-model-name-from-last-step>'\
   --transform-input '{
           "DataSource": {
               "S3DataSource": {
                   "S3DataType": "S3Prefix", 
                   "S3Uri": "<your-input-data>" 
               }
           },
           "ContentType": "text/csv",
           "SplitType": "Line"
       }'\
   --transform-output '{
           "S3OutputPath": "<your-output-path>",
           "AssembleWith": "Line" 
       }'\
   --transform-resources '{
           "InstanceType": "<instance-type>", 
           "InstanceCount": 1
       }' --region '<region>'
   ```

[DescribeTransformJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTransformJob.html) API를 사용하여 변환 작업의 진행 상황을 확인합니다. 다음 AWS CLI 명령을 예제로 참조하세요.

```
aws sagemaker describe-transform-job --transform-job-name '<your-custom-transform-job-name>' --region <region>
```

작업이 완료되면 예측된 결과를 `<your-output-path>`에서 확인할 수 있습니다.

출력 파일 이름의 형식: `<input_data_file_name>.out`. 예를 들어, 입력 파일이 `text_x.csv`인 경우 출력 이름은 `text_x.csv.out`입니다.

다음 탭은 SageMaker Python SDK, Python용 AWS SDK(boto3) 및에 대한 코드 예제를 보여줍니다 AWS CLI.

------
#### [ SageMaker Python SDK ]

다음 예제에서는 **[SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/overview.html)**를 사용하여 배치 예측을 만듭니다.

```
from sagemaker import AutoML

sagemaker_session= sagemaker.session.Session()

job_name = 'test-auto-ml-job' # your autopilot job name
automl = AutoML.attach(auto_ml_job_name=job_name)
output_path = 's3://test-auto-ml-job/output'
input_data = 's3://test-auto-ml-job/test_X.csv'

# call DescribeAutoMLJob API to get the best candidate definition
best_candidate = automl.describe_auto_ml_job()['BestCandidate']
best_candidate_name = best_candidate['CandidateName']

# create model
model = automl.create_model(name=best_candidate_name, 
               candidate=best_candidate)

# create transformer
transformer = model.transformer(instance_count=1, 
    instance_type='ml.m5.2xlarge',
    assemble_with='Line',
    output_path=output_path)

# do batch transform
transformer.transform(data=input_data,
                      split_type='Line',
                       content_type='text/csv',
                       wait=True)
```

------
#### [ AWS SDK for Python (boto3) ]

 다음 예제에서는 **Python용AWS SDK**를 사용하여 배치 예측을 만듭니다.

```
import sagemaker 
import boto3

session = sagemaker.session.Session()

sm_client = boto3.client('sagemaker', region_name='us-west-2')
role = 'arn:aws:iam::1234567890:role/sagemaker-execution-role'
output_path = 's3://test-auto-ml-job/output'
input_data = 's3://test-auto-ml-job/test_X.csv'

best_candidate = sm_client.describe_auto_ml_job(AutoMLJobName=job_name)['BestCandidate']
best_candidate_containers = best_candidate['InferenceContainers']
best_candidate_name = best_candidate['CandidateName']

# create model
reponse = sm_client.create_model(
    ModelName = best_candidate_name,
    ExecutionRoleArn = role,
    Containers = best_candidate_containers 
)

# Lauch Transform Job
response = sm_client.create_transform_job(
    TransformJobName=f'{best_candidate_name}-transform-job',
    ModelName=model_name,
    TransformInput={
        'DataSource': {
            'S3DataSource': {
                'S3DataType': 'S3Prefix',
                'S3Uri': input_data
            }
        },
        'ContentType': "text/csv",
        'SplitType': 'Line'
    },
    TransformOutput={
        'S3OutputPath': output_path,
        'AssembleWith': 'Line',
    },
    TransformResources={
        'InstanceType': 'ml.m5.2xlarge',
        'InstanceCount': 1,
    },
)
```

배치 추론 작업에서는 다음 형식으로 응답을 반환합니다.

```
{'TransformJobArn': 'arn:aws:sagemaker:us-west-2:1234567890:transform-job/test-transform-job',
 'ResponseMetadata': {'RequestId': '659f97fc-28c4-440b-b957-a49733f7c2f2',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '659f97fc-28c4-440b-b957-a49733f7c2f2',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '96',
   'date': 'Thu, 11 Aug 2022 22:23:49 GMT'},
  'RetryAttempts': 0}}
```

------
#### [ AWS Command Line Interface (AWS CLI) ]

1. 다음 코드 예제를 사용하여 **후보 정의를 확보하세요**.

   ```
   aws sagemaker describe-auto-ml-job --auto-ml-job-name 'test-automl-job' --region us-west-2
   ```

1. 다음 코드 예제를 사용하여 **모델을 생성합니다**.

   ```
   aws sagemaker create-model --model-name 'test-sagemaker-model'
   --containers '[{
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-sklearn-automl:2.5-1-cpu-py3",
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/out/test-job1/data-processor-models/test-job1-dpp0-1-e569ff7ad77f4e55a7e549a/output/model.tar.gz",
       "Environment": {
           "AUTOML_SPARSE_ENCODE_RECORDIO_PROTOBUF": "1",
           "AUTOML_TRANSFORM_MODE": "feature-transform",
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "application/x-recordio-protobuf",
           "SAGEMAKER_PROGRAM": "sagemaker_serve",
           "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code"
       }
   }, {
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-xgboost:1.3-1-cpu-py3",
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/out/test-job1/tuning/flicdf10v2-dpp0-xgb/test-job1E9-244-7490a1c0/output/model.tar.gz",
       "Environment": {
           "MAX_CONTENT_LENGTH": "20971520",
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv",
           "SAGEMAKER_INFERENCE_OUTPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_SUPPORTED": "predicted_label,probability,probabilities" 
       }
   }, {
       "Image": "348316444620.dkr.ecr.us-west-2.amazonaws.com/sagemaker-sklearn-automl:2.5-1-cpu-py3", 
       "ModelDataUrl": "s3://amzn-s3-demo-bucket/out/test-job1/data-processor-models/test-job1-dpp0-1-e569ff7ad77f4e55a7e549a/output/model.tar.gz", 
       "Environment": { 
           "AUTOML_TRANSFORM_MODE": "inverse-label-transform", 
           "SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv", 
           "SAGEMAKER_INFERENCE_INPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_OUTPUT": "predicted_label", 
           "SAGEMAKER_INFERENCE_SUPPORTED": "predicted_label,probability,labels,probabilities", 
           "SAGEMAKER_PROGRAM": "sagemaker_serve", 
           "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code" 
       } 
   }]' \
   --execution-role-arn 'arn:aws:iam::1234567890:role/sagemaker-execution-role' \
   --region 'us-west-2'
   ```

1. 다음 코드 예제를 사용하여 **변환 작업을 생성합니다**.

   ```
   aws sagemaker create-transform-job --transform-job-name 'test-tranform-job'\
    --model-name 'test-sagemaker-model'\
   --transform-input '{
           "DataSource": {
               "S3DataSource": {
                   "S3DataType": "S3Prefix",
                   "S3Uri": "s3://amzn-s3-demo-bucket/data.csv"
               }
           },
           "ContentType": "text/csv",
           "SplitType": "Line"
       }'\
   --transform-output '{
           "S3OutputPath": "s3://amzn-s3-demo-bucket/output/",
           "AssembleWith": "Line"
       }'\
   --transform-resources '{
           "InstanceType": "ml.m5.2xlarge",
           "InstanceCount": 1
       }'\
   --region 'us-west-2'
   ```

1. 다음 코드 예제를 사용하여 **변환 작업의 진행 상황을 확인합니다**.

   ```
   aws sagemaker describe-transform-job --transform-job-name  'test-tranform-job' --region us-west-2
   ```

   다음은 변환 작업의 응답입니다.

   ```
   {
       "TransformJobName": "test-tranform-job",
       "TransformJobArn": "arn:aws:sagemaker:us-west-2:1234567890:transform-job/test-tranform-job",
       "TransformJobStatus": "InProgress",
       "ModelName": "test-model",
       "TransformInput": {
           "DataSource": {
               "S3DataSource": {
                   "S3DataType": "S3Prefix",
                   "S3Uri": "s3://amzn-s3-demo-bucket/data.csv"
               }
           },
           "ContentType": "text/csv",
           "CompressionType": "None",
           "SplitType": "Line"
       },
       "TransformOutput": {
           "S3OutputPath": "s3://amzn-s3-demo-bucket/output/",
           "AssembleWith": "Line",
           "KmsKeyId": ""
       },
       "TransformResources": {
           "InstanceType": "ml.m5.2xlarge",
           "InstanceCount": 1
       },
       "CreationTime": 1662495635.679,
       "TransformStartTime": 1662495847.496,
       "DataProcessing": {
           "InputFilter": "$",
           "OutputFilter": "$",
           "JoinSource": "None"
       }
   }
   ```

   `TransformJobStatus` 상태를 `Completed`으로 변경한 후에는 `S3OutputPath`에서 추론 결과를 확인할 수 있습니다.

------

## 다양한 계정의 모델 배포
<a name="autopilot-deploy-models-batch-across-accounts"></a>

모델이 생성된 계정과 다른 계정에서 배치 추론 작업을 만들려면 [다양한 계정의 모델 배포](autopilot-deploy-models-realtime.md#autopilot-deploy-models-realtime-across-accounts)의 지침을 따르세요. 그런 다음 [SageMaker API를 사용하여 배포하기](#autopilot-deploy-models-batch-steps)에 따라 모델을 생성하고 작업을 변환할 수 있습니다.