SageMaker Python SDK 疑難排解指南 - Amazon SageMaker AI

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

SageMaker Python SDK 疑難排解指南

您可以使用 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 完整存取

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

建立訓練任務

重要

如果您不是將 SageMaker AI 完整存取政策新增至您的 IAM 角色,則必須具有呼叫 CreateTrainingJobDescribeTrainingJob 操作的許可。

它也需要許可才能:

  • 存取 S3 中的輸入/輸出資料

  • 執行 Amazon EC2 執行個體

  • Log CloudWatch 指標

如果您的 SageMaker 訓練任務需要存取 Amazon Virtual Private Cloud (Amazon VPC) 中的資源,請務必在建立處理任務時設定必要的 VPC 設定和安全群組。

當您建立訓練任務時,可能會遇到 botocore.exceptions.ClientErrorValueError 例外狀況。

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

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

    演算法類型頁面上,您可以導覽至模型,以尋找模型輸入通道的相關資訊。

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

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

    取得演算法輸入通道的相關資訊
    1. 導覽至 SageMaker AI 主控台

    2. 在左側導覽列中,選擇訓練

    3. 選取演算法

    4. 選擇尋找演算法

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

    6. 選取用量索引標籤。

    7. 導覽至頻道規格標題。

botocore.exceptions.ClientError

botocore.exceptions.ClientError 當基礎 AWS 服務擲回例外狀況時,就會發生例外狀況。這可能是由於各種原因,例如參數不正確、許可問題或資源限制。使用下列清單來了解botocore.exceptions.ClientError例外狀況的內容,以及如何修正例外狀況的資訊。

  • ResourceLimitExceeded – AWS 您的帳戶無法存取執行訓練任務所需的 Amazon EC2 執行個體。若要取得存取權,請請求提高配額。如需配額增加的相關資訊,請參閱 Service Quotas。使用下列清單以取得botocore.exceptions.ClientError例外狀況的相關資訊。

  • ValidationException – 當您使用錯誤的 Amazon EC2 執行個體類型進行訓練工作時,就會出現驗證例外狀況。當您正在使用的 IAM 角色沒有訓練任務的許可時,也可能出現。

更新訓練任務

重要

如果您不是將 SageMaker AI 受管政策新增至您的 IAM 角色,則必須授予該角色下列許可的存取權:

  • s3:GetObject – 提供從 Amazon S3 儲存貯體讀取模型成品的許可

  • s3:PutObject – 如果適用, 會提供許可,以寫入模型成品的更新

  • iam:GetRole – 提供許可,以取得執行訓練任務所需的 IAM 角色相關資訊

  • sagemaker:UpdateTrainingJob – 提供使用 UpdateTrainingJob 操作修改訓練任務的許可。

  • logs:PutLogEvents – 提供在更新程序期間將日誌寫入 Amazon CloudWatch logs的許可。

當您更新訓練任務時,您可能會執行到 botocore.exceptions.ParamValidationErrorbotocore.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 (清單) – Profiler 規則組態的清單。根據預設,沒有分析器規則組態。

  • profiler_config (dict) – SageMaker AI Profiler 的組態會收集指標並將其送出。根據預設,沒有分析器組態。

  • resource_config (dict) – 訓練任務資源的組態。如果暖集區狀態為 ,您可以更新保持連線期間Available。無法更新其他欄位。

  • remote_debug_config (dict) – 的組態RemoteDebug。字典可包含 EnableRemoteDebug(布爾)。

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 參數是清單。如果以字典形式傳遞 參數,則會引發錯誤。

建立處理任務

重要

如果您不是將 SageMaker AI 受管政策新增至您的 IAM 角色,則必須授予該角色下列許可的存取權:

  • sagemaker:CreateProcessingJob – 提供建立處理任務的許可

  • sagemaker:DescribeProcessingJob – 提供許可以取得處理任務的相關資訊

  • s3:GetObject – 提供從 Amazon S3 儲存貯體讀取模型成品的許可

  • s3:PutObject – 如果適用, 會提供許可,以寫入模型成品的更新

  • logs:PutLogEvents – 提供在更新程序期間將日誌寫入 Amazon CloudWatch logs的許可。

如果您的處理任務需要存取 Amazon Virtual Private Cloud 內的資源,則必須在建立的估算器subnets內指定其 security_group_ids和 。如需如何存取 Amazon VPC 內資源的範例,請參閱使用 VPC 進行安全訓練和推論

當您建立處理任務時,可能會執行到 ValueErrorUnexpectedStatusExceptionbotocore.exceptions.ClientError

ValueError

以下是 的範例ValueError

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

您指定的路徑不正確。您可以指定指令碼檔案的相對路徑或絕對路徑。如需指定檔案路徑的詳細資訊,請參閱 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"表示指定的路徑 census-income.csv 中找不到輸入檔案/opt/ml/processing/input/。確認輸入資料已正確提供,且預先處理指令碼正在將資料複製到預期的路徑。

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 處理任務時,會發生此"Cross-account pass role is not allowed in create processing job"錯誤。此安全功能可確保在每個帳戶中管理角色和許可。若要解決問題,請執行下列動作:

  1. 確認 IAM 角色與處理任務位於相同的帳戶中。跨帳戶角色需要明確額度

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

  3. 確保角色具有處理任務的必要許可,例如 sagemaker:CreateProcessingJobiam:PassRole

建立端點

重要

如果您不是將 SageMaker AI 受管政策新增至您的 IAM 角色,則必須授予該角色下列許可的存取權:

  • sagemaker:CreateModel – 提供建立您要部署至端點之模型的許可

  • sagemaker:CreateEndpointConfig – 提供建立定義端點行為的端點組態的許可,例如執行個體類型和計數

  • sagemaker:CreateEndpoint – 提供使用您指定的端點建立端點組態的許可

此外,您需要許可來描述和列出模型、端點和端點組態。

建立端點時,您可能會執行到 UnexpectedStatusExceptionbotocore.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 logs。使用下列程序來檢查日誌。

檢查 CloudWatch 日誌
  1. 導覽至 Amazon SageMaker AI 主控台

  2. 在左側導覽上,選擇端點

  3. 選取失敗的端點。

  4. 端點詳細資訊頁面上,選擇在 CloudWatch 中檢視日誌

找到日誌後,尋找特定問題。以下是 CloudWatch 日誌的範例:

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 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)
  2. 確認您指定給update_endpoint函數的端點在清單中。

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

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

例外狀況處理指引

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

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

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 服務