

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

# 註冊模型版本
<a name="model-registry-version"></a>

您可以透過建立一個指定模型所屬模型群組的模型版本來註冊 Amazon SageMaker AI 模型。模型版本必須包含模型成品 (模型的訓練權重)，以及選擇性地包含模型的推論程式碼。

*推論管道*是一種 SageMaker AI 模型，由兩個到十五個處理推論請求的容器線性序列容器構成。您可以透過指定容器和相關聯的環境變數來註冊推論管道。如需與推論管道相關的詳細資訊，請參閱[Amazon SageMaker AI 中的推論管道](inference-pipelines.md)。

您可以透過指定容器和關聯的環境變數，在推論管道中註冊模型。若要使用 適用於 Python (Boto3) 的 AWS SDK、Amazon SageMaker Studio 主控台或在 SageMaker AI 模型建置管道中建立步驟，建立具有推論管道的模型版本，請使用下列步驟。

**Topics**
+ [註冊模型版本 (SageMaker AI Pipeline)](#model-registry-pipeline)
+ [註冊模型版本 (Boto3)](#model-registry-version-api)
+ [註冊模型版本 (Studio 或 Studio Classic)](#model-registry-studio)
+ [從其他帳戶註冊模型版本](#model-registry-version-xaccount)

## 註冊模型版本 (SageMaker AI Pipeline)
<a name="model-registry-pipeline"></a>

若要使用 SageMaker AI 模型建置管道註冊模型版本，請在管道中建立 `RegisterModel` 步驟。如需與作為管道的一部分建立 `RegisterModel` 相關的詳細資訊，請參閱[步驟 8：定義 RegisterModel 步驟以建立模型套件](define-pipeline.md#define-pipeline-register)。

## 註冊模型版本 (Boto3)
<a name="model-registry-version-api"></a>

若要使用 Boto3 註冊模型版本，請呼叫 `create_model_package` API 操作。

首先，設定要傳遞至 `create_model_package` API 操作的參數字典。

```
# Specify the model source
model_url = "s3://your-bucket-name/model.tar.gz"

modelpackage_inference_specification =  {
    "InferenceSpecification": {
      "Containers": [
         {
            "Image": image_uri,
	    "ModelDataUrl": model_url
         }
      ],
      "SupportedContentTypes": [ "text/csv" ],
      "SupportedResponseMIMETypes": [ "text/csv" ],
   }
 }

# Alternatively, you can specify the model source like this:
# modelpackage_inference_specification["InferenceSpecification"]["Containers"][0]["ModelDataUrl"]=model_url

create_model_package_input_dict = {
    "ModelPackageGroupName" : model_package_group_name,
    "ModelPackageDescription" : "Model to detect 3 different types of irises (Setosa, Versicolour, and Virginica)",
    "ModelApprovalStatus" : "PendingManualApproval"
}
create_model_package_input_dict.update(modelpackage_inference_specification)
```

然後呼叫 `create_model_package` API 操作，傳入您剛剛設定的參數字典。

```
create_model_package_response = sm_client.create_model_package(**create_model_package_input_dict)
model_package_arn = create_model_package_response["ModelPackageArn"]
print('ModelPackage Version ARN : {}'.format(model_package_arn))
```

## 註冊模型版本 (Studio 或 Studio Classic)
<a name="model-registry-studio"></a>

若要在 Amazon SageMaker Studio 主控台中註冊模型版本，請根據您是使用 Studio 還是 Studio Classic 完成以下步驟。

------
#### [ Studio ]

1. 請遵循[啟動 Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html) 中的指示來開啟 SageMaker Studio 主控台。

1. 在左側導覽窗格中，從功能表中選擇**模型**。

1. 如果尚未選取，請選擇**已註冊模型**索引標籤。

1. 如果尚未選取，請在**已註冊模型**索引標籤標籤的正下方選擇**模型群組**和**我的模型**。

1. 選擇**註冊**。這會開啟**註冊模型**頁面。

1. 請遵循**註冊模型**頁面提供的指示。

1. 一旦檢閱了您的選擇，請選擇**註冊**。一旦完成，就會帶您前往模型版本**概觀**頁面。

------
#### [ Studio Classic ]

1. 登入 Amazon SageMaker Studio Classic。如需詳細資訊，請參閱[啟動 Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html)。

1. 在左側的導覽窗格中，選擇**首頁**圖示 (![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/studio/icons/house.png))。

1. 選擇**模型**，然後選擇**模型註冊表**。

1. 開啟**註冊版本**表單。您可以使用兩種方式的其中一種來執行此動作：
   + 選擇**動作**，然後選擇**建立模型版本**。
   + 選取您要為其建立模型版本的模型群組的名稱，然後選擇**建立模型版本**。

1. 在**註冊模型版本**表單中，輸入下列資訊：
   + 在**模型套件群組名稱**下拉式清單中，選取模型群組名稱。
   + (可選) 輸入模型版本的描述。
   + 在**模型核准狀態**下拉式清單中，選取版本核准狀態。
   + (選用) 在**自訂中繼資料**欄位中，以鍵值對形式新增自訂標籤。

1. 選擇**下一步**。

1. 在**推論規格**表單中，輸入下列資訊：
   + 輸入推論映像位置。
   + 輸入模型資料成品位置。
   + (選用) 輸入哪些映像要用於轉換和即時推論任務的相關資訊，以及支援的輸入和輸出 MIME 類型。

1. 選擇**下一步**。

1. (可選) 提供用於協助提出端點建議的詳細資料。

1. 選擇**下一步**。

1. (可選) 選擇您要包含的模型指標。

1. 選擇**下一步**。

1. 確認顯示的設定正確無誤，然後選擇**註冊模型版本**。如果您隨後看到顯示錯誤訊息的強制回應視窗，請選擇**檢視** (位於訊息旁) 以檢視錯誤來源。

1. 確認新模型版本在父模型群組頁面中顯示。

------

## 從其他帳戶註冊模型版本
<a name="model-registry-version-xaccount"></a>

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

若要啟用跨帳戶探索能力，允許其他帳戶從資源擁有者帳戶檢視模型套件群組，請參閱[跨帳戶探索能力](model-registry-ram.md)。

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

若要在 SageMaker AI 中啟用跨帳戶模型註冊庫，您必須為包含模型版本的模型群組提供跨帳戶資源政策。下列範例為模型群組建立了跨帳戶政策，並將這些政策套用至特定資源。

必須為在模型群組中註冊模型跨帳戶存取權的來源帳戶設定下列組態。在此範例中，來源帳戶是模型訓練帳戶，該帳戶將訓練模型，然後將模型跨帳戶存取權註冊到模型註冊表帳戶的模型註冊表中。

此範例假設您先前已定義下列變數：
+ `sm_client` - SageMaker AI Boto3 用戶端。
+ `model_package_group_name` - 您要授予存取權的模型群組。
+ `model_package_group_arn` - 您要授與跨帳戶存取權的模型群組 ARN。
+ `bucket` - 存放模型訓練成品的 Amazon S3 儲存貯體。

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

### 必要的 IAM 資源政策
<a name="model-registry-version-xaccount-policies"></a>

下圖展示允許跨帳戶模型註冊時所必要的政策。如圖所示，這些政策必須在模型訓練期間處於作用中狀態，模型才能正確註冊至模型註冊表帳戶。

![\[\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_registry_cross_account.png)


Amazon ECR、Amazon S3 和 AWS KMS 政策會在下列程式碼範例中示範。

**Amazon ECR 政策範例**

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AddPerm",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:root"
            },
            "Action": [
                "ecr:BatchGetImage",
                "ecr:Describe*"
            ]
        }
    ]
}
```

------

**Amazon S3 政策範例**

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AddPerm",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:root"
            },
            "Action": [
                "s3:GetObject",
                "s3:GetBucketAcl",
                "s3:GetObjectAcl"
            ],
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
        }
    ]
}
```

------

**範例 AWS KMS 政策**

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AddPerm",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:root"
            },
            "Action": [
                "kms:Decrypt",
                "kms:GenerateDataKey*"
            ],
            "Resource": "*"
        }
    ]
}
```

------

### 將資源政策套用至帳戶
<a name="model-registry-version-xaccount-policy-usage"></a>

下列政策組態會套用前一節中討論的政策，且必須放入模型訓練帳戶。

```
import json

# The Model Registry account id of the Model Group 
model_registry_account = "111111111111"

# The model training account id where training happens
model_training_account = "222222222222"

# 1. Create a policy for access to the ECR repository 
# in the model training account for the Model Registry account Model Group
ecr_repository_policy = {"Version": "2012-10-17",		 	 	 
    "Statement": [{"Sid": "AddPerm",
        "Effect": "Allow",
        "Principal": {
          "AWS": f"arn:aws:iam::{model_registry_account}:root"
        },
        "Action": [
          "ecr:BatchGetImage",
          "ecr:Describe*"
        ]
    }]
}

# 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 = model_training_account,
    repositoryName = "decision-trees-sample",
    policyText = ecr_repository_policy
)

# 2. Create a policy in the model training account for access to the S3 bucket 
# where the model is present in the Model Registry account Model Group
bucket_policy = {"Version": "2012-10-17",		 	 	 
    "Statement": [{"Sid": "AddPerm",
        "Effect": "Allow",
        "Principal": {"AWS": f"arn:aws:iam::{model_registry_account}:root"
        },
        "Action": [
          "s3:GetObject",
          "s3:GetBucketAcl",
          "s3:GetObjectAcl"
        ],
        "Resource": [
          "arn:aws:s3:::{bucket}/*",
	  "Resource: arn:aws:s3:::{bucket}"
        ]
    }]
}

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

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

# 3. Create the KMS grant for the key used during training for encryption
# in the model training account to the Model Registry account Model Group
client = boto3.client("kms")

response = client.create_grant(
    GranteePrincipal=model_registry_account,
    KeyId=kms_key_id
    Operations=[
        "Decrypt",
        "GenerateDataKey",
    ],
)
```

下列組態必須放入模型群組所在的模型註冊表帳戶。

```
# The Model Registry account id of the Model Group 
model_registry_account = "111111111111"

# 1. Create policy to allow the model training account to access the ModelPackageGroup
model_package_group_policy = {"Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AddPermModelPackageVersion",
            "Effect": "Allow",
            "Principal": {"AWS": f"arn:aws:iam::{model_training_account}:root"},
            "Action": ["sagemaker:CreateModelPackage"],
            "Resource": f"arn:aws:sagemaker:{region}:{model_registry_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 new policy
response = sm_client.put_model_package_group_policy(
    ModelPackageGroupName = model_package_group_name,
    ResourcePolicy = model_package_group_policy)
```

最後，透過模型訓練帳戶使用 `create_model_package` 動作跨帳戶註冊模型套件。

```
# Specify the model source
model_url = "s3://{bucket}/model.tar.gz"

#Set up the parameter dictionary to pass to the create_model_package API operation
modelpackage_inference_specification =  {
    "InferenceSpecification": {
        "Containers": [
            {
                "Image": f"{model_training_account}.dkr.ecr.us-east-2.amazonaws.com/decision-trees-sample:latest",
                "ModelDataUrl": model_url
            }
        ],
        "SupportedContentTypes": [ "text/csv" ],
        "SupportedResponseMIMETypes": [ "text/csv" ],
    }
}

# Alternatively, you can specify the model source like this:
# modelpackage_inference_specification["InferenceSpecification"]["Containers"][0]["ModelDataUrl"]=model_url

create_model_package_input_dict = {
    "ModelPackageGroupName" : model_package_group_arn,
    "ModelPackageDescription" : "Model to detect 3 different types of irises (Setosa, Versicolour, and Virginica)",
    "ModelApprovalStatus" : "PendingManualApproval"
}
create_model_package_input_dict.update(modelpackage_inference_specification)

# Create the model package in the Model Registry account
create_model_package_response = sm_client.create_model_package(**create_model_package_input_dict)
model_package_arn = create_model_package_response["ModelPackageArn"]
print('ModelPackage Version ARN : {}'.format(model_package_arn))
```