SageMaker Python 开发工具包故障排除指南 - 亚马逊 SageMaker AI

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

SageMaker Python 开发工具包故障排除指南

你可以使用 SageMaker Python 软件开发工具包在 Python 脚本或 Jupyter 笔记本中与 SageMaker Amazon AI 进行交互。尽管 SDK 提供了简化的工作流程,但您可能会遇到各种异常或错误。本疑难解答指南旨在帮助您了解和解决使用 SageMaker Python SDK 时可能出现的常见问题。它涵盖了与创建训练作业、处理作业和端点有关的场景,以及一般异常处理实践。按照以下各节提供的指导,您可以有效地诊断和解决常见问题。

SageMaker Python 开发工具包充当低级 SageMaker API 操作的封装器。用于访问 SDK 的 IAM 角色必须能够访问基础操作。将 A SageMaker I 完全访问策略添加到您的 IAM 角色是确保您有权使用 SageMaker Python SDK 的最直接方法。有关 SageMaker AI 完全访问策略的更多信息,请参阅 Amazon A SageMaker I 完全访问权限

虽然不太方便,但提供更精细的权限是使用 SDK 的一种安全方法。以下各节都有关于所需权限的信息。

创建训练作业

重要

如果您未将 SageMaker AI 完全访问权限策略添加到您的 IAM 角色,则该角色必须具有调用CreateTrainingJobDescribeTrainingJob操作的权限。

它还需要以下权限

  • 访问 S3 中的输入/输出数据

  • 运行 Amazon EC2 实例

  • 日志 CloudWatch 指标

如果您的 SageMaker 训练任务需要访问亚马逊虚拟私有云(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. 导航到 A SageMaker I 控制台

    2. 在左侧导航栏中,选择训练

    3. 选择算法

    4. 选择查找算法

    5. 在结果列表中找到您的算法。

    6. 选择使用方法选项卡。

    7. 导航至通道规范标题。

botocore.exceptions.ClientError

botocore.exceptions.ClientError底层 AWS 服务抛出异常时会发生异常。这可能是由于参数不正确、权限问题或资源限制等各种原因造成的。请使用以下列表了解 botocore.exceptions.ClientError 异常的上下文以及如何修复这些异常。

  • ResourceLimitExceeded— 您的 AWS 账户无权访问运行训练任务所需的亚马逊 EC2 实例。要获得访问权限,请申请增加配额。有关配额增加的信息,请参阅服务配额。请使用以下列表获取有关 botocore.exceptions.ClientError 例外的信息。

  • ValidationException— 当您在训练作业中使用错误的 Amazon EC2 实例类型时,会出现验证异常。当您使用的 IAM 角色没有训练作业的权限时,也会出现这种情况。

更新训练作业

重要

如果您未将 A SageMaker I 托管策略添加到您的 IAM 角色,则必须向该角色授予以下权限:

  • s3:GetObject:提供从 Amazon S3 存储桶读取模型构件的权限

  • s3:PutObject:如果适用,提供写入模型构件更新的权限

  • iam:GetRole:提供权限,以获取运行训练作业所需的 IAM 角色信息

  • sagemaker:UpdateTrainingJob— 提供使用操作修改训练UpdateTrainingJob作业的权限。

  • logs:PutLogEvents— 提供在更新过程中向 Amazon CloudWatch 日志写入日志的权限。

更新训练作业时,可能会遇到 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_config(dict)— SageMaker AI Profiler 的配置收集指标并将其发送出去。默认情况下,没有配置剖析器。

  • resource_config(字典):训练作业资源的配置。如果暖池状态为 Available,则可以更新保持连接周期。不能更新其他字段。

  • remote_debug_config(字典):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 参数是一个列表。如果参数以字典形式传递,则会引发错误。

创建处理任务

重要

如果您未将 A SageMaker I 托管策略添加到您的 IAM 角色,则必须向该角色授予以下权限:

  • sagemaker:CreateProcessingJob:提供创建处理任务的权限

  • sagemaker:DescribeProcessingJob:提供获取处理作业信息的权限

  • s3:GetObject:提供从 Amazon S3 存储桶读取模型构件的权限

  • s3:PutObject:如果适用,提供写入模型构件更新的权限

  • logs:PutLogEvents— 提供在更新过程中向 Amazon CloudWatch 日志写入日志的权限。

如果处理任务需要访问 Amazon 虚拟私有云中的资源,则必须在创建的估算器中指定其 security_group_idssubnets。有关如何访问 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" 表示在指定路径 /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 处理任务时,就会发生"Cross-account pass role is not allowed in create processing job"错误。这一安全功能可确保在每个账户内对角色和权限进行管理。要解决该问题,请执行以下操作:

  1. 确认 IAM 角色与处理任务的账户相同。跨账户角色需要明确允许

  2. 如果使用其他账户的角色,请更新其信任策略,允许创建处理任务的账户承担该角色。

  3. 确保角色拥有处理作业的必要权限,如 sagemaker:CreateProcessingJobiam:PassRole

创建端点

重要

如果您未将 A SageMaker I 托管策略添加到您的 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 日志。使用以下步骤检查日志。

查看日 CloudWatch 志
  1. 导航到亚马逊 A SageMaker I 控制台

  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 的信息,请参阅 异常处理指南

更新端点

重要

如果您未将 A SageMaker I 托管策略添加到您的 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 软件开发工具包的错误

  • 底层 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 服务捕获异常