

# Model Registration Deployment with Model Registry
<a name="model-registry"></a>

With the Amazon SageMaker Model Registry you can do the following:
+ Catalog models for production.
+ Manage model versions.
+ Associate metadata, such as training metrics, with a model.
+ View information from Amazon SageMaker Model Cards in your registered models. 
+ View model lineage for traceability and reproducibility.
+ Define a staging construct that models can progress through for your model lifecycle.
+ Manage the approval status of a model.
+ Deploy models to production.
+ Automate model deployment with CI/CD.
+ Share models with other users.

Catalog models by creating SageMaker Model Registry Model (Package) Groups that contain different versions of a model. You can create a Model Group that tracks all of the models that you train to solve a particular problem. You can then register each model you train and the Model Registry adds it to the Model Group as a new model version. Lastly, you can create categories of Model Groups by further organizing them into SageMaker Model Registry Collections. A typical workflow might look like the following:
+ Create a Model Group.
+ Create an ML pipeline that trains a model. For information about SageMaker pipelines, see [Pipelines actions](pipelines-build.md).
+ For each run of the ML pipeline, create a model version that you register in the Model Group you created in the first step.
+ Add your Model Group into one or more Model Registry Collections.

For details about how to create and work with models, model versions, and Model Groups, see [Model Registry Models, Model Versions, and Model Groups](model-registry-models.md). Optionally, if you want to further group your Model Groups into Collections, see [Model Registry Collections](modelcollections.md).

# Model Registry Models, Model Versions, and Model Groups
<a name="model-registry-models"></a>

The SageMaker Model Registry is structured as several Model (Package) Groups with model packages in each group. These Model Groups can optionally be added to one or more Collections. Each model package in a Model Group corresponds to a trained model. The version of each model package is a numerical value that starts at 1 and is incremented with each new model package added to a Model Group. For example, if 5 model packages are added to a Model Group, the model package versions will be 1, 2, 3, 4, and 5. 

 A model package is the actual model that is registered into the Model Registry as a versioned entity. There are two types of model packages in SageMaker AI. One type is used in the AWS Marketplace, and the other is used in the Model Registry. Model packages used in the AWS Marketplace are not versionable entities and are not associated with Model Groups in the Model Registry. The Model Registry receives every new model that you retrain, gives it a version, and assigns it to a Model Group inside the Model Registry. The following image shows an example of a Model Group with 25 consecutively-versioned models. For more information about model packages used in the AWS Marketplace, see [Algorithms and packages in the AWS Marketplace](sagemaker-marketplace.md).

The model packages used in the Model Registry are versioned, and **must** be associated with a Model Group. The ARN of this model package type has the structure: `'arn:aws:sagemaker:region:account:model-package-group/version'`

The following topics show you how to create and work with models, model versions, and Model Groups in the Model Registry.

**Topics**
+ [Create a Model Group](model-registry-model-group.md)
+ [Delete a Model Group](model-registry-delete-model-group.md)
+ [Register a Model Version](model-registry-version.md)
+ [View Model Groups and Versions](model-registry-view.md)
+ [Update the Details of a Model Version](model-registry-details.md)
+ [Compare Model Versions](model-registry-version-compare.md)
+ [View and Manage Model Group and Model Version Tags](model-registry-tags.md)
+ [Delete a Model Version](model-registry-delete-model-version.md)
+ [Staging Construct for your Model Lifecycle](model-registry-staging-construct.md)
+ [Update the Approval Status of a Model](model-registry-approve.md)
+ [Deploy a Model from the Registry with Python](model-registry-deploy.md)
+ [Deploy a Model in Studio](model-registry-deploy-studio.md)
+ [Cross-account discoverability](model-registry-ram.md)
+ [View the Deployment History of a Model](model-registry-deploy-history.md)
+ [View model lineage details in Studio](model-registry-lineage-view-studio.md)

# Create a Model Group
<a name="model-registry-model-group"></a>

A Model Group contains different versions of a model. You can create a Model Group that tracks all of the models that you train to solve a particular problem. Create a Model Group by using either the AWS SDK for Python (Boto3) or the Amazon SageMaker Studio console.

## Create a Model Group (Boto3)
<a name="model-registry-package-group-api"></a>

**Important**  
Custom IAM policies that allow Amazon SageMaker Studio or Amazon SageMaker Studio Classic to create Amazon SageMaker resources must also grant permissions to add tags to those resources. The permission to add tags to resources is required because Studio and Studio Classic automatically tag any resources they create. If an IAM policy allows Studio and Studio Classic to create resources but does not allow tagging, "AccessDenied" errors can occur when trying to create resources. For more information, see [Provide permissions for tagging SageMaker AI resources](security_iam_id-based-policy-examples.md#grant-tagging-permissions).  
[AWS managed policies for Amazon SageMaker AI](security-iam-awsmanpol.md) that give permissions to create SageMaker resources already include permissions to add tags while creating those resources.

To create a Model Group by using Boto3, call the `create_model_package_group` API operation and specify a name and description as parameters. The following example shows how to create a Model Group. The response from the `create_model_package_group` call is the Amazon Resource Name (ARN) of the new Model Group.

First, import the required packages and set up the SageMaker AI Boto3 client.

```
import time
import os
from sagemaker import get_execution_role, session
import boto3

region = boto3.Session().region_name

role = get_execution_role()

sm_client = boto3.client('sagemaker', region_name=region)
```

Now create the Model Group.

```
import time
model_package_group_name = "scikit-iris-detector-" + str(round(time.time()))
model_package_group_input_dict = {
 "ModelPackageGroupName" : model_package_group_name,
 "ModelPackageGroupDescription" : "Sample model package group"
}

create_model_package_group_response = sm_client.create_model_package_group(**model_package_group_input_dict)
print('ModelPackageGroup Arn : {}'.format(create_model_package_group_response['ModelPackageGroupArn']))
```

## Create a Model Group (Studio or Studio Classic)
<a name="model-registry-package-group-studio"></a>

To create a Model Group in the Amazon SageMaker Studio console, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models**.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. Choose **Register**, then choose **Model group**.

1. In the **Register model group** dialog box, enter the following information:
   + The name of the new Model Group in the **Model group name** field.
   + (Optional) A description for the Model Group in the **Description** field.
   + (Optional) Any key-value pairs you want to associate with the Model Group in the **Tags** field. For information about using tags, see [Tagging AWS resources](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) in the *AWS General Reference*.

1. Choose **Register model group**.

1. (Optional) In the **Models** page, choose the **Registered models** tab, then choose **Model Groups**. Confirm your newly-created Model Group appears in the list of Model Groups.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. Choose **Actions**, then choose **Create model group**.

1. In the **Create model group** dialog box, enter the following information:
   + Enter the name of the new Model Group in the **Model group name** field.
   + (Optional) Enter a description for the Model Group in the **Description** field.
   + (Optional) Enter any key-value pairs you want to associate with the Model Group in the **Tags** field. For information about using tags, see [Tagging AWS resources](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) in the *AWS General Reference*.
   + (Optional) Choose a project with which to associate the Model Group in the **Project** field. For information about projects, see [MLOps Automation With SageMaker Projects](sagemaker-projects.md).

1. Choose **Create model group**.

------

# Delete a Model Group
<a name="model-registry-delete-model-group"></a>

This procedure demonstrates how to delete a Model Group in the Amazon SageMaker Studio console. When you delete a Model Group, you lose access to the model versions in the Model Group.

## Delete a Model Group (Studio or Studio Classic)
<a name="model-registry-delete-model-group-studio"></a>

**Important**  
You can only delete an empty model group. Before you delete your model group, remove its model versions, if any.

To delete a Model Group in the Amazon SageMaker Studio console, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models**.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the model groups list, select the check box next to the name of the Model Group you want to delete.

1. Choose the vertical ellipsis above the top right corner of the model groups list, and choose **Delete**.

1. In the **Delete model group** dialog box, choose **Yes, delete the model group**.

1. Choose **Delete**.

1. Confirm that your deleted model groups no longer appear in your list of model groups.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**. A list of your Model Groups appears.

1. From the model groups list, select the name of the Model Group you want to delete.

1. In the top right corner, choose **Remove**.

1. In the confirmation dialog box, enter `REMOVE`.

1. Choose **Remove**.

------

# Register a Model Version
<a name="model-registry-version"></a>

You can register an Amazon SageMaker AI model by creating a model version that specifies the model group to which it belongs. A model version must include a model artifacts (the trained weights of a model) and optionally the inference code for the model.

An *inference pipeline* is a SageMaker AI model composed of a linear sequence of two to fifteen containers that process inference requests. You register an inference pipeline by specifying the containers and the associated environment variables. For more information on inference pipelines, see [Inference pipelines in Amazon SageMaker AI](inference-pipelines.md).

You can register a model with an inference pipeline, by specifying the containers and the associated environment variables. To create a model version with an inference pipeline by using either the AWS SDK for Python (Boto3), the Amazon SageMaker Studio console, or by creating a step in a SageMaker AI model building pipeline, use the following steps. 

**Topics**
+ [Register a Model Version (SageMaker AI Pipelines)](#model-registry-pipeline)
+ [Register a Model Version (Boto3)](#model-registry-version-api)
+ [Register a Model Version (Studio or Studio Classic)](#model-registry-studio)
+ [Register a Model Version from a Different Account](#model-registry-version-xaccount)

## Register a Model Version (SageMaker AI Pipelines)
<a name="model-registry-pipeline"></a>

To register a model version by using a SageMaker AI model building pipeline, create a `RegisterModel` step in your pipeline. For information about creating a `RegisterModel` step as part of a pipeline, see [Step 8: Define a RegisterModel step to create a model package](define-pipeline.md#define-pipeline-register).

## Register a Model Version (Boto3)
<a name="model-registry-version-api"></a>

To register a model version by using Boto3, call the `create_model_package` API operation.

First, you set up the parameter dictionary to pass to the `create_model_package` API operation.

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

Then you call the `create_model_package` API operation, passing in the parameter dictionary that you just set up.

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

## Register a Model Version (Studio or Studio Classic)
<a name="model-registry-studio"></a>

To register a model version in the Amazon SageMaker Studio console, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** from the menu.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups** and **My models**, if not selected already.

1. Choose **Register**. This will open the **Register model** page.

1. Follow the instructions provided in the **Register model** page. 

1. Once you have reviewed your choices, choose **Register**. Once completed, you will be taken to the model version **Overview** page.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. Open the **Register Version** form. You can do this in one of two ways:
   + Choose **Actions**, and then choose **Create model version**.
   + Select the name of the model group for which you want to create a model version, then choose **Create model version**.

1. In the **Register model version** form, enter the following information:
   + In the **Model package group name** dropdown, select the model group name.
   + (Optional) Enter a description for your model version.
   + In the **Model Approval Status** dropdown, select the version approval status.
   + (Optional) In the **Custom metadata** field, add custom tags as key-value pairs.

1. Choose **Next**.

1. In the **Inference Specification** form, enter the following information:
   + Enter your inference image location.
   + Enter your model data artifacts location.
   + (Optional) Enter information about images to use for transform and real-time inference jobs, and supported input and output MIME types.

1. Choose **Next**.

1. (Optional) Provide details to aid endpoint recommendations.

1. Choose **Next**.

1. (Optional) Choose model metrics you want to include.

1. Choose **Next**.

1. Ensure the displayed settings are correct, and choose **Register model version**. If you subsequently see a modal window with an error message, choose **View** (next to the message) to view the source of the error.

1. Confirm your new model version appears in the parent model group page.

------

## Register a Model Version from a Different Account
<a name="model-registry-version-xaccount"></a>

To register model versions with a Model Group created by a different AWS account, you must add a cross-account AWS Identity and Access Management resource policy to enable that account. For example, one AWS account in your organization is responsible for training models, and a different account is responsible for managing, deploying, and updating models. You create IAM resource policies and apply the policies to the specific account resource to which you want to grant access for this case. For more information about cross-account resource policies in AWS, see [Cross-account policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic-cross-account.html) in the *AWS Identity and Access Management User Guide*.

To enable cross-account discoverability, which allows other accounts to view model package groups from the resource owner account, see [Cross-account discoverability](model-registry-ram.md).

**Note**  
You must also use a KMS key to encrypt the [output data config](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_OutputDataConfig.html) action during training for cross-account model deployment.

To enable cross-account model registry in SageMaker AI, you have to provide a cross-account resource policy for the Model Group that contains the model versions. The following is an example that creates cross-account policies for the Model Group and applies these policies to that specific resource.

The following configuration must be set in the source account which registers models cross-account in a Model Group. In this example, the source account is the model training account which will train and then register the model cross-account into the Model Registry of the Model Registry account.

The example assumes that you previously defined the following variables:
+ `sm_client` – A SageMaker AI Boto3 client.
+ `model_package_group_name` – The Model Group to which you want to grant access.
+ `model_package_group_arn` – The Model Group ARN to which you want to grant cross-account access.
+ `bucket` – The Amazon S3 bucket where the model training artifacts are stored.

To be able to deploy a model created in a different account, the user must have a role that has access to SageMaker AI actions, such as a role with the `AmazonSageMakerFullAccess` managed policy. For information about SageMaker AI managed policies, see [AWS managed policies for Amazon SageMaker AI](security-iam-awsmanpol.md).

### Required IAM resource policies
<a name="model-registry-version-xaccount-policies"></a>

The following diagram captures the policies required to allow cross-account model registration. As shown, these policies need to be active during model training to properly register the model into the Model Registry account.

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


Amazon ECR, Amazon S3, and AWS KMS policies are demonstrated in the following code samples. 

**Sample Amazon ECR policy**

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

****  

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

------

**Sample Amazon S3 policy**

------
#### [ 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/*"
        }
    ]
}
```

------

**Sample AWS KMS policy**

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

****  

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

------

### Apply resource policies to accounts
<a name="model-registry-version-xaccount-policy-usage"></a>

The following policy configuration applies the policies discussed in the previous section and must be put in the model training account.

```
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 following configuration needs to be put in the Model Registry account where the Model Group exists.

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

Finally, use the `create_model_package` action from the model training account to register the model package in the cross-account.

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

# View Model Groups and Versions
<a name="model-registry-view"></a>

Model Groups and versions help you organize your models. You can view a list of the model versions in a Model Group by using either the AWS SDK for Python (Boto3) (Boto3) or the Amazon SageMaker Studio console.

## View a List of Model Versions in a Group
<a name="model-registry-view-list"></a>

You can view all of the model versions that are associated with a Model Group. If a Model Group represents all models that you train to address a specific ML problem, you can view all of those related models.

### View a List of Model Versions in a Group (Boto3)
<a name="model-registry-view-list-api"></a>

To view model versions associated with a Model Group by using Boto3, call the `list_model_packages` API operation, and pass the name of the Model Group as the value of the `ModelPackageGroupName` parameter. The following code lists the model versions associated with the Model Group you created in [Create a Model Group (Boto3)](model-registry-model-group.md#model-registry-package-group-api).

```
sm_client.list_model_packages(ModelPackageGroupName=model_package_group_name)
```

### View a List of Model Versions in a Group (Studio or Studio Classic)
<a name="model-registry-view-list-studio"></a>

To view a list of the model versions in a Model Group in the Amazon SageMaker Studio console, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** from the menu.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the model groups list, choose the angle bracket to the left of the model group you want to view.

1. A list of the model versions in the model group appears.

1. (Optional) Choose **View all**, if shown, to view additional model versions.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the model groups list, select the name of the Model Group you want to view.

1. A new tab appears with a list of the model versions in the Model Group.

------

# Update the Details of a Model Version
<a name="model-registry-details"></a>

You can view and update details of a specific model version by using either the AWS SDK for Python (Boto3) or the Amazon SageMaker Studio console.

**Important**  
Amazon SageMaker AI integrates Model Cards into Model Registry. A model package registered in the Model Registry includes a simplified Model Card as a component of the model package. For more information, see [Model package model card schema (Studio)](#model-card-schema).

## View and Update the Details of a Model Version (Boto3)
<a name="model-registry-details-api"></a>

To view the details of a model version by using Boto3, complete the following steps.

1. Call the `list_model_packages` API operation to view the model versions in a Model Group.

   ```
   sm_client.list_model_packages(ModelPackageGroupName="ModelGroup1")
   ```

   The response is a list of model package summaries. You can get the Amazon Resource Name (ARN) of the model versions from this list.

   ```
   {'ModelPackageSummaryList': [{'ModelPackageGroupName': 'AbaloneMPG-16039329888329896',
      'ModelPackageVersion': 1,
      'ModelPackageArn': 'arn:aws:sagemaker:us-east-2:123456789012:model-package/ModelGroup1/1',
      'ModelPackageDescription': 'TestMe',
      'CreationTime': datetime.datetime(2020, 10, 29, 1, 27, 46, 46000, tzinfo=tzlocal()),
      'ModelPackageStatus': 'Completed',
      'ModelApprovalStatus': 'Approved'}],
    'ResponseMetadata': {'RequestId': '12345678-abcd-1234-abcd-aabbccddeeff',
     'HTTPStatusCode': 200,
     'HTTPHeaders': {'x-amzn-requestid': '12345678-abcd-1234-abcd-aabbccddeeff',
      'content-type': 'application/x-amz-json-1.1',
      'content-length': '349',
      'date': 'Mon, 23 Nov 2020 04:56:50 GMT'},
     'RetryAttempts': 0}}
   ```

1. Call `describe_model_package` to see the details of the model version. You pass in the ARN of a model version that you got in the output of the call to `list_model_packages`.

   ```
   sm_client.describe_model_package(ModelPackageName="arn:aws:sagemaker:us-east-2:123456789012:model-package/ModelGroup1/1")
   ```

   The output of this call is a JSON object with the model version details.

   ```
   {'ModelPackageGroupName': 'ModelGroup1',
    'ModelPackageVersion': 1,
    'ModelPackageArn': 'arn:aws:sagemaker:us-east-2:123456789012:model-package/ModelGroup/1',
    'ModelPackageDescription': 'Test Model',
    'CreationTime': datetime.datetime(2020, 10, 29, 1, 27, 46, 46000, tzinfo=tzlocal()),
    'InferenceSpecification': {'Containers': [{'Image': '257758044811.dkr.ecr.us-east-2.amazonaws.com/sagemaker-xgboost:1.0-1-cpu-py3',
       'ImageDigest': 'sha256:99fa602cff19aee33297a5926f8497ca7bcd2a391b7d600300204eef803bca66',
       'ModelDataUrl': 's3://sagemaker-us-east-2-123456789012/ModelGroup1/pipelines-0gdonccek7o9-AbaloneTrain-stmiylhtIR/output/model.tar.gz'}],
     'SupportedTransformInstanceTypes': ['ml.m5.xlarge'],
     'SupportedRealtimeInferenceInstanceTypes': ['ml.t2.medium', 'ml.m5.xlarge'],
     'SupportedContentTypes': ['text/csv'],
     'SupportedResponseMIMETypes': ['text/csv']},
    'ModelPackageStatus': 'Completed',
    'ModelPackageStatusDetails': {'ValidationStatuses': [],
     'ImageScanStatuses': []},
    'CertifyForMarketplace': False,
    'ModelApprovalStatus': 'PendingManualApproval',
    'LastModifiedTime': datetime.datetime(2020, 10, 29, 1, 28, 0, 438000, tzinfo=tzlocal()),
    'ResponseMetadata': {'RequestId': '12345678-abcd-1234-abcd-aabbccddeeff',
     'HTTPStatusCode': 200,
     'HTTPHeaders': {'x-amzn-requestid': '212345678-abcd-1234-abcd-aabbccddeeff',
      'content-type': 'application/x-amz-json-1.1',
      'content-length': '1038',
      'date': 'Mon, 23 Nov 2020 04:59:38 GMT'},
     'RetryAttempts': 0}}
   ```

### Model package model card schema (Studio)
<a name="model-card-schema"></a>

All details related to the model version are encapsulated in the model package’s model card. The model card of a model package is a special usage of the Amazon SageMaker Model Card and its schema is simplified. The model package model card schema is shown in the following expandable dropdown.

#### Model package model card schema
<a name="collapsible-section-model-package-model-card-schema"></a>

```
{
  "title": "SageMakerModelCardSchema",
  "description": "Schema of a model package’s model card.",
  "version": "0.1.0",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "model_overview": {
      "description": "Overview about the model.",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "model_creator": {
          "description": "Creator of model.",
          "type": "string",
          "maxLength": 1024
        },
        "model_artifact": {
          "description": "Location of the model artifact.",
          "type": "array",
          "maxContains": 15,
          "items": {
            "type": "string",
            "maxLength": 1024
          }
        }
      }
    },
    "intended_uses": {
      "description": "Intended usage of model.",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "purpose_of_model": {
          "description": "Reason the model was developed.",
          "type": "string",
          "maxLength": 2048
        },
        "intended_uses": {
          "description": "Intended use cases.",
          "type": "string",
          "maxLength": 2048
        },
        "factors_affecting_model_efficiency": {
          "type": "string",
          "maxLength": 2048
        },
        "risk_rating": {
          "description": "Risk rating for model card.",
          "$ref": "#/definitions/risk_rating"
        },
        "explanations_for_risk_rating": {
          "type": "string",
          "maxLength": 2048
        }
      }
    },
    "business_details": {
      "description": "Business details of model.",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "business_problem": {
          "description": "Business problem solved by the model.",
          "type": "string",
          "maxLength": 2048
        },
        "business_stakeholders": {
          "description": "Business stakeholders.",
          "type": "string",
          "maxLength": 2048
        },
        "line_of_business": {
          "type": "string",
          "maxLength": 2048
        }
      }
    },
    "training_details": {
      "description": "Overview about the training.",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "objective_function": {
          "description": "The objective function for which the model is optimized.",
          "function": {
            "$ref": "#/definitions/objective_function"
          },
          "notes": {
            "type": "string",
            "maxLength": 1024
          }
        },
        "training_observations": {
          "type": "string",
          "maxLength": 1024
        },
        "training_job_details": {
          "type": "object",
          "additionalProperties": false,
          "properties": {
            "training_arn": {
              "description": "SageMaker Training job ARN.",
              "type": "string",
              "maxLength": 1024
            },
            "training_datasets": {
              "description": "Location of the model datasets.",
              "type": "array",
              "maxContains": 15,
              "items": {
                "type": "string",
                "maxLength": 1024
              }
            },
            "training_environment": {
              "type": "object",
              "additionalProperties": false,
              "properties": {
                "container_image": {
                  "description": "SageMaker training image URI.",
                  "type": "array",
                  "maxContains": 15,
                  "items": {
                    "type": "string",
                    "maxLength": 1024
                  }
                }
              }
            },
            "training_metrics": {
              "type": "array",
              "items": {
                "maxItems": 50,
                "$ref": "#/definitions/training_metric"
              }
            },
            "user_provided_training_metrics": {
              "type": "array",
              "items": {
                "maxItems": 50,
                "$ref": "#/definitions/training_metric"
              }
            },
            "hyper_parameters": {
              "type": "array",
              "items": {
                "maxItems": 100,
                "$ref": "#/definitions/training_hyper_parameter"
              }
            },
            "user_provided_hyper_parameters": {
              "type": "array",
              "items": {
                "maxItems": 100,
                "$ref": "#/definitions/training_hyper_parameter"
              }
            }
          }
        }
      }
    },
    "evaluation_details": {
      "type": "array",
      "default": [],
      "items": {
        "type": "object",
        "required": [
          "name"
        ],
        "additionalProperties": false,
        "properties": {
          "name": {
            "type": "string",
            "pattern": ".{1,63}"
          },
          "evaluation_observation": {
            "type": "string",
            "maxLength": 2096
          },
          "evaluation_job_arn": {
            "type": "string",
            "maxLength": 256
          },
          "datasets": {
            "type": "array",
            "items": {
              "type": "string",
              "maxLength": 1024
            },
            "maxItems": 10
          },
          "metadata": {
            "description": "Additional attributes associated with the evaluation results.",
            "type": "object",
            "additionalProperties": {
              "type": "string",
              "maxLength": 1024
            }
          },
          "metric_groups": {
            "type": "array",
            "default": [],
            "items": {
              "type": "object",
              "required": [
                "name",
                "metric_data"
              ],
              "properties": {
                "name": {
                  "type": "string",
                  "pattern": ".{1,63}"
                },
                "metric_data": {
                  "type": "array",
                  "items": {
                    "anyOf": [
                      {
                        "$ref": "#/definitions/simple_metric"
                      },
                      {
                        "$ref": "#/definitions/linear_graph_metric"
                      },
                      {
                        "$ref": "#/definitions/bar_chart_metric"
                      },
                      {
                        "$ref": "#/definitions/matrix_metric"
                      }
                    ]

                  }
                }
              }
            }
          }
        }
      }
    },
    "additional_information": {
      "additionalProperties": false,
      "type": "object",
      "properties": {
        "ethical_considerations": {
          "description": "Ethical considerations for model users.",
          "type": "string",
          "maxLength": 2048
        },
        "caveats_and_recommendations": {
          "description": "Caveats and recommendations for model users.",
          "type": "string",
          "maxLength": 2048
        },
        "custom_details": {
          "type": "object",
          "additionalProperties": {
            "$ref": "#/definitions/custom_property"
          }
        }
      }
    }
  },
  "definitions": {
    "source_algorithms": {
      "type": "array",
      "minContains": 1,
      "maxContains": 1,
      "items": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "algorithm_name"
        ],
        "properties": {
          "algorithm_name": {
            "description": "The name of the algorithm used to create the model package. The algorithm must be either an algorithm resource in your SageMaker AI account or an algorithm in AWS Marketplace that you are subscribed to.",
            "type": "string",
            "maxLength": 170
          },
          "model_data_url": {
            "description": "Amazon S3 path where the model artifacts, which result from model training, are stored.",
            "type": "string",
            "maxLength": 1024
          }
        }
      }
    },
    "inference_specification": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "containers"
      ],
      "properties": {
        "containers": {
          "description": "Contains inference related information used to create model package.",
          "type": "array",
          "minContains": 1,
          "maxContains": 15,
          "items": {
            "type": "object",
            "additionalProperties": false,
            "required": [
              "image"
            ],
            "properties": {
              "model_data_url": {
                "description": "Amazon S3 path where the model artifacts, which result from model training, are stored.",
                "type": "string",
                "maxLength": 1024
              },
              "image": {
                "description": "Inference environment path. The Amazon Elastic Container Registry (Amazon ECR) path where inference code is stored.",
                "type": "string",
                "maxLength": 255
              },
              "nearest_model_name": {
                "description": "The name of a pre-trained machine learning benchmarked by an Amazon SageMaker Inference Recommender model that matches your model.",
                "type": "string"
              }
            }
          }
        }
      }
    },
    "risk_rating": {
      "description": "Risk rating of model.",
      "type": "string",
      "enum": [
        "High",
        "Medium",
        "Low",
        "Unknown"
      ]
    },
    "custom_property": {
      "description": "Additional property.",
      "type": "string",
      "maxLength": 1024
    },
    "objective_function": {
      "description": "Objective function for which the training job is optimized.",
      "additionalProperties": false,
      "properties": {
        "function": {
          "type": "string",
          "enum": [
            "Maximize",
            "Minimize"
          ]
        },
        "facet": {
          "type": "string",
          "maxLength": 63
        },
        "condition": {
          "type": "string",
          "maxLength": 63
        }
      }
    },
    "training_metric": {
      "description": "Training metric data.",
      "type": "object",
      "required": [
        "name",
        "value"
      ],
      "additionalProperties": false,
      "properties": {
        "name": {
          "type": "string",
          "pattern": ".{1,255}"
        },
        "notes": {
          "type": "string",
          "maxLength": 1024
        },
        "value": {
          "type": "number"
        }
      }
    },
    "training_hyper_parameter": {
      "description": "Training hyperparameter.",
      "type": "object",
      "required": [
        "name",
        "value"
      ],
      "additionalProperties": false,
      "properties": {
        "name": {
          "type": "string",
          "pattern": ".{1,255}"
        },
        "value": {
          "type": "string",
          "pattern": ".{1,255}"
        }
      }
    },
    "linear_graph_metric": {
      "type": "object",
      "required": [
        "name",
        "type",
        "value"
      ],
      "additionalProperties": false,
      "properties": {
        "name": {
          "type": "string",
          "pattern": ".{1,255}"
        },
        "notes": {
          "type": "string",
          "maxLength": 1024
        },
        "type": {
          "type": "string",
          "enum": [
            "linear_graph"
          ]
        },
        "value": {
          "anyOf": [
            {
              "type": "array",
              "items": {
                "type": "array",
                "items": {
                  "type": "number"
                },
                "minItems": 2,
                "maxItems": 2
              },
              "minItems": 1
            }
          ]
        },
        "x_axis_name": {
          "$ref": "#/definitions/axis_name_string"
        },
        "y_axis_name": {
          "$ref": "#/definitions/axis_name_string"
        }
      }
    },
    "bar_chart_metric": {
      "type": "object",
      "required": [
        "name",
        "type",
        "value"
      ],
      "additionalProperties": false,
      "properties": {
        "name": {
          "type": "string",
          "pattern": ".{1,255}"
        },
        "notes": {
          "type": "string",
          "maxLength": 1024
        },
        "type": {
          "type": "string",
          "enum": [
            "bar_chart"
          ]
        },
        "value": {
          "anyOf": [
            {
              "type": "array",
              "items": {
                "type": "number"
              },
              "minItems": 1
            }
          ]
        },
        "x_axis_name": {
          "$ref": "#/definitions/axis_name_array"
        },
        "y_axis_name": {
          "$ref": "#/definitions/axis_name_string"
        }
      }
    },
    "matrix_metric": {
      "type": "object",
      "required": [
        "name",
        "type",
        "value"
      ],
      "additionalProperties": false,
      "properties": {
        "name": {
          "type": "string",
          "pattern": ".{1,255}"
        },
        "notes": {
          "type": "string",
          "maxLength": 1024
        },
        "type": {
          "type": "string",
          "enum": [
            "matrix"
          ]
        },
        "value": {
          "anyOf": [
            {
              "type": "array",
              "items": {
                "type": "array",
                "items": {
                  "type": "number"
                },
                "minItems": 1,
                "maxItems": 20
              },
              "minItems": 1,
              "maxItems": 20
            }
          ]
        },
        "x_axis_name": {
          "$ref": "#/definitions/axis_name_array"
        },
        "y_axis_name": {
          "$ref": "#/definitions/axis_name_array"
        }
      }
    },
    "simple_metric": {
      "description": "Metric data.",
      "type": "object",
      "required": [
        "name",
        "type",
        "value"
      ],
      "additionalProperties": false,
      "properties": {
        "name": {
          "type": "string",
          "pattern": ".{1,255}"
        },
        "notes": {
          "type": "string",
          "maxLength": 1024
        },
        "type": {
          "type": "string",
          "enum": [
            "number",
            "string",
            "boolean"
          ]
        },
        "value": {
          "anyOf": [
            {
              "type": "number"
            },
            {
              "type": "string",
              "maxLength": 63
            },
            {
              "type": "boolean"
            }
          ]
        },
        "x_axis_name": {
          "$ref": "#/definitions/axis_name_string"
        },
        "y_axis_name": {
          "$ref": "#/definitions/axis_name_string"
        }
      }
    },
    "axis_name_array": {
      "type": "array",
      "items": {
        "type": "string",
        "maxLength": 63
      }
    },
    "axis_name_string": {
      "type": "string",
      "maxLength": 63
    }
  }
}
```

## View and Update the Details of a Model Version (Studio or Studio Classic)
<a name="model-registry-details-studio"></a>

To view and update the details of a model version, complete the following steps based on whether you use Studio or Studio Classic. In Studio Classic, you can update the approval status for a model version. For details, see [Update the Approval Status of a Model](model-registry-approve.md). In Studio, on the other hand, SageMaker AI creates a model card for a model package, and the model version UI provides options to update details in the model card.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** from the menu.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. Select the name of the model group containing the model version to view.

1. In the list of model versions, select the model version to view.

1. Choose one of the following tabs.
   + **Training**: To view or edit details related to your training job, including performance metrics, artifacts, IAM role and encryption, and containers. For more information, see [Add a training job (Studio)](model-registry-details-studio-training.md).
   + **Evaluate**: To view or edit details related to your training job, such as performance metrics, evaluation datasets, and security. For more information, see [Add an evaluation job (Studio)](model-registry-details-studio-evaluate.md).
   + **Audit**: To view or edit high-level details related to the model’s business purpose, usage, risk, and technical details such as algorithm and performance limitations. For more information, see [Update audit (governance) information (Studio)](model-registry-details-studio-audit.md).
   + **Deploy**: To view or edit the location of your inference image container and instances which compose the endpoint. For more information, see [Update deployment information (Studio)](model-registry-details-studio-deploy.md).

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the model groups list, select the name of the Model Group you want to view.

1. A new tab appears with a list of the model versions in the Model Group.

1. In the list of model versions, select the name of the model version for which you want to view details.

1. On the model version tab that opens, choose one of the following to see details about the model version:
   + **Activity**: Shows events for the model version, such as approval status updates.
   + **Model quality**: Reports metrics related to your Model Monitor model quality checks, which compare model predictions to Ground Truth. For more information about Model Monitor model quality checks, see [Model quality](model-monitor-model-quality.md). 
   + **Explainability**: Reports metrics related to your Model Monitor feature attribution checks, which compare the relative rankings of your features in training data versus live data. For more information about Model Monitor explainability checks, see [Feature attribution drift for models in production](clarify-model-monitor-feature-attribution-drift.md).
   + **Bias**: Reports metrics related to your Model Monitor bias drift checks, which compare the distribution of live data to training data. For more information about Model Monitor bias drift checks, see [Bias drift for models in production](clarify-model-monitor-bias-drift.md).
   + **Inference recommender**: Provides initial instance recommendations for optimal performance based on your model and sample payloads.
   + **Load test**: Runs load tests across your choice of instance types when you provide your specific production requirements, such as latency and throughput constraints.
   + **Inference specification**: Displays instance types for your real-time inference and transform jobs, and information about your Amazon ECR containers.
   + **Information**: Shows information such as the project with which the model version is associated, the pipeline that generated the model, the Model Group, and the model's location in Amazon S3.

------

# Add a training job (Studio)
<a name="model-registry-details-studio-training"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the updated Studio experience. For information about using the Studio Classic application, see [Amazon SageMaker Studio Classic](studio.md).

You can add one training job, created externally or with SageMaker AI, to your model. If you add a SageMaker training job, SageMaker AI prepopulates the fields for all of the subpages in the **Train** tab. If you add an externally created training job, you need to add details related to your training job manually. 

**To add a training job to your model package, complete the following steps.**

1. Choose the **Train** tab.

1. Choose **Add**. If you do not see this option, you may already have a training job attached. If you want to remove this training job, complete the following instructions to remove a training job. 

1. You can add a training job you created in SageMaker AI or a training job you created externally.

   1. To add a training job you created in SageMaker AI, complete the following steps.

      1. Choose **SageMaker AI**.

      1. Select the radio box next to the training job you want to add.

      1. Choose **Add**.

   1. To add a training job you created externally, complete the following steps.

      1. Choose **Custom**.

      1. In the **Name** field, insert the name of your custom training job.

      1. Choose **Add**.

# Remove a training job (Studio)
<a name="model-registry-details-studio-training-remove"></a>

You can remove a training job, created externally or with SageMaker AI, from your model by completing the following steps.

**To remove a training job from your model package, complete the following steps.**

1. Choose **Train**.

1. Choose the **Gear** ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/icons/Settings_squid.png)) icon under the **Train** tab.

1. Choose **Remove** next to your training job.

1. Choose **Yes, I want to remove <name of your training job>**.

1. Choose **Done**.

# Update training job details (Studio)
<a name="model-registry-details-studio-training-update"></a>

Complete the following steps to update the details of a training job, created externally or with SageMaker AI, associated with your model.

**To update (and view) details related to the training job:**

1. On the **Train** tab, view the status of the training job. The status is `Complete` if you added a training job to your model package and `Undefined` if not.

1. To view details related to your training job such as performance, hyperparameters, and identifying details, choose the **Train** tab.

1. To update and view details related to model performance, complete the following steps.

   1. Choose **Performance** in the left sidebar of the **Train** tab.

   1. View **Metrics** related to your training job. The **Performance** page lists metrics by name, value, and any notes you added related to the metric.

   1. (Optional) To add notes to existing metrics, complete the following steps.

      1. Choose the vertical ellipsis in the top right corner of the model version page, and choose **Edit**.

      1. Add notes to any of the listed metrics.

      1. At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

   1. View **Custom Metrics** related to your training job. Custom metrics are formatted similarly to metrics.

   1. (Optional) To add custom metrics, complete the following steps.

      1. Choose **Add**.

      1. Insert a name, value, and any optional notes for your new metric.

   1. (Optional) To remove custom metrics, choose the **Trash** icon next to the metric you want to remove.

   1. In the **Observations** text box, view any notes you added related to the performance of your training job.

   1. (Optional) To add or update observations, complete the following steps.

      1. Choose the vertical ellipsis in the top right corner of the model version page, and choose **Edit**.

      1. Add or update your notes in the **Observations** text box.

      1. At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

1. To update and view details related to model artifacts, complete the following steps.

   1. Choose **Artifacts** in the left sidebar of the **Train** tab.

   1. In the **Location (S3 URI)** field, view the Amazon S3 location of your training datasets.

   1. In the **Models** field, view the name and Amazon S3 locations of model artifacts from other models that you included in the training job.

   1. To update any of the fields in the **Artifacts** page, complete the following steps.

      1. Choose the vertical ellipsis in the top right of the model version page, and choose **Edit**.

      1. Enter new values in any of the fields.

      1. At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

1. To update and view details related to hyperparameters, complete the following steps.

   1. Choose **Hyperparameters** in the left sidebar of the **Train** tab.

   1. View the SageMaker AI provided and custom hyperparameters defined. Each hyperparameter is listed with its name and value.

   1. View the custom hyperparameters you added.

   1. (Optional) To add an additional custom hyperparameter, complete the following steps.

      1. Above the top right corner of the **Custom Hyperparameters** table, choose **Add**. A pair of new blank fields appears.

      1. Enter the name and value of the new custom hyperparameter. These values are automatically saved.

   1. (Optional) To remove a custom hyperparameter, choose the **Trash** icon to the right of the hyperparameter.

1. To update and view details related to the training job environment, complete the following steps.

   1. Choose **Environment** in the left sidebar of the **Train** tab.

   1. View the Amazon ECR URI locations for any training job containers added by SageMaker AI (for a SageMaker training job) or by you (for a custom training job).

   1. (Optional) To add an additional training job container, choose **Add**, and then enter the URI of the new training container.

1. To update and view the training job name and the Amazon Resource Names (ARN) for the training job, complete the following steps.

   1. Choose **Details** in the left sidebar of the **Train** tab.

   1. View the training job name and ARN of the training job.

# Add an evaluation job (Studio)
<a name="model-registry-details-studio-evaluate"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the updated Studio experience. For information about using the Studio Classic application, see [Amazon SageMaker Studio Classic](studio.md).

After you register your model, you can test your model with one or more datasets to assess its performance. You can add one or more evaluation jobs from Amazon S3 or define your own evaluation job by manually entering all details. If you add a job from Amazon S3, SageMaker AI prepopulates the fields for all of the subpages in the **Evaluate** tab. If you define your own evaluation job, you need to add details related to your evaluation job manually.

**To add your first evaluation job to your model package, complete the following steps.**

1. Choose the **Evaluate** tab.

1. Choose **Add**.

1. You can add an evaluation job from Amazon S3 or a custom evaluation job.

   1. To add an evaluation job with collaterals from Amazon S3, complete the following steps.

      1. Choose **S3**.

      1. Enter a name for the evaluation job.

      1. Enter the Amazon S3 location to the output collaterals of your evaluation job.

      1. Choose **Add**.

   1. To add a custom evaluation job, complete the following step:

      1. Choose **Custom**.

      1. Enter a name for the evaluation job.

      1. Choose **Add**.

**To add an additional evaluation job to your model package, complete the following steps.**

1. Choose the **Evaluate** tab.

1. Choose the **Gear** ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/icons/Settings_squid.png)) icon under the **Train** tab.

1. In the dialog box, choose **Add**.

1. You can add an evaluation job from Amazon S3 or a custom evaluation job.

   1. To add an evaluation job with collaterals from Amazon S3, complete the following steps.

      1. Choose **S3**.

      1. Enter a name for the evaluation job.

      1. Enter the Amazon S3 location to the output collaterals of your evaluation job.

      1. Choose **Add**.

   1. To add a custom evaluation job, complete the following step:

      1. Choose **Custom**.

      1. Enter a name for the evaluation job.

      1. Choose **Add**.

# Remove an evaluation job (Studio)
<a name="model-registry-details-studio-evaluate-remove"></a>

You can remove an evaluation job, created externally or with SageMaker AI, from your model by completing the following steps.

**To remove an evaluation job from your model package, complete the following steps.**

1. Choose the **Evaluate** tab.

1. Choose the **Gear** ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/icons/Settings_squid.png)) icon under the **Train** tab.

1. (Optional) To find your evaluation job from the list, enter a search term in the search box to narrow the list of choices.

1. Choose the radio button next to your evaluation job.

1. Choose **Remove**.

1. Choose **Yes, I want to remove <name of your evaluation job>**.

1. Choose **Done**.

# Update an evaluation job (Studio)
<a name="model-registry-details-studio-evaluate-update"></a>

Complete the following steps to update the details of an evaluation job, created externally or with SageMaker AI, associated with your model.

**To update (and view) details related to the evaluation job:**

1. On the **Evaluate** tab, view the status of the evaluation job. The status is `Complete` if you added an evaluation job to your model package and `Undefined` if not.

1. To view details related to your evaluation job, such as performance and artifacts location, choose the **Evaluate** tab.

1. To update and view details related to model performance during evaluation, complete the following steps.

   1. Choose **Performance** in the **Evaluate** tab sidebar.

   1. View metrics related to your evaluation job in the **Metrics** list. The **Metrics** list displays the individual metrics by name, value, and any notes you added related to the metric.

   1. In the **Observations** text box, view any notes you added related to the performance of your evaluation job.

   1. To update any of the **Notes** fields for any metric or the **Observations** field, complete the following steps.

      1. Choose the vertical ellipsis in the top right of the model version page, and choose **Edit**.

      1. Enter notes for any metric or in the **Observations** text box.

      1. At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

1. To update and view details related to your evaluation job datasets, complete the following steps.

   1. Choose **Artifacts** in the left sidebar of the **Evaluate** page.

   1. View datasets used in your evaluation job.

   1. (Optional) To add a dataset, choose **Add** and enter an Amazon S3 URI to the dataset.

   1. (Optional) To remove a dataset, choose the **Trash** icon next to the dataset you want to remove.

1. To view the job name and evaluation job ARN, choose **Details**.

# Update audit (governance) information (Studio)
<a name="model-registry-details-studio-audit"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the updated Studio experience. For information about using the Studio Classic application, see [Amazon SageMaker Studio Classic](studio.md).

Document important model details to help your organization establish a robust framework of model governance. You and your team members can reference these details so they use the model for the appropriate use cases, know the business domain and owners of the model, and understand model risks. You can also save details about how the model is expected to perform and reasons for performance limitations.

**To view or update details related to the model governance, complete the following steps.**

1. On the **Audit** tab, view the approval status of the model card. The status can be one the following:
   + **Draft**: The model card is still a draft.
   + **Pending approval**: The model card is waiting to be approved.
   + **Approved**: The model card is approved.

1. To update the approval status of the model card, choose the pulldown menu next to the approval status and choose the updated approval status.

1. To update and view details related to your model package risk, complete the following steps.

   1. Choose **Risk** in the left sidebar of the **Audit** tab.

   1. View the current risk rating and explanation for the risk rating.

   1. To update the rating or explanation, complete the following steps.

      1. Choose the vertical ellipsis at the top right corner of the **Audit** page, and choose **Edit**.

      1. (Optional) Choose an updated risk rating.

      1. (Optional) Update the risk rating explanation.

      1.  At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

1. To update and view details related to the usage of your model package, complete the following steps.

   1. Choose **Usage** in the left sidebar of the **Audit** tab.

   1. View text you added in the following fields:
      + **Problem type**: The category of machine learning algorithm used to build your model.
      + **Algorithm type**: The specific algorithm used to create your model.
      + **Intended uses**: The current application of the model in your business problem.
      + **Factors affecting model efficacy**: Notes about your model’s performance limitations.
      + **Recommended use**: The types of applications you can create with the model, the scenarios in which you can expect a reasonable performance, or the type of data to use with the model.
      + **Ethical considerations**: A description of how your model might discriminate based on factors such as age or gender.

   1. To update any of the previously listed fields, complete the following steps.

      1. Choose the vertical ellipsis at the top right corner of the model version page, and choose **Edit**.

      1. (Optional) Use the dropdown menus for **Problem type** and **Algorithm type** to select new values, if needed.

      1. (Optional) Update the text descriptions in the remaining fields.

      1.  At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

1. To update and view details related to the stakeholders of your model package, complete the following steps.

   1. Choose **Stakeholders** in the left sidebar of the **Audit** tab.

   1. View the current model owner and creator, if any.

   1. To update the model owner or creator, complete the following steps:

      1. Choose the vertical ellipsis at the top right corner of the model version page, and choose **Edit**.

      1. Update the model owner or model creator fields.

      1.  At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

1. To update and view details related to the business problem that your model package addresses, complete the following steps.

   1. Choose **Business** in the left sidebar of the **Audit** tab.

   1. View the current descriptions, if any, for the business problem that the model addresses, the business problem stakeholders, and the line of business.

   1. To update any of the fields in the **Business** tab, complete the following steps.

      1. Choose the vertical ellipsis at the top right corner of the model version page, and choose **Edit**.

      1. Update the descriptions in any of the fields.

      1.  At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

1. To update and view existing documentation (represented as key-value pairs) for your model, complete the following steps.

   1. Choose **Documentation** in the left sidebar of the **Audit** page.

   1. View existing key-value pairs.

   1. To add any key-value pairs, complete the following steps.

      1. Choose the vertical ellipsis at the top right corner of the model version page, and choose **Edit**.

      1. Choose **Add**.

      1. Enter a new key and associated value.

      1.  At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

   1. To remove any key-value pairs, complete the following steps.

      1. Choose the vertical ellipsis at the top right corner of the model version page, and choose **Edit**.

      1. Choose the **Trash** icon next to the key-value pair to remove.

      1.  At the top of the model version page, choose **Save** in the **Editing Model Version...** banner.

# Update deployment information (Studio)
<a name="model-registry-details-studio-deploy"></a>

**Important**  
As of November 30, 2023, the previous Amazon SageMaker Studio experience is now named Amazon SageMaker Studio Classic. The following section is specific to using the updated Studio experience. For information about using the Studio Classic application, see [Amazon SageMaker Studio Classic](studio.md).

After you evaluate your model performance and determine that it is ready to use for production workloads, you can change the approval status of the model to initiate CI/CD deployment. For more about approval status definitions, see [Update the Approval Status of a Model](model-registry-approve.md).

**To view or update details related to the model package deployment, complete the following steps.**

1. On the **Deploy** tab, view the model package approval status. Possible values can be the following:
   + **Pending Approval**: The model is registered but not yet approved or rejected for deployment.
   + **Approved**: The model is approved for CI/CD deployment. If there is an EventBridge rule in place that initiates model deployment upon a model approval event, as is the case for a model built from a SageMaker AI project template, SageMaker AI also deploys the model.
   + **Rejected**: The model is rejected for deployment.

   If you need to change the approval status, choose the dropdown menu next to the status and choose the updated status.

1. To update the model package approval status, choose the dropdown next to the approval status and choose the updated approval status.

1. In the **Containers** list, view the inference image containers.

1. In the **Instances** list, view the instances which compose your deployment endpoint.

# Compare Model Versions
<a name="model-registry-version-compare"></a>

As you generate model versions, you might want to compare models versions by viewing relevant model quality metrics side-by-side. For example, you might want to track accuracy by comparing mean squared error (MSE) values, or you might decide to remove models that perform poorly on selected measures. The following procedure shows you how to set up model version comparison in Model Registry using the Amazon SageMaker Studio Classic console.

## Compare Model Versions (Amazon SageMaker Studio Classic)
<a name="model-registry-version-compare-studio"></a>

**Note**  
You can only compare model versions the Amazon SageMaker Studio Classic console.

To compare model versions within a model group, complete the following steps:

1. Sign in to Studio Classic. For more information, see [Amazon SageMaker AI domain overview](gs-studio-onboard.md).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the model groups list, select the name of the Model Group you want to view. A new tab opens with a list of the model versions in the Model Group.

1. In the list of model versions, check the boxes next to the model versions you want to compare.

1. Choose the **Actions** dropdown menu, then choose **Compare**. A listing of model quality metrics appears for your selected models.

# View and Manage Model Group and Model Version Tags
<a name="model-registry-tags"></a>

Model Registry helps you view and manage tags related to your model groups. You can use tags to categorize model groups by purpose, owner, environment, or other criteria. The following instructions show you how to view, add, delete, and edit your tags in the Amazon SageMaker Studio console.

**Note**  
Model packages in the SageMaker Model Registry do not support tags—these are versioned model packages. Instead, you can add key value pairs using `CustomerMetadataProperties`. Model package groups in the model registry support tagging. 

## View and manage model group tags
<a name="model-registry-tags-model-group"></a>

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

**To view a model group tag, complete the following steps:**

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** to display a list of your model groups.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the Model Groups list, select the name of the Model Group you want to view.

1. In the model group page, choose the **Tags** tab. View the tags associated with your model group.

**To add a model group tag, complete the following steps:**

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** to display a list of your model groups.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the Model Groups list, select the name of the Model Group you want to edit.

1. In the model group page, choose the **Tags** tab.

1. Choose **Add/Edit tags**.

1. Above **\$1 Add new tag**, enter your new key in the blank **Key** field.

1. (Optional) Enter your new value in the blank **Value** field.

1. Choose **Confirm changes**.

1. Confirm your new tag appears in the **Tags** section of the **Information** page.

**To delete a model group tag, complete the following steps:**

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** to display a list of your model groups.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the Model Groups list, select the name of the Model Group you want to edit.

1. In the model group page, choose the **Tags** tab.

1. Choose **Add/Edit tags**.

1. Choose the **Trash** icon next to the key-value pair you want to remove.

1. Choose **Confirm changes**.

**To edit a model group tag, complete the following steps:**

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** to display a list of your model groups.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the Model Groups list, select the name of the Model Group you want to edit.

1. In the model group page, choose the **Tags** tab.

1. Choose **Add/Edit tags**.

1. Enter a new value in the **Value** field of the key-pair you want to edit.

1. Choose **Confirm changes**.

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

**To view a model group tag, complete the following steps:**

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the Model Groups list, select the name of the Model Group you want to edit.

1. Choose **Information**.

1. View your tags in the **Tags** section of the **Information** page.

**To add a model group tag, complete the following steps:**

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Amazon SageMaker AI domain overview](gs-studio-onboard.md).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the Model Groups list, select the name of the Model Group you want to edit.

1. Choose **Information**.

1. If you don't have any tags, choose **Add tags**.

1. If you have pre-existing tags, choose **Manage tags** in the **Tags** section. A list of the model group's tags appears as key-value pairs.

1. Above **Add new tag**, enter your new key in the blank **Key** field.

1. (Optional) Enter your new value in the blank **Value** field.

1. Choose **Confirm changes**.

1. Confirm your new tag appears in the **Tags** section of the **Information** page.

**To delete a model group tag, complete the following steps:**

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Amazon SageMaker AI domain overview](gs-studio-onboard.md).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the Model Groups list, select the name of the Model Group you want to edit.

1. Choose **Information**.

1. In the **Tags** section, choose **Manage tags**. A list of the model group's tags appears as key-value pairs.

1. Choose the **Trash** icon to the right of the tag you want to remove.

1. Choose **Confirm changes**.

1. Confirm your removed tag does not appear in the **Tags** section of the **Information** page.

**To edit a model group tag, complete the following steps:**

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Amazon SageMaker AI domain overview](gs-studio-onboard.md).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the Model Groups list, select the name of the Model Group you want to edit.

1. Choose **Information**.

1. In the **Tags** section, choose **Manage tags**. A list of the model group's tags appears as key-value pairs.

1. Edit any key or value.

1. Choose **Confirm changes**.

1. Confirm your tag contains your edits in the **Tags** section of the **Information** page.

**To assign or tag model groups to a project, complete the following steps:**

1. Get tags with key `sagemaker:project-name` and `sagemaker:project-id` for the SageMaker AI project using the [ListTags](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ListTags.html) API.

1. To apply the tags to your model package group, choose one of the following methods:
   + If you create a new model package group and want to add tags, pass your tags from Step 1 to the [CreateModelPackageGroup](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackageGroup.html) API.
   + If you want to add tags to an existing model package group, use the [AddTags](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AddTags.html) APIs.
   + If you create your model package group through Pipelines, use the `pipeline.create()` or `pipeline.upsert()` methods, or pass your tags to the [RegisterModel](https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html#step-type-register-model) step.

------

# Delete a Model Version
<a name="model-registry-delete-model-version"></a>

This procedure demonstrates how to delete a model version in the Amazon SageMaker Studio console.

## Delete a Model Version (Studio or Studio Classic)
<a name="model-registry-delete-model-version-studio"></a>

To delete a model version in the Amazon SageMaker Studio console, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** to display a list of your model groups.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the model groups list, choose the angle bracket to the left of the model group that you want to view.

1. A list of the model versions in the model group appears. If you don't see the model version that you want to delete, choose **View all**.

1. Select the check boxes next to the model versions that you want to delete.

1. Choose the vertical ellipsis above the top right corner of the table, and choose **Delete** (or **Delete model version** if you are in the model group details page).

1. In the **Delete model version** dialog box, choose **Yes, delete the model version**.

1. Choose **Delete**.

1. Confirm that your deleted model versions no longer appear in the model group.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**. A list of your Model Groups appears.

1. From the model groups list, select the name of the Model Group of the model version that you want to delete.

1. From the list of model versions, select the name of the model version that you want to delete.

1. Choose the **Actions** dropdown menu, and choose **Remove**.

1. In the confirmation dialog box, enter `REMOVE`.

1. Choose **Remove**.

1. Confirm the model version you removed does not appear in the list of the model group’s model versions.

------

# Staging Construct for your Model Lifecycle
<a name="model-registry-staging-construct"></a>

You can define a series of stages that models can progress through for your model workflows and lifecycle with the Model Registry staging construct. This simplifies tracking and managing models as they transition through development, testing, and production stages. The following will provide information on staging constructs and how to use them in your model governance.

The stage construct allows you to define a series of stages and statuses that models progress through. At each stage, specific personas with the relevant permissions can update the stage status. As a model advances through the stages, its metadata is carried forward, providing a comprehensive view of the model's lifecycle. This metadata can be accessed and reviewed by authorized personas at each stage, enabling informed decision making. This includes the following benefits.
+ Model Life Cycle Permissions - Set permissions for designated personas to update a model stage state and enforce approval gates at critical transition points. Administrators can assign permission by using IAM policies and condition keys with the API. For example, you can restrict you data scientist from updating the Model Lifecycle stage transition from "Development" to "Production". For examples, see [Set up Staging Construct Examples](model-registry-staging-construct-set-up.md).
+ Model Life Cycle Events via Amazon EventBridge - You can consume the lifecycle stage events using EventBridge. This sets you up to receive event notifications when models change approval or staging state, enabling integration with third-party governance tools. See [Get event notifications for ModelLifeCycle](model-registry-staging-construct-event-bridge.md) for an example.
+ Search based on Model Life Cycle Fields - You can search and filter stage and stage status using the [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Search.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Search.html) API.
+ Audit Trails for Model Life Cycle Events - You can view the history of model approval and staging events for the model lifecycle transitions.

The following topics will walk you through how to set up a stage construct on the administrator side and how to update a stage status from the user side.

**Topics**
+ [Set up Staging Construct Examples](model-registry-staging-construct-set-up.md)
+ [Update a model package stage and status in Studio](model-registry-staging-construct-update-studio.md)
+ [Update a model package stage and status example (boto3)](model-registry-staging-construct-update-boto3.md)
+ [Invoke ModelLifeCycle using the AWS CLI examples](model-registry-staging-construct-cli.md)
+ [Get event notifications for ModelLifeCycle](model-registry-staging-construct-event-bridge.md)

# Set up Staging Construct Examples
<a name="model-registry-staging-construct-set-up"></a>

To set up stage constructs for your Amazon SageMaker Model Registry, the administrator will need to grant the relevant permissions to the intended roles. The following provides examples on how to set up stage constructs for various roles.

**Note**  
Users within a Amazon SageMaker AI domain will be able to view all stages defined within the domain, but can only use the ones they have permissions for.

Stages are defined by the `ModelLifeCycle` parameter and have the following structure. The administrator sets up the permissions for which `stage` and `stageStatus` can be accessed by which roles. The users assuming a role can use the relevant `stage` and `stageStatus` and include their own `stageDescription`.

```
ModelLifeCycle {
    stage: String # Required (e.g., Development/QA/Production)
    stageStatus: String # Required (e.g., PendingApproval/Approved/Rejected)  
    stageDescription: String # Optional
}
```

The following table contains Model Registry pre-defined stage construct templates. You can define your own stage constructs based on your use cases. The relevant permissions will need to be set up before users can use them.


| Stage | Stage status | 
| --- | --- | 
|  Proposal  |  PendingApproval  | 
|  Development  |  InProgress  | 
|  QA  |  OnHold  | 
|  PreProduction  |  Approved  | 
|  Production  |  Rejected  | 
|  Archived  |  Retired  | 

The `ModelLifeCycle` parameter can be invoked by the following APIs:
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html)
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateModelPackage.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateModelPackage.html)
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeModelPackage.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeModelPackage.html)

------
#### [ Policy for a data scientist role ]

The following is an example IAM policy using model lifecycle condition keys. You can modify them based on your own requirements. In this example, the role’s permissions are limited to set or define the model lifecycle stage to:
+ Create or update a model with the stage `"Development"` and status `"Approved"`.
+ Update a model package with the stage quality assurance, `"QA"`, and status `"PendingApproval"`.

```
{
    "Action" : [
        "sagemaker:UpdateModelPackage",
        "sagemaker:CreateModelPackage"
    ],
    "Resource": [
        "*"
    ],
    "Condition": {
        "StringEquals": {
            "sagemaker:ModelLifeCycle:stage" : "Development"
            "sagemaker:ModelLifeCycle:stageStatus" : "Approved"       
        }
    }
},
{
    "Action" : [
        "sagemaker:UpdateModelPackage"
    ],
    "Resource": [
        "*"
    ],
    "Condition": {
        "StringEquals": {
            "sagemaker:ModelLifeCycle:stage" : "Staging"
            "sagemaker:ModelLifeCycle:stageStatus" : "PendingApproval"       
        }
    }
}
```

------
#### [ Policy for a quality assurance specialist ]

The following is an example IAM policy using model lifecycle condition keys. You can modify them based on your own requirements. In this example, the role’s permissions are limited to set or define the model lifecycle stage to:
+ Update a model package with:
  + The stage `"QA"` and status `"Approved"` or `"Rejected"`.
  + The stage `"Production"` and status `"PendingApproval"`.

```
{
    "Action": [
        "sagemaker:UpdateModelPackage"
    ],
    "Resource": [
        "*"
    ],
    "Condition": {
        "StringEquals": {
            "sagemaker:ModelLifeCycle:stage": "Staging",
            "sagemaker:ModelLifeCycle:stageStatus": "Approved"
        }
    }
}, {
    "Action": [
        "sagemaker:UpdateModelPackage"
    ],
    "Resource": [
        "*"
    ],
    "Condition": {
        "StringEquals": {
            "sagemaker:ModelLifeCycle:stage": "Staging",
            "sagemaker:ModelLifeCycle:stageStatus": "Rejected"
        }
    }
}, {
    "Action": [
        "sagemaker:UpdateModelPackage"
    ],
    "Resource": [
        "*"
    ],
    "Condition": {
        "StringEquals": {
            "sagemaker:ModelLifeCycle:stage": "Production",
            "sagemaker:ModelLifeCycle:stageStatus": "PendingApproval"
        }
    }
}
```

------
#### [ Policy for lead engineer role ]

The following is an example IAM policy using model lifecycle condition keys. You can modify them based on your own requirements. In this example, the role’s permissions are limited to set or define the model lifecycle stage to:
+ Update a model package with:
  + The stage `"Production"` and status `"Approved"` or `"Rejected"`.
  + The stage `"Development"` and status `"PendingApproval"`.

```
{
    "Action" : [
        "sagemaker:UpdateModelPackage"
    ],
    "Resource": [
        "*"
    ],
    "Condition": {
        "ForAnyvalue:StringEquals" : {
            "sagemaker:ModelLifeCycle:stage" : "Production",
            "sagemaker:ModelLifeCycle:stageStatus" : "Approved"
        }
    }
},
{
    "Action" : [
        "sagemaker:UpdateModelPackage"
    ],
    "Resource": [
        "*"
    ],
    "Condition": {
        "StringEquals:" {
            "sagemaker:ModelLifeCycle:stage" : "Production"
            "sagemaker:ModelLifeCycle:stageStatus" : "Rejected"
        }
    }
},
{
    "Action" : [
        "sagemaker:UpdateModelPackage"
    ],
    "Resource": [
        "*"
    ],
    "Condition": {
        "StringEquals": {
            "sagemaker:ModelLifeCycle:stage" : "Development"
            "sagemaker:ModelLifeCycle:stageStatus" : "PendingApproval"
        }
    }
}
```

------

To get Amazon EventBridge notifications on any model status update, see the example in [Get event notifications for ModelLifeCycle](model-registry-staging-construct-event-bridge.md). For an example EventBridge payload you may receive, see [SageMaker model package state change](automating-sagemaker-with-eventbridge.md#eventbridge-model-package).

# Update a model package stage and status in Studio
<a name="model-registry-staging-construct-update-studio"></a>

To use a model package stage construct, you will need to assume an execution role with the relevant permissions. The following page provides information on how to update the stage status using Amazon SageMaker Studio.

All stage constructs defined in the domain will be viewable by all users. To update a stage, you will need have the administrator set up the relevant permissions for you to access it. For information on how, see [Set up Staging Construct Examples](model-registry-staging-construct-set-up.md). 

The following procedure will take you to the Studio UI where you can update your model package stage.

1. Sign in to Amazon SageMaker Studio. For more information, see [Launch Amazon SageMaker Studio](studio-updated-launch.md).

1. In the left navigation pane, choose the **Models**.

1. Find your model.
   + You can use the tabs to find your models. For example, choose the **Registered models** or **Deployable models** tabs.
   + You can use the **My models** and **Shared with me** options to find models you created or ones that are shared by you.

1. Select the checkbox next to the model you wish to update.

1. Choose the **More options** icon. 

1. Choose **Update model lifecycle**. This will take you to the **Update model lifecycle** section.

1. Complete the tasks to update the stage. 

   If you cannot update the stage, you will receive an error. Your administrator will need to set up the permissions for you to do so. For information on how to set up the permissions, see [Set up Staging Construct Examples](model-registry-staging-construct-set-up.md).

# Update a model package stage and status example (boto3)
<a name="model-registry-staging-construct-update-boto3"></a>

To update a model package stage and status, you will need to assume an execution role with the relevant permissions. The following provides an example on how you can update the stage status using the [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateModelPackage.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateModelPackage.html) API using AWS SDK for Python (Boto3).

In this example, the `ModelLifeCycle` stage `"Development"` and stage status `"Approved"` condition keys for the [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateModelPackage.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateModelPackage.html) API action has been granted to the your execution role. You can include a description in `stage-description`. See [Set up Staging Construct Examples](model-registry-staging-construct-set-up.md) for more information. 

```
from sagemaker import get_execution_role, session 
import boto3 

region = boto3.Session().region_name role = get_execution_role() 
sm_client = boto3.client('sagemaker', region_name=region)

model_package_update_input_dict = {
    "ModelLifeCycle" : { 
        "stage" : "Development",
        "stageStatus" : "Approved",
        "stageDescription" : "stage-description"
    }
} 
model_package_update_response = sm_client.update_model_package(**model_package_update_input_dict)
```

# Invoke ModelLifeCycle using the AWS CLI examples
<a name="model-registry-staging-construct-cli"></a>

You can use the AWS CLI tool to manage your AWS resources. A few AWS CLI commands include [search](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudsearchdomain/search.html) and [list-actions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/list-actions.html). The following page will provide examples on how to use `ModelPackage` while using these commands. For information and examples on setting up your stage construct, see [Set up Staging Construct Examples](model-registry-staging-construct-set-up.md).

The examples on this page uses the following variables.
+ `region` is the region that your model package exists in.
+ `stage-name` is the name of your defined stage.
+ `stage-status` is the name of your defined stage status.

The following are example AWS CLI commands using ModelLifeCycle.

Search for your model packages with a *stage-name* you have already defined.

```
aws sagemaker search --region 'region' --resource ModelPackage --search-expression '{"Filters": [{"Name": "ModelLifeCycle.Stage","Value": "stage-name"}]}'
```

List the actions associated with `ModelLifeCycle`.

```
aws sagemaker list-actions --region 'region' --action-type ModelLifeCycle
```

Create a model package with ModelLifeCycle.

```
aws sagemaker create-model-package --model-package-group-name 'model-package-group-name' --source-uri 'source-uri' --region 'region' --model-life-cycle '{"Stage":"stage-name", "StageStatus":"stage-status", "StageDescription":"Your Staging Comment"}' 
```

Update a model package with ModelLifeCycle.

```
aws sagemaker update-model-package --model-package 'model-package-arn' --region 'region' --model-life-cycle '{"Stage":"stage-name", "StageStatus":"stage-status"}' 
```

Search via the ModelLifeCycle field.

```
aws sagemaker search --region 'region' --resource ModelPackage --search-expression '{"Filters": [{"Name": "ModelLifeCycle.Stage","Value": "stage-name"}]}'
```

Fetch audit records for ModelLifeField updates via [Amazon SageMaker ML Lineage Tracking](lineage-tracking.md) APIs.

```
aws sagemaker list-actions --region 'region' --action-type ModelLifeCycle
```

```
aws sagemaker describe-action --region 'region' --action-name 'action-arn or action-name'
```

# Get event notifications for ModelLifeCycle
<a name="model-registry-staging-construct-event-bridge"></a>

You can get the ModelLifeCycle update notifications and events with EventBridge in your account. The following is an example of an EventBridge rule, to be configured in your account, in order to get the ModelLifeCycle event notifications.

```
{
  "source": ["aws.sagemaker"],
  "detail-type": ["SageMaker Model Package State Change"]
}
```

For an example EventBridge payload you may receive, see [SageMaker model package state change](automating-sagemaker-with-eventbridge.md#eventbridge-model-package).

# Update the Approval Status of a Model
<a name="model-registry-approve"></a>

After you create a model version, you typically want to evaluate its performance before you deploy it to a production endpoint. If it performs to your requirements, you can update the approval status of the model version to `Approved`. Setting the status to `Approved` can initiate CI/CD deployment for the model. If the model version does not perform to your requirements, you can update the approval status to `Rejected`.

You can manually update the approval status of a model version after you register it, or you can create a condition step to evaluate the model when you create a SageMaker AI pipeline. For information about creating a condition step in a SageMaker AI pipeline, see [Pipelines steps](build-and-manage-steps.md).

When you use one of the SageMaker AI provided project templates and the approval status of a model version changes, the following action occurs. Only valid transitions are shown.
+ `PendingManualApproval` to `Approved` – initiates CI/CD deployment for the approved model version
+ `PendingManualApproval` to `Rejected` – No action
+ `Rejected` to `Approved` – initiates CI/CD deployment for the approved model version
+ `Approved` to `Rejected` – initiates CI/CD to deploy the latest model version with an `Approved` status

You can update the approval status of a model version by using the AWS SDK for Python (Boto3) or by using the Amazon SageMaker Studio console. You can also update the approval status of a model version as part of a condition step in a SageMaker AI pipeline. For information about using a model approval step in a SageMaker AI pipeline, see [Pipelines overview](pipelines-overview.md).

## Update the Approval Status of a Model (Boto3)
<a name="model-registry-approve-api"></a>

When you created the model version in [Register a Model Version](model-registry-version.md), you set the `ModelApprovalStatus` to `PendingManualApproval`. You update the approval status for the model by calling `update_model_package`. Note that you can automate this process by writing code that, for example, sets the approval status of a model depending on the result of an evaluation of some measure of the model's performance. You can also create a step in a pipeline that automatically deploys a new model version when it is approved. The following code snippet shows how to manually change the approval status to `Approved`.

```
model_package_update_input_dict = {
    "ModelPackageArn" : model_package_arn,
    "ModelApprovalStatus" : "Approved"
}
model_package_update_response = sm_client.update_model_package(**model_package_update_input_dict)
```

## Update the Approval Status of a Model (Studio or Studio Classic)
<a name="model-registry-approve-studio"></a>

To manually change the approval status in the Amazon SageMaker Studio console, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose the **Models** to display a list of your model groups.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the model groups list, choose the angle bracket to the left of the model group that you want to view.

1. A list of the model versions in the model group appears. If you don't see the model version that you want to delete, choose **View all** to display the complete list of model versions in the model group details page.

1. Select the name of the model version that you want to update.

1. The **Deploy** tab displays the current approval status. Choose the dropdown menu next to the current approval status and select the updated approval status.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the model groups list, select the name of the Model Group that you want to view. A new tab opens with a list of the model versions in the Model Group.

1. In the list of model versions, select the name of the model version that you want to update.

1. Under the **Actions** dropdown menu, you can choose one of two possible menu options to update the model version status.
   + Using the **Update Status** option

     1. Under the **Actions** dropdown menu, choose the **Update Status** dropdown menu, and choose the new model version status.

     1. (Optional) In the **Comment** field, add additional details.

     1. Choose **Save and Update**.
   + Using the **Edit** option

     1. Under the **Actions** dropdown menu, choose **Edit**.

     1. (Optional) In the **Comment** field, add additional details.

     1. Choose **Save changes**.

1. Confirm the model version status is updated to the correct value in the model version page.

------

For `us-east-1`, `us-west-2`, `ap-northeast-1`, and `eu-west-1` regions, you can use the following instructions to access the lineage details for logged and registered model versions:

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. Choose **Models** from the left navigation pane.

1. Choose the Logged **models** tab, if not selected already, then select **Registered Models**.

1. Select a model and choose **View Latest Version**.

1. Choose the **Governance** tab.

1. The **Deploy** section under **Governance overview** displays the current approval status. Select the updated approval status from the dropdown menu.

# Deploy a Model from the Registry with Python
<a name="model-registry-deploy"></a>

After you register a model version and approve it for deployment, deploy it to a SageMaker AI endpoint for real-time inference. You can deploy your model by using the SageMaker AI SDK or the AWS SDK for Python (Boto3).

When you create a machine learning operations (MLOps) project and choose an MLOps project template that includes model deployment, approved model versions in the Model Registry are automatically deployed to production. For information about using SageMaker AI MLOps projects, see [MLOps Automation With SageMaker Projects](sagemaker-projects.md).

You can also enable an AWS account to deploy model versions that were created in a different account by adding a cross-account resource policy. For example, one team in your organization might be responsible for training models, and a different team is responsible for deploying and updating models.

**Topics**
+ [Deploy a Model from the Registry (SageMaker SDK)](#model-registry-deploy-smsdk)
+ [Deploy a Model from the Registry (Boto3)](#model-registry-deploy-api)
+ [Deploy a Model Version from a Different Account](#model-registry-deploy-xaccount)

## Deploy a Model from the Registry (SageMaker SDK)
<a name="model-registry-deploy-smsdk"></a>

To deploy a model version using the [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) use the following code snippet:

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

## Deploy a Model from the Registry (Boto3)
<a name="model-registry-deploy-api"></a>

To deploy a model version using the AWS SDK for Python (Boto3), complete the following steps:

1. The following code snippet assumes you already created the SageMaker AI Boto3 client `sm_client` and a model version whose ARN is stored in the variable `model_version_arn`.

   Create a model object from the model version by calling the [create\$1model](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_model) API operation. Pass the Amazon Resource Name (ARN) of the model version as part of the `Containers` for the model object:

   ```
   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 an endpoint configuration by calling `create_endpoint_config`. The endpoint configuration specifies the number and type of Amazon EC2 instances to use for the endpoint.

   ```
   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 the endpoint by calling `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'])
   ```

## Deploy a Model Version from a Different Account
<a name="model-registry-deploy-xaccount"></a>

You can permit an AWS account to deploy model versions that were created in a different account by adding a cross-account resource policy. For example, one team in your organization might be responsible for training models, and a different team is responsible for deploying and updating models. When you create these resource policies, you apply the policy to the specific resource to which you want to grant access. For more information about cross-account resource policies in AWS, see [Cross-account policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic-cross-account.html) in the *AWS Identity and Access Management User Guide*.

**Note**  
You must use a KMS key to encrypt the [output data config](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_OutputDataConfig.html) action during training for cross-account model deployment.

To enable cross-account model deployment in SageMaker AI, you have to provide a cross-account resource policy for the Model Group that contains the model versions you want to deploy, the Amazon ECR repository where the inference image for the Model Group resides, and the Amazon S3 bucket where the model versions are stored.

To be able to deploy a model that was created in a different account, you must have a role that has access to SageMaker AI actions, such as a role with the `AmazonSageMakerFullAccess` managed policy. For information about SageMaker AI managed policies, see [AWS managed policies for Amazon SageMaker AI](security-iam-awsmanpol.md).

The following example creates cross-account policies for all three of these resources, and applies the policies to the resources. The example also assumes that you previously defined the following variables:
+ `bucket` – The Amazon S3 bucket where the model versions are stored.
+ `kms_key_id` – The KMS key used to encrypt the training output.
+ `sm_client` – A SageMaker AI Boto3 client.
+ `model_package_group_name` – The Model Group to which you want to grant cross-account access.
+ `model_package_group_arn` – The Model Group ARN to which you want to grant cross-account access.

```
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.")
```

# Deploy a Model in Studio
<a name="model-registry-deploy-studio"></a>

After you register a model version and approve it for deployment, deploy it to a Amazon SageMaker AI endpoint for real-time inference. You can [Deploy a Model from the Registry with Python](model-registry-deploy.md) or deploy your model in Amazon SageMaker Studio. The following provides instructions on how to deploy your model in Studio.

This feature is not available in Amazon SageMaker Studio Classic.
+ If Studio is your default experience, the UI is similar to the images found in [Amazon SageMaker Studio UI overview](studio-updated-ui.md).
+ If Studio Classic is your default experience, the UI is similar to the images found in [Amazon SageMaker Studio Classic UI Overview](studio-ui.md).

Before you can deploy a model package, the following requirements must be met for the model package:
+ A valid inference specification available. See [InferenceSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelPackage.html#sagemaker-CreateModelPackage-request-InferenceSpecification) for more information.
+ Model with approved status. See [Update the Approval Status of a Model](model-registry-approve.md) for more information.

The following provides instructions on how to deploy a model in Studio.

**To deploy a model in Studio**

1. Open the Studio console by following the instructions in [Launch Amazon SageMaker Studio](studio-updated-launch.md).

1. Choose **Models** from the left navigation pane.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. (Optional) If you have models that are shared with you, you can choose between **My models** or **Shared with me**.

1. Select the checkboxes for the registered models. If the above requirements are met, the **Deploy** button becomes available to choose.

1. Choose **Deploy** to open the **Deploy model to endpoint** page.

1. Configure the deployment resources in the **Endpoint settings**. 

1. Once you have verified the settings, choose **Deploy**. The model will then be deployed to the endpoint with the **In service** status.

For `us-east-1`, `us-west-2`, `ap-northeast-1`, and `eu-west-1` regions, you can use the following instructions to deploy models:

**To deploy a model in Studio**

1. Open the Studio console by following the instructions in [Launch Amazon SageMaker Studio](studio-updated-launch.md).

1. Choose **Models** from the left navigation pane.

1. Choose the **My models** tab.

1. Choose the Logged **models** tab, if not selected already.

1. Select a model and choose **View Latest Version**.

1. Choose **Deploy** and select between SageMaker AI or Amazon Bedrock.

1. Once you have verified the settings, choose **Deploy**. The model will then be deployed to the endpoint with the **In service** status.

# Cross-account discoverability
<a name="model-registry-ram"></a>

By exploring and accessing model package groups registered in other accounts, data scientists and data engineers can promote data consistency, streamline collaboration, and reduce duplication of effort. With Amazon SageMaker Model Registry, you can share model package groups across accounts. There are two categories of permissions associated with the sharing of resources:
+ **Discoverability**: *Discoverability* is the ability of the resource consumer account to see the model package groups shared by one or more resource owner accounts. Discoverability is only possible if the resource owner attaches the necessary resource policies to the shared model package groups. The resource consumer can view all shared model package groups in the AWS RAM UI and AWS CLI.
+ **Accessibility**: *Accessibility* is the ability of the resource consumer account to use the shared model package groups. For example, the resource consumer can register or deploy a model package from a different account if they have the necessary permissions.

**Topics**
+ [Share model group in Studio](model-registry-ram-studio-share.md)
+ [View shared model groups in Studio](model-registry-ram-studio-view.md)
+ [Accessibility](model-registry-ram-accessibility.md)
+ [Set up discoverability](model-registry-ram-discover.md)
+ [View shared model package groups](model-registry-ram-view-shared.md)
+ [Dissociate principals from a resource share and remove a resource share](model-registry-ram-dissociate.md)
+ [Promote the permission and resource share](model-registry-ram-promote.md)

# Share model group in Studio
<a name="model-registry-ram-studio-share"></a>

You can share your model groups with other AWS principals (AWS accounts or AWS Organizations) using the Studio UI. This streamlined sharing process enables cross-team collaboration, promotes best practices, and facilitates model reuse across your teams. The following will provide instructions on how to share model groups in Studio.

This feature is not available in Amazon SageMaker Studio Classic.
+ If Studio is your default experience, the UI is similar to the images found in [Amazon SageMaker Studio UI overview](studio-updated-ui.md).
+ If Studio Classic is your default experience, the UI is similar to the images found in [Amazon SageMaker Studio Classic UI Overview](studio-ui.md).

To share model groups you will first need to make sure that you have the following permission added to the execution role you a sharing the resources from.

1. [Get your execution role](sagemaker-roles.md#sagemaker-roles-get-execution-role).

1. [Update role permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_update-role-permissions.html) with the following:

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "ram:ListPermissions",
                   "ram:GetPermission",
                   "ram:GetResourceShareAssociations",
                   "ram:ListResourceSharePermissions",
                   "ram:DeleteResourceShare",
                   "ram:GetResourceShareInvitations",
                   "ram:AcceptResourceShareInvitation"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

------

The following provides instructions on how to share a model group with other AWS principals.

**To share a model group with other AWS principals**

1. Open the Studio console by following the instructions in [Launch Amazon SageMaker Studio](studio-updated-launch.md).

1. Choose **Models** from the left navigation pane.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. Select a registered model.

1. At the top right corner, choose **Share**. This will open the **Share model group** section.

   If you see an error message at the bottom of the screen, you will need add the appropriate permissions to your execution role. See the above permissions for more information.

1. Under **Resource shares**, choose a resource share to update or create a new resource share. 

1. Under **Managed permission**, choose a managed permission to control the level of access for your model. 

   The viewable options include permissions that have already been created for you or your custom made permissions in AWS RAM. See [Creating and using customer managed permissions](https://docs.aws.amazon.com/ram/latest/userguide/create-customer-managed-permissions.html) in the *AWS Resource Access Manager* User Guide.

1. Under **AWS principals**, input the AWS Organizations ARN or AWS account IDs you wish to share to and then choose **Add**. You can add multiple AWS principals this way.

1. When the minimum requirements are satisfied, the **Share** button becomes accessible. Once you have verified your settings, choose **Share**.

   A successful share will result in a green banner message at the bottom of the screen.

# View shared model groups in Studio
<a name="model-registry-ram-studio-view"></a>

You can view model groups that are shared with you or an account belonging to the same AWS Organizations. If a model group is shared with an account belonging to the same AWS Organizations, the shared model group will be automatically approved and available for you to view in Studio. Otherwise, you will need to approve the pending invitation before you can view the shared model group in Studio. The following will provide instructions on how to view shared model groups and accept model group share invitations in Studio.

This feature is not available in Amazon SageMaker Studio Classic.
+ If Studio is your default experience, the UI is similar to the images found in [Amazon SageMaker Studio UI overview](studio-updated-ui.md).
+ If Studio Classic is your default experience, the UI is similar to the images found in [Amazon SageMaker Studio Classic UI Overview](studio-ui.md).

The following provides instructions on how to view and accept model groups shared with you.

**View and accept model groups shared with you**

1. Open the Studio console by following the instructions in [Launch Amazon SageMaker Studio](studio-updated-launch.md).

1. Choose **Models** from the left navigation pane.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. Choose **Shared with me** to view the model groups that are shared with you.

1. To accept pending model group invitations:

   1. Choose **View pending approvals** to open the **Pending invitations** list.

   1. If you would like to accept the invitation, choose **Accept**.

# Accessibility
<a name="model-registry-ram-accessibility"></a>

If the resource consumer has access permissions to use a shared model package group, they can register or deploy a version of the model package group. For details about how the resource consumer can register a shared model package group, see [Register a Model Version from a Different Account](model-registry-version.md#model-registry-version-xaccount). For details about how the resource consumer can deploy a shared model package group, see [Deploy a Model Version from a Different Account](model-registry-deploy.md#model-registry-deploy-xaccount).

# Set up discoverability
<a name="model-registry-ram-discover"></a>

The resource owner can set up model package group discoverability by creating resource shares and attaching resource policies to the entities. For detailed steps about how to create a general resource share in AWS RAM, see [Create a resource share](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-sharing.html#getting-started-sharing-create) in the [AWS RAM](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html) documentation.

Complete the following instructions to set up model package group discoverability using the AWS RAM console or Model Registry Resource Policy APIs.

------
#### [ AWS CLI ]

1. Create a resource share in the model owner account.

   1. The model owner attaches a resource policy to the model package group using the SageMaker AI Resource Policy API [put-model-package-group-policy](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/put-model-package-group-policy.html), as demonstrated in the following command.

      ```
      aws sagemaker put-model-package-group-policy
      --model-package-group-name <model-package-group-name>
      --resource-policy "{\"Version\":\"2012-10-17\",		 	 	 \"Statement\":[{\"Sid\":
      \"ExampleResourcePolicy\",\"Effect\":\"Allow\",\"Principal\":<principal>,
      \"Action\":[\"sagemaker:DescribeModelPackage\",
      \"sagemaker:ListModelPackages\",\"sagemaker:DescribeModelPackageGroup\"],
      \"Resource\":[\"<model-package-group-arn>,\"
      \"arn:aws:sagemaker:<region>:<owner-account-id>:model-package/
      <model-package-group-name>/*\"]}]}"
      ```
**Note**  
Different combinations of actions can be attached to the resource policy. For custom policies, the permission created should be promoted by the model package group owner, and only entities with promoted permissions attached are discoverable. Unpromotable resource shares cannot be made discoverable or managed through AWS RAM.

   1. To check that AWS RAM created the resource share ARN, use the following command:

      ```
      aws ram get-resource-share-associations --association-type resource --resource-arn <model-package-group-arn>
      ```

      The response contains the *resource-share-arn* for the entity.

   1. To check if the attached policy permission is a managed or custom policy, use the following command:

      ```
      aws ram list-resource-share-permissions --resource-share-arn <resource-share-arn>
      ```

      The `featureSet` field can take values `CREATED_FROM_POLICY` or `STANDARD`, which are defined as follows:
      + `STANDARD`: The permission already exists.
      + `CREATED_FROM_POLICY`: The permission needs to be promoted in order for the entity to be discoverable. For more information, see [Promote the permission and resource share](model-registry-ram-promote.md).

1. Accept the resource share invitation in the model consumer account.

   1. The model package group consumer accepts the invitation for resource share. To see all resource invitations, run the following command:

      ```
      aws ram get-resource-share-invitations
      ```

      Identify the requests that have status `PENDING` and include the account ID of the owner account.

   1. Accept the resource share invitation from the model owner using the following command:

      ```
      aws ram accept-resource-share-invitation --resource-share-invitation-arn <resource-share-invitation-arn>
      ```

------
#### [ AWS RAM console ]

1. Log into the [AWS RAM console](https://console.aws.amazon.com/ram/home).

1. Complete the following steps to create a resource share from the model package group owner account.

   1. Complete the following steps to specify resource share details.

      1. In the **Name** field, add a unique name for your resource.

      1. In the **Resources** card, choose the dropdown menu and select **SageMaker AI Model Package Groups**.

      1. Select the check box of the ARN of the model package group resource share.

      1. In the **Select resources** card, select the check box of your model package group resource share.

      1. In the **Tags** card, add key-value pairs for tags to add to your resource share.

      1. Choose **Next**.

   1. Complete the following steps to associate managed permissions to the resource share.

      1. If you use a managed permission, choose a managed permission in the **Managed permissions** dropdown menu.

      1. If you use a custom permission, choose **Customer Managed Permission**. In this case, the model package group is not immediately discoverable. You have to promote the permission and the resource policy after you create the resource share. For information about how to promote permissions and resource shares, see [Promote the permission and resource share](model-registry-ram-promote.md). For more information about how to attach custom permissions, see [Creating and using customer managed permissions in AWS RAM](https://docs.aws.amazon.com/ram/latest/userguide/create-customer-managed-permissions.html).

      1. Choose **Next**.

   1. Complete the following steps to grant access to principals.

      1. Choose **Allow sharing with anyone** to allow sharing with accounts outside of your organization, or choose **Allow sharing only within your organization**.

      1. In the **Select principal type** dropdown menu, add the principal types and ID for the principals you want to add.

      1. Add and select the chosen principals for the share.

      1. Choose **Next**.

   1. Review the displayed share configuration and then choose **Create resource share**.

1. Accept the resource share invitation from the consumer account. Once the model owner creates the resource share and principal associations, the specified resource consumer accounts receive an invitation to join the resource share. The resource consumer accounts can view and accept the invitations in the [Shared with me: Resource shares](https://console.aws.amazon.com/ram/home#SharedResourceShares:) page in the AWS RAM console. For more information about accepting and viewing resources in AWS RAM, see [Access AWS resources shared with you](https://docs.aws.amazon.com//ram/latest/userguide/working-with-shared.html).

------

# View shared model package groups
<a name="model-registry-ram-view-shared"></a>

After the resource owner completes the previous steps to create a resource share and the consumer accepts the invitation for the share, the consumer can view the shared model package groups using the AWS CLI or in the AWS RAM console.

## AWS CLI
<a name="model-registry-ram-view-shared-cli"></a>

To view the model package groups shared, use the following command in the model consumer account:

```
aws sagemaker list-model-package-groups --cross-account-filter-option CrossAccount
```

## AWS RAM console
<a name="model-registry-ram-view-shared-ram"></a>

In the AWS RAM console, the resource owner and consumer can view shared model package groups. The resource owner can view the model package groups shared with the consumer by following the steps in [Viewing resource shares you created in AWS RAM](https://docs.aws.amazon.com/ram/latest/userguide/working-with-sharing-view-rs.html). The resource consumer can view the model package groups shared by the owner by following the steps in [Viewing resource shares shared with you](https://docs.aws.amazon.com/ram/latest/userguide/working-with-shared-view-rs.html).

# Dissociate principals from a resource share and remove a resource share
<a name="model-registry-ram-dissociate"></a>

The resource owner can dissociate principals from the resource share for a set of permissions or delete the entire resource share using the AWS CLI or the AWS RAM console. For details about how to dissociate principals from a resource share, see [Update a Resource Share](https://docs.aws.amazon.com/ram/latest/userguide/working-with-sharing-update.html) in the [AWS RAM](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html) documentation. For details about how to delete a resource share, see [Deleting a resource share](https://docs.aws.amazon.com/ram/latest/userguide/working-with-sharing-delete.html) in the [AWS RAM](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html) documentation.

## AWS CLI
<a name="model-registry-ram-dissociate-cli"></a>

To dissociate principals from a resource share, use the command [dissociate-resource-share](https://docs.aws.amazon.com/cli/latest/reference/ram/disassociate-resource-share.html) as follows:

```
aws ram disassociate-resource-share --resource-share-arn <resource-share-arn> --principals <principal>
```

To delete a resource share, use the command [delete-resource-share](https://docs.aws.amazon.com/cli/latest/reference/ram/delete-resource-share.html) as follows:

```
aws ram delete-resource-share --resource-share-arn <resource-share-arn>
```

## AWS RAM console
<a name="model-registry-ram-dissociate-ram"></a>

For more details about how to dissociate principals from a resource share, see [Update a Resource Share](https://docs.aws.amazon.com/ram/latest/userguide/working-with-sharing-update.html) in the [AWS RAM](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html) documentation. For more details about how to delete a resource share, see [Deleting a resource share](https://docs.aws.amazon.com/ram/latest/userguide/working-with-sharing-delete.html) in the [AWS RAM](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html) documentation.

# Promote the permission and resource share
<a name="model-registry-ram-promote"></a>

If you use customized (customer managed) permissions, you need to promote the permission and the associated resource share in order for the model package group to be discoverable. Complete the following steps to promote the permission and resource share.

1. To promote your customized permission to be accessible by AWS RAM, use the following command:

   ```
   aws ram promote-permission-created-from-policy —permission-arn <permission-arn>
   ```

1. Promote the resource share using the following command:

   ```
   aws ram promote-resource-share-created-from-policy --resource-share-arn <resource-share-arn>
   ```

If you see the `OperationNotPermittedException` error while performing the previous steps, the entity is not discoverable but is accessible. For example, if the resource owner attaches a resource policy with an assume role principal such as `“Principal”: {“AWS”: “arn:aws:iam::3333333333:role/Role-1”}`, or if the resource policy allows `“Action”: “*”` , the associated model package group is not promotable nor discoverable.

# View the Deployment History of a Model
<a name="model-registry-deploy-history"></a>

To view the deployments for a model version in the Amazon SageMaker Studio console, complete the following steps based on whether you use Studio or Studio Classic.

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

**View the deployment history for a model version**

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models** to display a list of your model groups.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. From the model groups list, choose the angle bracket to the left of the model group that you want to view.

1. A list of the model versions in the model group appears. If you don't see the model version that you want to delete, choose **View all**.

1. Select the name of the model version that you want to view.

1. Choose the **Activity** tab. Deployments for the model version appear as events in the activity list with an **Event type** of **ModelDeployment**.

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

**View the deployment history for a model version**

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. From the model groups list, select the name of the Model Group that you want to view.

1. A new tab appears with a list of the model versions in the Model Group.

1. In the list of model versions, select the name of the model version for which you want to view details.

1. On the model version tab that opens, choose **Activity**. Deployments for the model version appear as events in the activity list with an **Event type** of **ModelDeployment**.

------

# View model lineage details in Studio
<a name="model-registry-lineage-view-studio"></a>

You can view the lineage details of a registered model in Amazon SageMaker Studio. The following will provide instructions on how to access the lineage view in Studio. See [Amazon SageMaker ML Lineage Tracking](lineage-tracking.md) for more information about lineage tracking in Amazon SageMaker Studio.

This feature is not available in Amazon SageMaker Studio Classic.
+ If Studio is your default experience, the UI is similar to the images found in [Amazon SageMaker Studio UI overview](studio-updated-ui.md).
+ If Studio Classic is your default experience, the UI is similar to the images found in [Amazon SageMaker Studio Classic UI Overview](studio-ui.md).

The lineage view is an interactive visualization of the resources associated with your registered models. These resources include datasets, training jobs, approvals, models, and endpoints. In the lineage you can also view the associated resource details, including the source URI, creation timestamp, and other metadata.

The following capabilities are available in `us-east-1`, `us-west-2`, `ap-northeast-1`, and `eu-west-1` regions: 

You can track the lineage of logged and registered models. Furthermore, lineage for models resources include datasets, evaluators, training jobs, approvals, models, inference components, and endpoints. In the lineage you can also view the associated resource details, including the source URI, creation timestamp, and other metadata.

The following provides instructions on how to access the lineage details for a registered model version.

**To access the lineage details for a registered model version**

1. Open the Studioconsole by following the instructions in [Launch Amazon SageMaker Studio](studio-updated-launch.md).

1. Choose **Models** from the left navigation pane.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. (Optional) If you have models that are shared with you, you can choose between **My models** or **Shared with me**.

1. Select a registered model.

1. Choose the **Versions** tab, if not selected already.

1. Choose a specific model version from the **Versions** list.

1. Choose the **Lineage** tab. 

In the **Lineage** tab you can navigate through the resources associated with the model version. You can also choose a resource to view the resource details. 

Note that the Lineage view is for visualization purposes only. Rearranging or moving the components in this view does not affect the actual registered model resources.

For `us-east-1`, `us-west-2`, `ap-northeast-1`, and `eu-west-1` regions, you can use the following instructions to access the lineage details for logged and registered model versions:

1. Open the Studio console by following the instructions in [Launch Amazon SageMaker Studio](studio-updated-launch.md).

1. Choose **Models** from the left navigation pane.

1. Choose the **My models** tab.

1. (Optional) If you have models that are shared with you, you can choose between **Created by me** or **Shared with me**.

1. Select a model and choose **View Latest Version**.

1. Choose the **Lineage** tab.

# Model Registry Collections
<a name="modelcollections"></a>

You can use Collections to group registered models that are related to each other and organize them in hierarchies to improve model discoverability at scale. With Collections, you can organize registered models that are associated with one another. For example, you could categorize your models based on the domain of the problem they solve as Collections titled * NLP-models*, *CV-models*, or * Speech-recognition-models*. To organize your registered models in a tree structure, you can nest Collections within each other. Any operations you perform on a Collection, such as create, read, update, or delete, will not alter your registered models. You can use the Amazon SageMaker Studio UI or the Python SDK to manage your Collections.

The **Collections** tab in the Model Registry displays a list of all the Collections in your account. The following sections describe how you can use options in the **Collections** tab to do the following:
+ Create Collections
+ Add Model Groups to a Collection
+ Move Model Groups between Collections
+ Remove Model Groups or Collections from other Collections

Any operation you perform on your Collections does not affect the integrity of the individual Model Groups they contain—the underlying Model Group artifacts in Amazon S3 and Amazon ECR are not modified.

While Collections provide greater flexibility in organizing your models, the internal representation imposes some constraints on the size of your hierarchy. For a summary of these constraints, see [Constraints](modelcollections-limitations.md).

The following topics show you how to create and work with Collections in the Model Registry.

**Topics**
+ [Set up prerequisite permissions](modelcollections-permissions.md)
+ [Create a Collection](modelcollections-create.md)
+ [Add Model Groups to a Collection](modelcollections-add-models.md)
+ [Remove Model Groups or Collections from a Collection](modelcollections-remove-models.md)
+ [Move a Model Group Between Collections](modelcollections-move-models.md)
+ [View a Model Group's Parent Collection](modelcollections-view-parent.md)
+ [Constraints](modelcollections-limitations.md)

# Set up prerequisite permissions
<a name="modelcollections-permissions"></a>

Create a custom policy which includes the following required Resource Groups actions:
+ `resource-groups:CreateGroup`
+ `resource-groups:DeleteGroup`
+ `resource-groups:GetGroupQuery`
+ `resource-groups:ListGroupResources`
+ `resource-groups:Tag`
+ `tag:GetResources`

For instructions on how to add an inline policy, see [ Adding IAM identity permissions (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html#add-policies-console). When you choose the policy format, choose the JSON format and add the following policy:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "resource-groups:ListGroupResources"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "resource-groups:GetGroupQuery"
            ],
            "Resource": "arn:aws:resource-groups:*:*:group/*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "resource-groups:CreateGroup",
                "resource-groups:Tag"
            ],
            "Resource": "arn:aws:resource-groups:*:*:group/*",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "aws:TagKeys": "sagemaker:collection"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "resource-groups:DeleteGroup",
            "Resource": "arn:aws:resource-groups:*:*:group/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/sagemaker:collection": "true"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "tag:GetResources",
            "Resource": "*"
        }
    ]
}
```

------

# Create a Collection
<a name="modelcollections-create"></a>

**Important**  
Custom IAM policies that allow Amazon SageMaker Studio or Amazon SageMaker Studio Classic to create Amazon SageMaker resources must also grant permissions to add tags to those resources. The permission to add tags to resources is required because Studio and Studio Classic automatically tag any resources they create. If an IAM policy allows Studio and Studio Classic to create resources but does not allow tagging, "AccessDenied" errors can occur when trying to create resources. For more information, see [Provide permissions for tagging SageMaker AI resources](security_iam_id-based-policy-examples.md#grant-tagging-permissions).  
[AWS managed policies for Amazon SageMaker AI](security-iam-awsmanpol.md) that give permissions to create SageMaker resources already include permissions to add tags while creating those resources.

You can create a Collection in the Amazon SageMaker Studio console. To create a Collection, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models**.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Collections**.

1. (Optional) To create a Collection inside another Collection, navigate to the hierarchy where you want to add your Collection. Otherwise, your Collection is created at the root level.

1. In the **Actions** dropdown menu in the top right, choose **Create new collection**.

1. Enter a name for your Collection in the **Name** field of the dialog box.
**Note**  
If you plan to create multiple hierarchies in this Collection, keep your Collection names short. The absolute path, which is a string representing the location of your Collections from the root level, must be 256 characters or less. For additional details, see [Collection and Model Group tagging](modelcollections-limitations.md#modelcollections-tagging).

1. (Optional) To add Model Groups to your Collection, complete the following steps:

   1. Choose **Select model groups**.

   1. Select the Model Groups that you want to add. You can select up to 10.

1. Choose **Create**.

1. Check to make sure your Collection was created in the current hierarchy. If you do not immediately see your new Collection, choose **Refresh**.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. Choose the **Collections** tab.

1. (Optional) To create a Collection inside another Collection, navigate to the hierarchy where you want to add your Collection. Otherwise, your Collection is created at the root level.

1. In the **Actions** dropdown menu in the top right, choose **Create new collection**.

1. Enter a name for your Collection in the **Name** field of the dialog box.
**Note**  
If you plan to create multiple hierarchies in this Collection, keep your Collection names short. The absolute path, which is a string representing the location of your Collections from the root level, must be 256 characters or less. For additional details, see [Collection and Model Group tagging](modelcollections-limitations.md#modelcollections-tagging).

1. (Optional) To add Model Groups to your Collection, complete the following steps:

   1. Choose **Select model groups**.

   1. Select the Model Groups that you want to add. You can select up to 10.

1. Choose **Create**.

1. Check to make sure your Collection was created in the current hierarchy. If you do not immediately see your new Collection, choose **Refresh**.

------

# Add Model Groups to a Collection
<a name="modelcollections-add-models"></a>

You can add model groups to a Collection in the Amazon SageMaker Studio console. To add Model Groups to a Collection, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models**.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Models**, if not selected already.

1. Select the check box next to the model groups that you want to add. You can select up to 10 Model Groups. If you select more than 10, the UI option to add your Model Groups to a Collection is inactive.

1. Choose the vertical ellipsis next to **Create**, and choose **Add to collection**.

1. Select the radio button for the collection to which you want to add your selected Model Groups.

1. Choose **Add to collection**.

1. Check to make sure your Model Groups were added in to the collection. In the **Collections** column of the Model Groups you selected, you should see the name of collection to which you added the Model Groups.

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

You can add Model Groups to a Collection from either the **Model Groups** or **Collections** tab.

To add one or more Model Groups to a Collection from the ** Collections** tab, complete the following steps:

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. Choose the **Collections** tab.

1. Select the Collection to which you want to add Model Groups. If the desired Collection is not at root level, navigate to the hierarchy where you want to add your Model Groups.

1. In the **Actions** dropdown menu in the top right, choose **Add model groups**.

1. Select the Model Groups that you want to add. You can select up to 10 Model Groups. If you select more than 10, the UI option to add your Model Groups to a Collection is inactive.

1. Choose **Add to collection**.

1. Check to make sure your Model Groups were added in the current hierarchy. If you do not immediately see your new Model Groups, choose **Refresh**.

To add one or more Model Groups to a Collection from the **Model Groups** tab, complete the following steps:

1. Sign in to Studio Classic. For more information, see [Amazon SageMaker AI domain overview](gs-studio-onboard.md).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. Choose the **Model Groups** tab.

1. Select the Model Groups that you want to add. You can select up to 10. If you select more than 10, the UI option to add your Model Groups to a Collection is inactive.

1. In the **Actions** dropdown menu in the top right, choose **Add to collection**.

1. In the pop-up dialog, choose the root path location `Collections`. This link to the root location appears above the table.

1. Navigate to the hierarchy which contains your destination Collection, or where you want to create a new Collection to which you add your models.

1. (Optional) To add your Model Groups to an existing Collection, complete the following steps:

   1. Select the destination Collection.

   1. Choose **Add to collection**.

1. (Optional) To add your Model Groups to a new Collection, complete the following steps:

   1. Choose **New collection**.

   1. Enter a name for your new Collection.

   1. Choose **Create**.

------

# Remove Model Groups or Collections from a Collection
<a name="modelcollections-remove-models"></a>

When you remove Model Groups or Collections from a Collection, you are removing them from a particular grouping and not from the Model Registry. You can remove Model Groups from a Collection in the Amazon SageMaker Studio console.

To remove one or more Model Groups or Collections from a Collection, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models**.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Collections**.

1. Navigate to the Collection which contains the Model Groups or Collections you want to remove.

1. Select the Model Groups or Collections that you want to remove. You can select up to 10. If you select more than 10 Model Groups or Collections, the UI option to remove them is inactive.
**Important**  
You cannot simultaneously select Model Groups and Collections for removal. To remove both Model Groups and Collections, first remove Model Groups, and then remove Collections.
**Important**  
You cannot remove non-empty Collections. To remove a non-empty Collection, first remove its contents.

1. In the **Actions** dropdown menu in the top right, choose **Remove X items from collection** (where X is the number of Model Groups that you selected).

1. Confirm that you want to remove the selected Model Groups.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. Choose the **Collections** tab.

1. Navigate to the Collection which contains the Model Groups or Collections you want to remove.

1. Select the Model Groups or Collections that you want to remove. You can select up to 10. If you select more than 10 Model Groups or Collections, the UI option to remove them is inactive.
**Important**  
You cannot simultaneously select Model Groups and Collections for removal. To remove both Model Groups and Collections, first remove Model Groups, and then remove Collections.
**Important**  
You cannot remove non-empty Collections. To remove a non-empty Collection, first remove its contents.

1. In the **Actions** dropdown menu in the top right, choose **Remove X items from collection** (where X is the number of Model Groups you selected).

1. Confirm that you want to remove the selected Model Groups.

------

# Move a Model Group Between Collections
<a name="modelcollections-move-models"></a>

You can move one or more Model Groups from one Collection to another in the Amazon SageMaker Studio console.

To move Model Groups, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models**.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Collections**.

1. Navigate to the Collection which contains the Model Groups that you want to move.

1. Select the Model Groups that you want to move. You can select up to 10. If you select more than 10, the UI option to move your Model Groups is inactive.

1. In the **Actions** dropdown menu in the top right, choose **Move to**.

1. In the dialog box, choose the root path location `Collections`. This link to the root location appears above the table.

1. Navigate to the hierarchy which contains your destination Collection.

1. Select your destination Collection in the table.

1. Choose **Move here**.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. Choose the **Collections** tab.

1. Navigate to the Collection which contains the Model Groups that you want to move.

1. Select the Model Groups that you want to move. You can select up to 10. If you select more than 10, the UI option to move your Model Groups is inactive.

1. In the **Actions** dropdown menu in the top right, choose **Move to**.

1. In the dialog box, choose the root path location `Collections`. This link to the root location appears above the table.

1. Navigate to the hierarchy which contains your destination Collection.

1. Select your destination Collection in the table.

1. Choose **Move here**.

------

# View a Model Group's Parent Collection
<a name="modelcollections-view-parent"></a>

You can view the Collections which contain a particular Model Group in the Amazon SageMaker Studio console.

To view the Collections which contain a particular Model Group, complete the following steps based on whether you use Studio or Studio Classic.

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

1. Open the SageMaker Studio console by following the instructions in [Launch Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html).

1. In the left navigation pane, choose **Models**.

1. Choose the **Registered models** tab, if not selected already.

1. Immediately below the **Registered models** tab label, choose **Model Groups**, if not selected already.

1. View the **Collection** column for your Model Group, which displays the name of the Collection which contains this Model Group. If multiple Collections contain this Model Group, choose the **Collection** column entry to display a pop-up listing the Collections which contain this Model Group.

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

1. Sign in to Amazon SageMaker Studio Classic. For more information, see [Launch Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html).

1. In the left navigation pane, choose the **Home** icon ( ![\[Black square icon representing a placeholder or empty image.\]](http://docs.aws.amazon.com/sagemaker/latest/dg/images/studio/icons/house.png)).

1. Choose **Models**, and then **Model registry**.

1. Choose the **Model Groups** tab.

1. Find your Model Group in the table.

1. View the **Collection** column for your Model Group, which displays the name of the Collection which contains this Model Group. If multiple Collections contain this Model Group, choose the **Collection** column entry to display a pop-up listing the Collections which contain this Model Group.

------

# Constraints
<a name="modelcollections-limitations"></a>

While using Collections, you may face issues related to tag length constraints or rate limits for Collection operations. Review the following list of caveats so you can avoid issues related to these limitations when you work with your Collections.

**VPC constraints**
+ Collections are not supported in VPC mode.

**Collection operation constraints**
+ You can add a maximum of 10 Model Groups to a Collection at a time.
+ You can remove a maximum of 10 Model Groups from a Collection at a time.
+ You can move a maximum of 10 Model Groups from one Collection to another at a time.
+ You cannot delete a Collection unless it is empty.
+ A Model Group can belong to multiple Collections, but a Collection can only belong to one Collection.

**Tag-related constraints**
+ A Model Group can belong to a maximum of 48 Collections. For more details, see the following section [Collection and Model Group tagging](#modelcollections-tagging).
+ A Collection’s absolute path can be a maximum of 256 characters long. Since Collection names are user-specified, you can control the path length. For more details, see the following section [Collection and Model Group tagging](#modelcollections-tagging).

## Collection and Model Group tagging
<a name="modelcollections-tagging"></a>

The SageMaker Model Registry uses tag rules and tags to internally represent your Collection groupings and hierarchy. You can access these tag elements in the AWS Resource Access Manager, the SageMaker SDK, and the AWS CLI, but it is important that you do not alter or delete them.

**Important**  
Do not delete or alter any tag rules or tags which belong to your Collections or Model Groups. Doing so prevents you from performing Collection operations\$1

A tag rule is a key-value pair that SageMaker AI uses to identify a Collection’s location in the hierarchy. In short, the key is the key of the parent Collection, and the value is the path of the Collection within the hierarchy. SageMaker AI allows tag values to be 256 characters or less, so if you have multiple nested hierarchies you are advised to keep your Collection names short.

**Important**  
Keep your Collection names short. The absolute path to any Collection must be 256 characters long or less.

Model Groups, on the other hand, do not have tag rules but use tags. A Model Group’s tags include the tag rules for all the Collections which contain the Model Group. For example, if four Collections contain *model-group-1*, * model-group-1* has four tags. SageMaker AI allows a single AWS resource to have a maximum of 50 tags. Since two are pre-allocated for general purposes, a Model Group can have a maximum of 48 tags. In conclusion, a Model Group can belong to a maximum of 48 Collections.