

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Python 從登錄中部署模型
<a name="model-registry-deploy"></a>

註冊模型版本並核准其進行部署後，請將其部署到 SageMaker AI 端點以進行即時推論。您可以使用 SageMaker AI SDK 或 適用於 Python (Boto3) 的 AWS SDK部署模型。

當您建立機器學習維運 (MLOps) 專案並選擇包含模型部署的 MLOps 專案範本後，模型註冊庫中已核准的模型版本會自動部署到生產環境。如需使用 SageMaker MLOps 專案的相關資訊，請參閱[使用 SageMaker 專案進行 MLOps 自動化](sagemaker-projects.md)。

您也可以透過新增跨 AWS 帳戶資源政策，讓 帳戶部署在不同帳戶中建立的模型版本。例如，您組織中的一個團隊可能負責訓練模型，另一個團隊負責部署和更新模型。

**Topics**
+ [透過登錄檔部署模型 (SageMaker SDK)](#model-registry-deploy-smsdk)
+ [透過登錄檔部署模型 (Boto3)](#model-registry-deploy-api)
+ [從其他帳戶部署模型版本](#model-registry-deploy-xaccount)

## 透過登錄檔部署模型 (SageMaker SDK)
<a name="model-registry-deploy-smsdk"></a>

若要使用 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 部署模型版本，請使用下列程式碼片段：

```
from sagemaker import ModelPackage
from time import gmtime, strftime

model_package_arn = 'arn:aws:sagemaker:us-east-2:12345678901:model-package/modeltest/1'
model = ModelPackage(role=role, 
                     model_package_arn=model_package_arn, 
                     sagemaker_session=sagemaker_session)
model.deploy(initial_instance_count=1, instance_type='ml.m5.xlarge')
```

## 透過登錄檔部署模型 (Boto3)
<a name="model-registry-deploy-api"></a>

若要使用 部署模型版本 適用於 Python (Boto3) 的 AWS SDK，請完成下列步驟：

1. 下列程式碼片段假設您已建立 SageMaker AI Boto3 用戶端 `sm_client`，以及其 ARN 存放在變數 `model_version_arn` 中的模型版本。

   呼叫 [create\$1model](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_model) API 操作，從模型版本建立模型物件。作為 `Containers` 模型物件的一部分，傳遞模型版本的 Amazon Resource Name (ARN)：

   ```
   model_name = 'DEMO-modelregistry-model-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
   print("Model name : {}".format(model_name))
   container_list = [{'ModelPackageName': model_version_arn}]
   
   create_model_response = sm_client.create_model(
       ModelName = model_name,
       ExecutionRoleArn = role,
       Containers = container_list
   )
   print("Model arn : {}".format(create_model_response["ModelArn"]))
   ```

1. 調用 `create_endpoint_config`，建立端點組態。端點組態會指定端點要使用的 Amazon EC2 執行個體的數量和類型。

   ```
   endpoint_config_name = 'DEMO-modelregistry-EndpointConfig-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
   print(endpoint_config_name)
   create_endpoint_config_response = sm_client.create_endpoint_config(
       EndpointConfigName = endpoint_config_name,
       ProductionVariants=[{
           'InstanceType':'ml.m4.xlarge',
           'InitialVariantWeight':1,
           'InitialInstanceCount':1,
           'ModelName':model_name,
           'VariantName':'AllTraffic'}])
   ```

1. 調用 `create_endpoint` 來更新端點。

   ```
   endpoint_name = 'DEMO-modelregistry-endpoint-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
   print("EndpointName={}".format(endpoint_name))
   
   create_endpoint_response = sm_client.create_endpoint(
       EndpointName=endpoint_name,
       EndpointConfigName=endpoint_config_name)
   print(create_endpoint_response['EndpointArn'])
   ```

## 從其他帳戶部署模型版本
<a name="model-registry-deploy-xaccount"></a>

您可以新增跨 AWS 帳戶資源政策，以允許 帳戶部署在不同帳戶中建立的模型版本。例如，您組織中的一個團隊可能負責訓練模型，另一個團隊負責部署和更新模型。建立資源政策後，您可以將政策套用至要向其授予存取權的特定資源。如需 中跨帳戶資源政策的詳細資訊 AWS，請參閱*AWS Identity and Access Management 《 使用者指南*》中的[跨帳戶政策評估邏輯](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic-cross-account.html)。

**注意**  
在跨帳戶模型部署訓練期間，您必須使用 KMS 金鑰來對[輸出資料設定](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_OutputDataConfig.html)動作進行加密。

若要在 SageMaker AI 中啟用跨帳戶模型部署，您必須為模型群組提供跨帳戶資源政策，其中包含要部署的模型版本、模型群組推論映像所在的 Amazon ECR 儲存庫，以及儲存模型版本的 Amazon S3 儲存貯體。

您必須擁有對 SageMaker AI 動作有存取權的角色 (例如具有 `AmazonSageMakerFullAccess` 受管政策的角色)，才能夠部署在不同帳戶中建立的模型。如需 SageMaker AI 受管政策的相關資訊，請參閱 [AWS Amazon SageMaker AI 的 受管政策](security-iam-awsmanpol.md)。

下列範例會為所有這三種資源建立跨帳戶政策，並將政策套用至資源。此範例也假設您先前已定義下列變數：
+ `bucket` - 存放模型版本的 Amazon S3 儲存貯體。
+ `kms_key_id` - 用來加密訓練輸出的 KMS 金鑰。
+ `sm_client` - SageMaker AI Boto3 用戶端。
+ `model_package_group_name` - 您要授予跨帳戶存取權的模型群組。
+ `model_package_group_arn` - 您要授與跨帳戶存取權的模型群組 ARN。

```
import json

# The cross-account id to grant access to
cross_account_id = "123456789012"

# Create the policy for access to the ECR repository
ecr_repository_policy = {
    'Version': '2012-10-17		 	 	 ',
    'Statement': [{
        'Sid': 'AddPerm',
        'Effect': 'Allow',
        'Principal': {
            'AWS': f'arn:aws:iam::{cross_account_id}:root'
        },
        'Action': ['ecr:*']
    }]
}

# Convert the ECR policy from JSON dict to string
ecr_repository_policy = json.dumps(ecr_repository_policy)

# Set the new ECR policy
ecr = boto3.client('ecr')
response = ecr.set_repository_policy(
    registryId = account,
    repositoryName = 'decision-trees-sample',
    policyText = ecr_repository_policy
)

# Create a policy for accessing the S3 bucket
bucket_policy = {
    'Version': '2012-10-17		 	 	 ',
    'Statement': [{
        'Sid': 'AddPerm',
        'Effect': 'Allow',
        'Principal': {
            'AWS': f'arn:aws:iam::{cross_account_id}:root'
        },
        'Action': 's3:*',
        'Resource': f'arn:aws:s3:::{bucket}/*'
    }]
}

# Convert the policy from JSON dict to string
bucket_policy = json.dumps(bucket_policy)

# Set the new policy
s3 = boto3.client('s3')
response = s3.put_bucket_policy(
    Bucket = bucket,
    Policy = bucket_policy)

# Create the KMS grant for encryption in the source account to the
# Model Registry account Model Group
client = boto3.client('kms')

response = client.create_grant(
    GranteePrincipal=cross_account_id,
    KeyId=kms_key_id
    Operations=[
        'Decrypt',
        'GenerateDataKey',
    ],
)

# 3. Create a policy for access to the Model Group.
model_package_group_policy = {
    'Version': '2012-10-17		 	 	 ',
    'Statement': [{
        'Sid': 'AddPermModelPackageGroup',
        'Effect': 'Allow',
        'Principal': {
            'AWS': f'arn:aws:iam::{cross_account_id}:root'
        },
        'Action': ['sagemaker:DescribeModelPackageGroup'],
        'Resource': f'arn:aws:sagemaker:{region}:{account}:model-package-group/{model_package_group_name}'
    },{
        'Sid': 'AddPermModelPackageVersion',
        'Effect': 'Allow',
        'Principal': {
            'AWS': f'arn:aws:iam::{cross_account_id}:root'
        },
        'Action': ["sagemaker:DescribeModelPackage",
                   "sagemaker:ListModelPackages",
                   "sagemaker:UpdateModelPackage",
                   "sagemaker:CreateModel"],
        'Resource': f'arn:aws:sagemaker:{region}:{account}:model-package/{model_package_group_name}/*'
    }]
}

# Convert the policy from JSON dict to string
model_package_group_policy = json.dumps(model_package_group_policy)

# Set the policy to the Model Group
response = sm_client.put_model_package_group_policy(
    ModelPackageGroupName = model_package_group_name,
    ResourcePolicy = model_package_group_policy)

print('ModelPackageGroupArn : {}'.format(create_model_package_group_response['ModelPackageGroupArn']))
print("First Versioned ModelPackageArn: " + model_package_arn)
print("Second Versioned ModelPackageArn: " + model_package_arn2)

print("Success! You are all set to proceed for cross-account deployment.")
```