

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# モデルバージョンを登録する
<a name="model-registry-version"></a>

Amazon SageMaker AI モデルを登録するには、モデルが属するモデルグループを指定するモデルバージョンを作成します。モデルバージョンには、モデルのアーティファクト (モデルの学習済みの加重) が含まれている必要があります。必要に応じて、モデルの推論コードを含めることができます。

*推論パイプライン*は、推論リクエストを処理する、直線上に並んだ 2～15 個のコンテナで構成される SageMaker AI モデルです。コンテナと関連する環境変数を指定して、推論パイプラインを登録します。推論パイプラインの詳細については、「[Amazon SageMaker AI の推論パイプライン](inference-pipelines.md)」を参照してください。

コンテナと関連する環境変数を指定して、推論パイプラインを持つモデルを登録します。推論パイプラインを使用してモデルバージョンを作成するには AWS SDK for Python (Boto3)、、Amazon SageMaker Studio コンソールを使用するか、SageMaker AI モデル構築パイプラインでステップを作成します。次の手順を実行します。

**Topics**
+ [モデルバージョンを登録する (SageMaker AI パイプライン)](#model-registry-pipeline)
+ [モデルバージョンを登録する (Boto3)](#model-registry-version-api)
+ [モデルのバージョンを登録する (Studio または Studio Classic)](#model-registry-studio)
+ [別のアカウントからモデルバージョンを登録する](#model-registry-version-xaccount)

## モデルバージョンを登録する (SageMaker AI パイプライン)
<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. 「[Launch 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 にサインインします。詳細については、「[Launch 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/ja_jp/sagemaker/latest/dg/images/studio/icons/house.png)) を選択します。

1. **[モデル]** を選択し、**[モデルレジストリ]** を選択します。

1. **[バージョンを登録]** フォームを開きます。これには以下の 2 つの方法があります。
   + **[アクション]** を選択してから、**[モデルバージョンを作成]** をクリックします。
   + モデルバージョンを作成するモデルグループの名前を選択し、**[モデルバージョンを作成]** を選択します。

1. **[モデルバージョンを登録]** フォームに、次の情報を入力します。
   + **[モデルパッケージグループ名]** ドロップダウンで、モデルグループ名を選択します。
   + (オプション) モデルバージョンの説明を入力します。
   + **[モデル承認ステータス]** ドロップダウンで、バージョン承認ステータスを選択します。
   + (オプション) **[カスタムメタデータ]** フィールドで、カスタムタグをキー値のペアとして追加します。

1. [**次へ**] を選択します。

1. **[推論の仕様]** フォームに、以下の情報を入力します。
   + 推論イメージの場所を入力します。
   + モデルデータのアーティファクトの場所を入力します。
   + (オプション) 変換ジョブやリアルタイム推論ジョブに使用するイメージと、サポートされている入出力 MIME タイプに関する情報を入力します。

1. [**次へ**] を選択します。

1. (オプション) エンドポイントの推奨に役立つ詳細情報を入力します。

1. [**次へ**] を選択します。

1. (オプション) 含めるモデルメトリクスを選択します。

1. [**次へ**] を選択します。

1. 表示された設定が正しいことを確認し、**[モデルバージョンを登録]** を選択します。その後、モーダルウィンドウにエラーメッセージが表示されたら、(メッセージの横にある) **[表示]** を選択してエラーの原因を確認します。

1. 親モデルグループのページに新しいモデルバージョンが表示されることを確認します。

------

## 別のアカウントからモデルバージョンを登録する
<a name="model-registry-version-xaccount"></a>

別の AWS アカウントによって作成されたモデルグループにモデルバージョンを登録するには、クロスアカウント AWS Identity and Access Management リソースポリシーを追加して、そのアカウントを有効にする必要があります。たとえば、組織内の 1 つの 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 でクロスアカウントのモデルレジストリを有効にするには、モデルバージョンを含むモデルグループ用のクロスアカウントリソースポリシーを指定する必要があります。モデルパッケージグループのクロスアカウントポリシーを作成し、その特定のリソースにこのポリシーを適用する例を以下に示します。

アカウントをまたいでモデルグループにモデルを登録するソースアカウントで、次を設定する必要があります。この例では、ソースアカウントはモデルトレーニングアカウントであり、モデルクロスアカウントをトレーニングし、Model Registry アカウントの Model Registry に登録します。

この例では、次の変数が事前に定義されていることを前提としています。
+ `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>

以下の図は、クロスアカウントモデル登録を可能にするために必要なポリシーをまとめたものです。図のように、モデルを Model Registry アカウントに正しく登録するには、モデルトレーニング中これらのポリシーをに有効にする必要があります。

![\[\]](http://docs.aws.amazon.com/ja_jp/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",
    ],
)
```

次の設定は、Model Group がある Model Registry アカウントに配置する必要があります。

```
# 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))
```