

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

# SageMaker Python SDK 疑難排解指南
<a name="sagemaker-python-sdk-troubleshooting"></a>

您可以使用 SageMaker Python SDK，在 Python 指令碼或 Jupyter 筆記本內與 Amazon SageMaker AI 互動。雖然 SDK 提供簡化的工作流程，但您可能會遇到各種例外狀況或錯誤。本疑難排解指南旨在協助您了解並解決使用 SageMaker Python SDK 時可能發生的常見問題。它涵蓋了與建立訓練任務、處理任務和端點相關的案例，以及一般例外狀況處理實務。透過遵循以下各節中提供的指引，您可以有效地診斷並解決常見問題。

SageMaker Python SDK 可做為低階 SageMaker API 操作的包裝函式。您用來存取 SDK 的 IAM 角色必須能夠存取基礎操作。將 SageMaker AI 完整存取政策新增至您的 IAM 角色是最直接的方式，以確保您具有使用 SageMaker Python SDK 的許可。如需 SageMaker AI 完整存取政策的詳細資訊，請參閱 [Amazon SageMaker AI 完整存取](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonSageMakerFullAccess.html)。

雖然較不方便，但提供更精細的許可卻是使用 SDK 的安全方法。下列每一節都有所需許可的相關資訊。

## 建立訓練任務
<a name="sagemaker-python-sdk-troubleshooting-create-training-job"></a>

**重要**  
如果您不是將 SageMaker AI 完整存取政策新增至您的 IAM 角色，則其必須具有呼叫 [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) 和 [DescribeTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html) 操作的許可。  
它還需要下列動作的許可：  
存取 S3 中的輸入/輸出資料
執行 Amazon EC2 執行個體
日誌 CloudWatch 指標
如果您的 SageMaker 訓練任務需要存取 Amazon Virtual Private Cloud (Amazon VPC) 中的資源，請確定您在建立處理任務時設定必要的 VPC 設定和安全群組。

當您建立訓練任務時，可能會遇到 `botocore.exceptions.ClientError` 或 `ValueError` 例外狀況。

------
#### [ ValueError ]

當您傳遞給函式的值或參數有問題時，就會發生 `ValueError` 例外狀況。使用以下清單查看 `ValueError` 例外狀況的範例，以及如何修正這些例外狀況。
+ `ValueError: either image_uri or algorithm_arn is required. None was provided`:
  + 如果您使用的是 `AlgorithmEstimator` 函式，請提供 `algorithm_arn`。
  + 如果您使用的是 `Estimator` 函式，請提供 `estimator_arn`。
+ `ValueError: Unknown input channel: train is not supported by: scikit-decision-trees-15423055-57b73412d2e93e9239e4e16f83298b8f`

  提供無效的輸入通道時，您會收到此錯誤。輸入通道是模型預期的資料來源或參數。

  在 [演算法類型](algorithms-choose.md) 頁面上，您可以導覽至模型，以尋找模型輸入通道的相關資訊。

  您也可以在演算法 AWS Marketplace 頁面的使用****區段中找到輸入通道的相關資訊。

  使用下列程序取得演算法輸入通道的相關資訊。

**取得演算法輸入通道的相關資訊**

  1. 導覽至 [SageMaker AI 主控台](https://console.aws.amazon.com/sagemaker)。

  1. 在左側導覽列中，選擇**訓練**。

  1. 選取**演算法**。

  1. 選擇**尋找演算法**。

  1. 在產生的清單中尋找您的演算法。

  1. 選取**用量**索引標籤。

  1. 導覽至**通道規格**標題。

------
#### [ botocore.exceptions.ClientError ]

`botocore.exceptions.ClientError` 當基礎 AWS 服務擲回例外狀況時，就會發生例外狀況。這可能是由於各種原因所造成，例如參數不正確、許可問題或資源限制。使用以下清單取得 `botocore.exceptions.ClientError` 例外狀況的內容，以及如何修正這些例外狀況的相關資訊。
+ `ResourceLimitExceeded` – AWS 您的帳戶無法存取執行訓練任務所需的 Amazon EC2 執行個體。若要取得存取權，請求增加配額。如需配額增加的相關資訊，請參閱 [Service Quotas](https://docs.aws.amazon.com/general/latest/gr/sagemaker.html#limits_sagemaker)。如需 `botocore.exceptions.ClientError` 例外狀況的相關資訊，請使用下列清單。
+ `ValidationException` - 當您為訓練任務使用了錯誤的 Amazon EC2 執行個體類型時，驗證例外狀況就會出現。當您使用的 IAM 角色沒有訓練任務的許可時，它們也可能出現。

------

## 更新訓練任務
<a name="sagemaker-python-sdk-troubleshooting-update-training-job"></a>

**重要**  
如果您不是將 SageMaker AI 受管政策新增至 IAM 角色，則必須授予角色下列許可的存取權：  
`s3:GetObject` - 提供從 Amazon S3 儲存貯體讀取模型成品的許可
`s3:PutObject` - 如果適用，會提供將更新寫入至模型成品的許可
`iam:GetRole` - 提供取得執行訓練任務所需 IAM 角色之相關資訊的許可
`sagemaker:UpdateTrainingJob` – 提供使用 [UpdateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateTrainingJob.html) 操作來修改訓練任務的許可。
`logs:PutLogEvents` – 提供在更新過程中將日誌寫入 Amazon CloudWatch logs 的許可。

當您更新訓練任務時，可能會遇到 `botocore.exceptions.ParamValidationError` 或 `botocore.exceptions.ClientError`。

------
#### [ botocore.exceptions.ClientError ]

`ClientError` 具有下列訊息：

```
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateTrainingJob operation: Invalid UpdateTrainingJobRequest, the request cannot be empty            
```

如果遇到此錯誤，您必須包含下列其中一個參數，以及訓練任務的名稱：
+ `profiler_rule_configs` (list) - 分析工具規則組態的清單。根據預設，沒有分析工具規則組態。
+ `profiler_config` (dict) - SageMaker AI Profiler 的組態會收集指標並將其送出。根據預設，沒有分析工具組態。
+ `resource_config` (dict) - 訓練任務資源的組態。如果暖集區狀態為 `Available`，您可以更新持續作用期間。無法更新其他欄位。
+ `remote_debug_config` (dict) - `RemoteDebug` 的組態。字典可以包含 `EnableRemoteDebug`(bool)。

------
#### [ botocore.exceptions.ParamValidationError ]

`botocore.exceptions.ParamValidationError` 具有下列錯誤：

```
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter ProfilerRuleConfigurations, value: {'DisableProfiler': False}, type: <class 'dict'>, valid types: <class 'list'>, <class 'tuple'>
```

如果 `update_training_job` 函式未以預期格式提供參數，則可能會發生此例外狀況。例如，它預期 `profiler_rule_configs` 參數是清單。如果改以字典形式傳遞參數，則會引發錯誤。

------

## 建立處理任務
<a name="sagemaker-python-sdk-troubleshooting-create-processing-job"></a>

**重要**  
如果您不是將 SageMaker AI 受管政策新增至 IAM 角色，則必須授予角色下列許可的存取權：  
`sagemaker:CreateProcessingJob` - 提供建立處理任務的許可
`sagemaker:DescribeProcessingJob` - 提供取得處理任務相關資訊的許可
`s3:GetObject` - 提供從 Amazon S3 儲存貯體讀取模型成品的許可
`s3:PutObject` - 如果適用，會提供將更新寫入至模型成品的許可
`logs:PutLogEvents` – 提供在更新過程中將日誌寫入 Amazon CloudWatch logs 的許可。
如果您的處理任務需要存取 Amazon Virtual Private Cloud 內的資源，您必須在您建立的估算器內中指定其 `security_group_ids` 和 `subnets`。如需如何存取 Amazon VPC 內資源的範例，請參閱[使用 VPC 保護訓練和推論](https://sagemaker.readthedocs.io/en/stable/overview.html#secure-training-and-inference-with-vpc)。

當您建立處理任務時，可能會遇到 `ValueError`、`UnexpectedStatusException` 或 `botocore.exceptions.ClientError`。

------
#### [ ValueError ]

以下是 `ValueError` 的範例：

```
ValueError: code preprocess.py wasn't found. Please make sure that the file exists.           
```

您指定的路徑不正確。您可以指定指令碼檔案的相對路徑或絕對路徑。如需指定檔案路徑的詳細資訊，請參閱 [sagemaker.processing.RunArgs](https://sagemaker.readthedocs.io/en/stable/api/training/processing.html#sagemaker.processing.RunArgs)。

------
#### [ UnexpectedStatusException ]

以下是 `UnexpectedStatusException` 的範例：

```
UnexpectedStatusException: Error for Processing job sagemaker-scikit-learn-2024-07-02-14-08-55-993: Failed. Reason: AlgorithmError: , exit code: 1           
```

例外狀況隨附的回溯可協助您識別根本原因：

```
Traceback (most recent call last):
  File "/opt/ml/processing/input/code/preprocessing.py", line 51, in <module>
    df = pd.read_csv(input_data_path)
  .
  .
  .
  File "pandas/_libs/parsers.pyx", line 689, in pandas._libs.parsers.TextReader._setup_parser_source
FileNotFoundError: [Errno 2] File b'/opt/ml/processing/input/census-income.csv' does not exist: b'/opt/ml/processing/input/census-income.csv'
```

錯誤 `"FileNotFoundError: [Errno 2] File b'/opt/ml/processing/input/census-income.csv' does not exist"` 表示在指定的路徑 `/opt/ml/processing/input/` 中找不到輸入檔案 `census-income.csv`。驗證是否已正確地提供輸入資料，以及預先處理指令碼是否正在將資料複製到預期的路徑。

------
#### [ botocore.exceptions.ClientError ]

以下是 `botocore.exceptions.ClientError` 的範例：

```
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the CreateProcessingJob operation: RoleArn: Cross-account pass role is not allowed.
```

當您嘗試使用來自不同 AWS 帳戶的 IAM 角色建立 SageMaker Processing 任務時，會發生此`"Cross-account pass role is not allowed in create processing job"`錯誤。此安全功能確保在每個帳戶內管理角色和許可。若要解決問題，請執行下列動作：

1. 驗證 IAM 角色是否與處理任務位於相同的帳戶中。跨帳戶角色需要明確的限額

1. 如果使用來自另一個帳戶的角色，請更新其信任政策，以允許建立處理任務的帳戶擔任該角色。

1. 確保角色具有處理任務的必要許可，例如 `sagemaker:CreateProcessingJob` 或 `iam:PassRole`。

------

## 建立端點
<a name="sagemaker-python-sdk-troubleshooting-create-endpoint"></a>

**重要**  
如果您不是將 SageMaker AI 受管政策新增至 IAM 角色，則必須授予角色下列許可的存取權：  
`sagemaker:CreateModel` - 提供建立您要部署至端點之模型的許可
`sagemaker:CreateEndpointConfig` - 提供建立端點組態的許可，此組態會定義端點的行為，例如執行個體類型和計數
`sagemaker:CreateEndpoint` - 提供使用您所指定端點建立端點組態的許可
此外，您需要描述和列出模型、端點和端點組態的許可。

當您建立端點時，可能會遇到 `UnexpectedStatusException` 或 `botocore.exceptions.ClientError`。

以下是 `UnexpectedStatusException` 的範例：

```
UnexpectedStatusException: Error hosting endpoint gpt2-large-2024-07-03-15-28-20-448: Failed. Reason: The primary container for production variant AllTraffic did not pass the ping health check. Please check CloudWatch logs for this endpoint.. Try changing the instance type or reference the troubleshooting page https://docs.aws.amazon.com/sagemaker/latest/dg/async-inference-troubleshooting.html            
```

錯誤訊息會告知您檢查 Amazon CloudWatch 日誌。使用下列程序來檢查日誌。

**檢查 CloudWatch 日誌**

1. 導覽至 [Amazon SageMaker AI 主控台](https://console.aws.amazon.com/sagemaker)。

1. 在左側導覽窗格上，選擇**端點**。

1. 選取失敗的端點。

1. 在**端點詳細資訊**索引標籤上，選擇**檢視 CloudWatch 中的日誌**。

找到日誌之後，請尋找特定問題。以下是 CloudWatch Logs 日誌的範例：

```
NotImplementedError: gptq quantization is not supported for AutoModel, you can try to quantize it with text-generation-server quantize ORIGINAL_MODEL_ID NEW_MODEL_ID            
```

如需解決 `botocore.exceptions.ClientError` 的相關資訊，請參閱[例外狀況處理指引](#sagemaker-python-sdk-troubleshooting-exception-handling)。

## 更新端點
<a name="sagemaker-python-sdk-troubleshooting-update-endpoint"></a>

**重要**  
如果您不是將 SageMaker AI 受管政策新增至 IAM 角色，則必須授予角色下列許可的存取權：  
`sagemaker:UpdateEndpoint` - 提供更新現有端點的許可，例如變更端點的執行個體類型或計數
`sagemaker:UpdateEndpointWeightsAndCapacities` - 提供建立端點組態的許可，此組態會定義端點的行為，例如執行個體類型和計數
`sagemaker:DescribeEndpoint` - 提供描述端點目前組態的許可，這通常在更新之前需要此許可
此外，您可能需要描述和列出端點和端點組態的許可。

您可能會遇到 `ValueError`，如下所示：

```
ValueError: Endpoint with name 'abc' does not exist; please use an existing endpoint name            
```

錯誤表示指定的端點名稱與您 AWS 帳戶中的任何現有端點不相符。使用下列程序針對此錯誤進行疑難排解：

**針對值錯誤進行疑難排解**

1. 使用下列程式碼列出您的所有端點：

   ```
   import sagemaker
   sagemaker_session = sagemaker.Session()
   # List all endpoints
   endpoints = sagemaker_session.sagemaker_client.list_endpoints()
   print(endpoints)
   ```

1. 驗證您指定給 `update_endpoint` 函式的端點是否在清單中。

1. 請確定您在正確的區域中操作 AWS 。SageMaker AI 端點是區域特定的。

1. 確定您使用的 IAM 角色具有列出、描述或更新端點的許可。

## 例外狀況處理指引
<a name="sagemaker-python-sdk-troubleshooting-exception-handling"></a>

如果您找不到可協助您修正特定問題的相關資訊，下列程式碼範例可以給如何處理例外狀況的啟發。

以下是您可以用來擷取大多數例外狀況的一般範例。

```
import sagemaker
from botocore.exceptions import ParamValidationError, ClientError

try:
    sagemaker.some_api_call(SomeParam='some_param')

except ClientError as error:
    # Put your error handling logic here
    raise error

except ParamValidationError as error:
    raise ValueError('The parameters you provided are incorrect: {}'.format(error))
    
except ValueError as error:
    # Catch generic ValueError exceptions
```

有兩種主要類別的錯誤：
+ 特定於 SageMaker Python SDK 的錯誤
+ 基礎 AWS 服務的特定錯誤

基礎 AWS 服務特有的錯誤一律為`botocore.exceptions.ClientError`例外狀況。`botocore.exceptions.ClientError` 具有 `Error` 物件和 `ResponseMetadata` 物件。以下顯示用戶端錯誤的範本：

```
{
    'Error': {
        'Code': 'SomeServiceException',
        'Message': 'Details/context around the exception or error'
    },
    'ResponseMetadata': {
        'RequestId': '1234567890ABCDEF',
        'HostId': 'host ID data will appear here as a hash',
        'HTTPStatusCode': 400,
        'HTTPHeaders': {'header metadata key/values will appear here'},
        'RetryAttempts': 0
    }
}
```

以下是您可以使用 `botocore.exceptions.ClientError` 執行的特定錯誤處理範例：

```
try:
    sagemaker.some_api_call(SomeParam='some_param')

except botocore.exceptions.ClientError as err:
    if err.response['Error']['Code'] == 'InternalError': # Generic error
        # We grab the message, request ID, and HTTP code to give to customer support
        print('Error Message: {}'.format(err.response['Error']['Message']))
        print('Request ID: {}'.format(err.response['ResponseMetadata']['RequestId']))
        print('Http code: {}'.format(err.response['ResponseMetadata']['HTTPStatusCode']))
        raise err
    else if err.response['Error']['Code'] == 'ValidationException':
       raise ValueError(err.response['Error']['Message'])
```

如需如何處理`ClientError`例外狀況的詳細資訊，請參閱[剖析錯誤回應和擷取例外狀況 AWS 服務](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/error-handling.html#parsing-error-responses-and-catching-exceptions-from-aws-services)。