

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

# 調整您的訓練工作以存取私有 Docker 登錄檔中的映像
<a name="docker-containers-adapt-your-own-private-registry"></a>

您可以使用私有 [Docker 登錄檔](https://docs.docker.com/registry/)，代替 Amazon Elastic Container Registry (Amazon ECR) 來託管 SageMaker AI 訓練的映像。下列指示說明如何建立 Docker 登錄檔、配置虛擬私有雲端 (VPC) 和訓練任務、儲存映像，以及讓 SageMaker AI 可以存取私有 Docker 登錄檔中的訓練映像。這些指示也會示範如何使用需要對 SageMaker 訓練工作進行身份驗證的 Docker 登錄檔。

## 在私有 Docker 登錄檔中建立並儲存您的映像
<a name="docker-containers-adapt-your-own-private-registry-prerequisites"></a>

建立一個私有的 Docker 登錄檔來儲存您的映像。您的登錄檔必須：
+ 使用 [Docker Registry HTTP API](https://docs.docker.com/registry/spec/api/) 協議
+ 可從 `CreateTrainingJob` API 中的 [VpcConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html#API_CreateTrainingJob_RequestSyntax) 參數內指定的相同 VPC 存取。在建立訓練工作時輸入 `VpcConfig`。
+ 使用出自已知公用憑證授權機構的 [TLS 憑證](https://aws.amazon.com/what-is/ssl-certificate/)加以保護。

如需建立 Docker 登錄檔的詳細資訊，請參閱[設定登錄檔伺服器](https://docs.docker.com/registry/deploying/)。

## 設定您的 VPC 和 SageMaker 訓練工作
<a name="docker-containers-adapt-your-own-private-registry-configure"></a>

SageMaker AI 使用您的 VPC 內的網路連線以存取 Docker 登錄檔中的映像。若要使用 Docker 登錄檔中的映像進行訓練，必須可以從您帳戶中的 Amazon VPC 存取該登錄檔。如需詳細資訊，請參閱[使用需要驗證的 Docker 登錄檔進行訓練](docker-containers-adapt-your-own-private-registry-authentication.md)。

並且必須將訓練工作設定為連接到 Docker 登錄檔可以存取的同一個 VPC。如需詳細資訊，請參閱[設定訓練工作以供 Amazon VPC 存取](https://docs.aws.amazon.com/sagemaker/latest/dg/train-vpc.html#train-vpc-configure)。

## 使用私有 Docker 登錄檔中的映像建立訓練工作
<a name="docker-containers-adapt-your-own-private-registry-create"></a>

若要使用私有 Docker 登錄檔中的映像進行訓練，請使用下列指南來設定映像、設定並建立訓練工作。以下程式碼範例使用 適用於 Python (Boto3) 的 AWS SDK 用戶端。

1. 建立訓練映像組態物件，並輸入 `Vpc` 的 `TrainingRepositoryAccessMode` 欄位，如下所示。

   ```
   training_image_config = {
       'TrainingRepositoryAccessMode': 'Vpc'
   }
   ```
**注意**  
如果您的私有 Docker 登錄檔需要驗證，必須新增一個 `TrainingRepositoryAuthConfig` 物件至訓練映像組態物件。您也必須指定 函數的 Amazon Resource Name (ARN)，該 AWS Lambda 函數會使用 `TrainingRepositoryAuthConfig` 物件`TrainingRepositoryCredentialsProviderArn`的 欄位，為 SageMaker AI 提供存取憑證。如需詳細資訊，請參閱下方的程式碼架構範例。  

   ```
   training_image_config = {
      'TrainingRepositoryAccessMode': 'Vpc',
      'TrainingRepositoryAuthConfig': {
           'TrainingRepositoryCredentialsProviderArn': 'arn:aws:lambda:Region:Acct:function:FunctionName'
      }
   }
   ```

   如需如何建立 Lambda 函式以提供驗證的資訊，請參閱[使用需要驗證的 Docker 登錄檔進行訓練](docker-containers-adapt-your-own-private-registry-authentication.md)。

1. 使用 Boto3 用戶端建立一個訓練工作，並將正確的組態傳送至 [create\$1training\$1job](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) API。下列指示說明如何設定元件及建立訓練工作。

   1. 建立要傳送給 `create_training_job` 的 `AlgorithmSpecification` 物件。使用您在前一步驟中建立的訓練映像組態物件，如以下程式碼範例所示。

      ```
      algorithm_specification = {
         'TrainingImage': 'myteam.myorg.com/docker-local/my-training-image:<IMAGE-TAG>',
         'TrainingImageConfig': training_image_config,
         'TrainingInputMode': 'File'
      }
      ```
**注意**  
若要使用固定版本而非更新版本的映像，請參照映像的[摘要](https://docs.docker.com/engine/reference/commandline/pull/#pull-an-image-by-digest-immutable-identifier)，而不是依據名稱或標籤。

   1. 指定要傳送給 `create_training_job` 的訓練工作名稱和角色，如以下程式碼範例所示。

      ```
      training_job_name = 'private-registry-job'
      execution_role_arn = 'arn:aws:iam::123456789012:role/SageMakerExecutionRole'
      ```

   1. 為訓練工作的 VPC 組態指定安全群組和子網路。您的私有 Docker 登錄檔必須允許來自指定的安全群組的傳入流量，如下列程式碼範例所示。

      ```
      vpc_config = {
          'SecurityGroupIds': ['sg-0123456789abcdef0'],
          'Subnets': ['subnet-0123456789abcdef0','subnet-0123456789abcdef1']
      }
      ```
**注意**  
如果您的子網路與私有 Docker 登錄檔不在相同的 VPC 中，您必須在兩個 VPC 之間設定網路連線。如需詳細資訊，請參閱使用 [VPC 對等互連](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-peering.html)連接數個 VPC。

   1. 指定資源組態，包括用於訓練的機器學習運算執行個體和儲存磁碟區，如下列程式碼範例所示。

      ```
      resource_config = {
          'InstanceType': 'ml.m4.xlarge',
          'InstanceCount': 1,
          'VolumeSizeInGB': 10,
      }
      ```

   1. 指定輸入和輸出資料組態、訓練資料集的儲存位置，以及您要儲存模型成品的位置，如下列程式碼範例所示。

      ```
      input_data_config = [
          {
              "ChannelName": "training",
              "DataSource":
              {
                  "S3DataSource":
                  {
                      "S3DataDistributionType": "FullyReplicated",
                      "S3DataType": "S3Prefix",
                      "S3Uri": "s3://your-training-data-bucket/training-data-folder"
                  }
              }
          }
      ]
      
      output_data_config = {
          'S3OutputPath': 's3://your-output-data-bucket/model-folder'
      }
      ```

   1. 指定模型訓練工作可以執行的秒數上限，如下列程式碼範例所示。

      ```
      stopping_condition = {
          'MaxRuntimeInSeconds': 1800
      }
      ```

   1. 最後，使用您在先前步驟所指定的參數來建立訓練工作，如下列程式碼範例所示。

      ```
      import boto3
      sm = boto3.client('sagemaker')
      try:
          resp = sm.create_training_job(
              TrainingJobName=training_job_name,
              AlgorithmSpecification=algorithm_specification,
              RoleArn=execution_role_arn,
              InputDataConfig=input_data_config,
              OutputDataConfig=output_data_config,
              ResourceConfig=resource_config,
              VpcConfig=vpc_config,
              StoppingCondition=stopping_condition
          )
      except Exception as e:
          print(f'error calling CreateTrainingJob operation: {e}')
      else:
          print(resp)
      ```

# 使用 SageMaker AI 估算器執行訓練任務
<a name="docker-containers-adapt-your-own-private-registry-estimator"></a>

您也可以使用 SageMaker Python SDK 中的[估算器](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html)來處理 SageMaker 訓練工作的組態和執行。下列程式碼範例，說明如何使用私有 Docker 登錄檔的映像來設定及執行估算器。

1. 匯入必要的程式庫和相依性，如以下程式碼範例所示。

   ```
   import boto3
   import sagemaker
   from sagemaker.estimator import Estimator
   
   session = sagemaker.Session()
   
   role = sagemaker.get_execution_role()
   ```

1. 提供您的訓練映像、安全性群組和子網路的通用資源識別碼 (URI) 給您的訓練工作的 VPC 組態，如下列程式碼範例所示。

   ```
   image_uri = "myteam.myorg.com/docker-local/my-training-image:<IMAGE-TAG>"
   
   security_groups = ["sg-0123456789abcdef0"]
   subnets = ["subnet-0123456789abcdef0", "subnet-0123456789abcdef0"]
   ```

   如需有關 `security_group_ids` 和 `subnets` 的詳細資訊，請參閱 SageMaker Python SDK 的[估算器](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html)一節有關適當參數的說明。
**注意**  
SageMaker AI 使用您的 VPC 內的網路連線以存取 Docker 登錄檔中的映像。若要使用 Docker 登錄檔中的映像進行訓練，必須可以從您帳戶中的 Amazon VPC 存取該登錄檔。

1. 或者，如果您的 Docker 登錄檔需要身分驗證，您也必須指定 AWS Lambda 函數的 Amazon Resource Name (ARN)，以提供 SageMaker AI 存取憑證。以下程式碼範例說明如何指定 ARN。

   ```
   training_repository_credentials_provider_arn = "arn:aws:lambda:us-west-2:1234567890:function:test"
   ```

   如需詳細資訊以了解如何在需要驗證的 Docker 登錄檔中使用映像檔，請參閱下方的**使用需要驗證的 Docker 登錄檔進行訓練**。

1. 使用先前步驟的程式碼範例來設定估算器，如下列程式碼範例所示。

   ```
   # The training repository access mode must be 'Vpc' for private docker registry jobs 
   training_repository_access_mode = "Vpc"
   
   # Specify the instance type, instance count you want to use
   instance_type="ml.m5.xlarge"
   instance_count=1
   
   # Specify the maximum number of seconds that a model training job can run
   max_run_time = 1800
   
   # Specify the output path for the model artifacts
   output_path = "s3://your-output-bucket/your-output-path"
   
   estimator = Estimator(
       image_uri=image_uri,
       role=role,
       subnets=subnets,
       security_group_ids=security_groups,
       training_repository_access_mode=training_repository_access_mode,
       training_repository_credentials_provider_arn=training_repository_credentials_provider_arn,  # remove this line if auth is not needed
       instance_type=instance_type,
       instance_count=instance_count,
       output_path=output_path,
       max_run=max_run_time
   )
   ```

1. 以您的工作名稱和輸入路徑做為參數呼叫 `estimator.fit`，以開始訓練工作，如下列程式碼範例所示。

   ```
   input_path = "s3://your-input-bucket/your-input-path"
   job_name = "your-job-name"
   
   estimator.fit(
       inputs=input_path,
       job_name=job_name
   )
   ```

# 使用需要驗證的 Docker 登錄檔進行訓練
<a name="docker-containers-adapt-your-own-private-registry-authentication"></a>

如果您的 Docker 登錄檔需要驗證，您必須建立 AWS Lambda 函式以供 SageMaker AI 存取憑證。然後，建立訓練工作，並在 [create\$1training\$1job](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_training_job) API 內提供此 Lambda 函式的 ARN。最後，您可以選擇建立介面 VPC 端點，讓您的 VPC 可以與 Lambda 函式通訊，而不必透過網際網路傳送流量。以下指南說明如何建立 Lambda 函式、為其指派正確角色，以及建立介面 VPC 端點。

## 建立 Lambda 函式
<a name="docker-containers-adapt-your-own-private-registry-authentication-create-lambda"></a>

建立 AWS Lambda 函數，將存取憑證傳遞至 SageMaker AI 並傳回回應。下列程式碼範例建立 Lambda 函式處理常式，如下所示。

```
def handler(event, context):
   response = {
      "Credentials": {"Username": "username", "Password": "password"}
   }
   return response
```

設定私有 Docker 登錄檔的驗證類型，會決定 Lambda 函式傳回的回應內容，如下所示。
+ 如果您的私有 Docker 登錄檔使用基本驗證，Lambda 函式會傳回所需的使用者名稱和密碼，以便向登錄檔進行驗證。
+ 如果您的私有 Docker 登錄檔使用[持有者權杖驗證](https://docs.docker.com/registry/spec/auth/token/)，則使用者名稱和密碼將發送至您的授權服務器，然後回傳持有者權杖。然後，此權杖將用於驗證您的私有 Docker 登錄檔。

**注意**  
如果同一帳戶中多個登錄檔有多個 Lambda 函式，而且訓練工作的執行角色相同，那麼針對登錄檔之一的訓練工作，將可以存取其他登錄檔的 Lambda 函式。

## 授予 Lambda 函式正確的角色許可
<a name="docker-containers-adapt-your-own-private-registry-authentication-lambda-role"></a>

您在 `create_training_job` API 中使用的 [IAMrole](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) 必須具有呼叫 AWS Lambda 函數的許可。下列程式碼範例示範如何延伸 IAM 角色的許可政策以呼叫 `myLambdaFunction`。

```
{
    "Effect": "Allow",
    "Action": [
        "lambda:InvokeFunction"
    ],
    "Resource": [
        "arn:aws:lambda:*:*:function:*myLambdaFunction*"
    ]
}
```

如需如何編輯角色許可的詳細資訊，請參閱*身分和存取管理使用者指南*AWS 內的[修改角色許可政策 (主控台)](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-modify_permissions-policy)。

**注意**  
已連接 **AmazonSageMakerFullAccess** 受管政策的 IAM 角色具有許可，可以呼叫名稱中含有 “SageMaker AI” 的所有 Lambda 函式。

## 為 Lambda 建立介面 VPC 端點
<a name="docker-containers-adapt-your-own-private-registry-authentication-lambda-endpoint"></a>

如果您建立一個介面端點，Amazon VPC 就可以與 Lambda 函式通訊，而不必透過網際網路傳送流量。如需詳細資訊，請參閱 *AWS Lambda 開發人員指南*中的[設定 Lambda 的介面 VPC 端點](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc-endpoints.html)。

建立介面端點之後，SageMaker 訓練會透過您的 VPC 將請求傳送至 `lambda.region.amazonaws.com` 來呼叫您的 Lambda 函式。如果您在建立介面端點時選取**啟用 DNS 名稱**，[Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 會將呼叫路由至 Lambda 介面端點。如果您使用不同的 DNS 提供者，則必須將 `lambda.region.amazonaws.co`m 對應至 Lambda 介面端點。