使用 SageMaker Training Compiler 运行 TensorFlow 训练作业 - 亚马逊 SageMaker AI
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

使用 SageMaker Training Compiler 运行 TensorFlow 训练作业

您可以使用任意 SageMaker AI 界面通过 SageMaker Training Compiler 运行训练作业:Amazon SageMaker Studio Classic、Amazon SageMaker Notebook 实例、适用于 Python (Boto3) 的 Amazon SDK和 Amazon Command Line Interface。

使用 SageMaker Python SDK

要开启 SageMaker Training Compiler,请将 compiler_config 参数添加到 SageMaker AI TensorFlow 或 Hugging Face 估算器中。导入 TrainingCompilerConfig 类,并将它的一个实例传递给 compiler_config 参数。以下代码示例显示了已开启 SageMaker Training Compiler 的 SageMaker AI 估算器类的结构。

提示

要开始使用 TensorFlow 和 Transformers 库提供的预构建模型,请尝试使用 经过测试的模型 上的参考表中提供的批处理大小。

注意

适用于 TensorFlow 的 SageMaker Training Compiler 可通过 SageMaker AI TensorFlowHugging Face 框架估算器获得。

有关适合您的使用案例的信息,请参阅下列选项之一。

TensorFlow
from sagemaker.tensorflow import TensorFlow, TrainingCompilerConfig # the original max batch size that can fit into GPU memory without compiler batch_size_native=12 learning_rate_native=float('5e-5') # an updated max batch size that can fit into GPU memory with compiler batch_size=64 # update the global learning rate learning_rate=learning_rate_native/batch_size_native*batch_size hyperparameters={ "n_gpus": 1, "batch_size": batch_size, "learning_rate": learning_rate } tensorflow_estimator=TensorFlow( entry_point='train.py', instance_count=1, instance_type='ml.p3.2xlarge', framework_version='2.9.1', hyperparameters=hyperparameters, compiler_config=TrainingCompilerConfig(), disable_profiler=True, debugger_hook_config=False ) tensorflow_estimator.fit()

要准备训练脚本,请参阅以下页面。

Hugging Face Estimator with TensorFlow
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig # the original max batch size that can fit into GPU memory without compiler batch_size_native=12 learning_rate_native=float('5e-5') # an updated max batch size that can fit into GPU memory with compiler batch_size=64 # update the global learning rate learning_rate=learning_rate_native/batch_size_native*batch_size hyperparameters={ "n_gpus": 1, "batch_size": batch_size, "learning_rate": learning_rate } tensorflow_huggingface_estimator=HuggingFace( entry_point='train.py', instance_count=1, instance_type='ml.p3.2xlarge', transformers_version='4.21.1', tensorflow_version='2.6.3', hyperparameters=hyperparameters, compiler_config=TrainingCompilerConfig(), disable_profiler=True, debugger_hook_config=False ) tensorflow_huggingface_estimator.fit()

要准备训练脚本,请参阅以下页面。

Hugging Face Estimator with TensorFlow
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig # choose an instance type, specify the number of instances you want to use, # and set the num_gpus variable the number of GPUs per instance. instance_count=1 instance_type='ml.p3.8xlarge' num_gpus=4 # the original max batch size that can fit to GPU memory without compiler batch_size_native=16 learning_rate_native=float('5e-5') # an updated max batch size that can fit to GPU memory with compiler batch_size=26 # update learning rate learning_rate=learning_rate_native/batch_size_native*batch_size*num_gpus*instance_count hyperparameters={ "n_gpus": num_gpus, "batch_size": batch_size, "learning_rate": learning_rate } tensorflow_huggingface_estimator=HuggingFace( entry_point='train.py', instance_count=instance_count, instance_type=instance_type, transformers_version='4.21.1', tensorflow_version='2.6.3', hyperparameters=hyperparameters, compiler_config=TrainingCompilerConfig(), disable_profiler=True, debugger_hook_config=False ) tensorflow_huggingface_estimator.fit()
提示

要准备训练脚本,请参阅以下页面。

以下列表是使用编译器运行 SageMaker 训练作业所需的最少参数集。

注意

使用 SageMaker AI Hugging Face 估算器时,必须指定 transformers_versiontensorflow_versionhyperparameterscompiler_config 参数才能启用 SageMaker Training Compiler。您无法使用 image_uri 手动指定集成了 支持的框架 上列出的深度学习容器的 Training Compiler。

  • entry_point (str) – 必需。指定训练脚本的文件名。

  • instance_count (int) – 必需。指定实例数。

  • instance_type (str) – 必需。指定实例类型。

  • transformers_version(str):仅在使用 SageMaker AI Hugging Face 估算器时必需。指定 SageMaker Training Compiler 支持的 Hugging Face Transformers 库版本。要查找可用版本,请参阅 支持的框架

  • framework_versiontensorflow_version (str) – 必需。指定 SageMaker Training Compiler 支持的 TensorFlow 版本。要查找可用版本,请参阅 支持的框架

    注意

    在使用 SageMaker AI TensorFlow 估算器时,必须指定 framework_version

    在使用 SageMaker AI Hugging Face 估算器时,必须同时指定 transformers_versiontensorflow_version

  • hyperparameters (dict) – 可选。为训练作业指定超参数,例如 n_gpusbatch_sizelearning_rate。启用 SageMaker Training Compiler 后,请尝试更大的批处理大小并相应调整学习率。要查找有关使用编译器和调整的批处理大小以提高训练速度的案例研究,请参阅经过测试的模型SageMaker Training Compiler 示例笔记本和博客

  • compiler_config(TrainingCompilerConfig 对象)– 必需。包括此参数可启用 SageMaker Training Compiler。下面是 TrainingCompilerConfig 类的参数。

    • enabled (bool) – 可选。指定 TrueFalse 可打开或关闭 SageMaker Training Compiler。默认值为 True

    • debug (bool) – 可选。要从编译器加速的训练作业中接收更详细的训练日志,请将此项更改为 True。但是,额外的日志记录可能会增加开销并减缓编译后的训练作业。默认值为 False

警告

如果您打开 SageMaker Debugger,可能会影响 SageMaker Training Compiler 的性能。我们建议您在运行 SageMaker Training Compiler 时关闭 Debugger,以确保不会对性能产生影响。有关更多信息,请参阅 注意事项。要关闭 Debugger 功能,请向估算器添加以下两个参数:

disable_profiler=True, debugger_hook_config=False

如果使用编译器成功启动训练作业,则在作业初始化阶段将收到以下日志:

  • TrainingCompilerConfig(debug=False)

    Found configuration for Training Compiler Configuring SM Training Compiler...
  • TrainingCompilerConfig(debug=True)

    Found configuration for Training Compiler Configuring SM Training Compiler... Training Compiler set to debug mode

使用 SageMaker AI Python SDK 和扩展 SageMaker AI 框架深度学习容器

适用于 TensorFlow 的 Amazon 深度学习容器 (DLC) 使用 TensorFlow 的更改后版本,其中包括基于开源 TensorFlow 框架的更改。SageMaker AI Framework Deep Learning Containers 针对底层 Amazon 基础设施和 Amazon SageMaker AI 进行了优化。凭借使用 DLC 所获得的优势,SageMaker Training Compiler 集成在原生 TensorFlow 的基础上增加了更多的性能改进。此外,您可以通过扩展 DLC 映像来创建自定义训练容器。

注意

这项 Docker 自定义功能目前仅适用于 TensorFlow。

要针对您的使用案例扩展和自定义 SageMaker AI TensorFlow DLC,请按照以下说明进行操作。

创建 Dockerfile

使用以下 Dockerfile 模板扩展 SageMaker AI TensorFlow DLC。您必须使用 SageMaker AI TensorFlow DLC 映像作为 Docker 容器的基本映像。要查找 SageMaker AI TensorFlow DLC 映像 URI,请参阅 Supported Frameworks

# SageMaker AI TensorFlow Deep Learning Container image FROM 763104351884.dkr.ecr.<aws-region>.amazonaws.com/tensorflow-training:<image-tag> ENV PATH="/opt/ml/code:${PATH}" # This environment variable is used by the SageMaker AI container # to determine user code directory. ENV SAGEMAKER_SUBMIT_DIRECTORY /opt/ml/code # Add more code lines to customize for your use-case ...

有关更多信息,请参阅步骤 2:创建并上传 Dockerfile 和 Python 训练脚本

在扩展 SageMaker AI Framework DLC 时,请考虑以下缺陷:

  • 请不要在 SageMaker AI 容器中显式卸载或更改 TensorFlow 包的版本。这样做会导致经 Amazon 优化后的 TensorFlow 包由开源 TensorFlow 包覆盖,从而导致性能下降。

  • 注意那些将特定 TensorFlow 版本或风格作为依赖项的包。这些包可能会隐式卸载经 Amazon 优化的 TensorFlow 并安装开源 TensorFlow 包。

例如,有一个已知问题,即 tensorflow/modelstensorflow/text 库总是尝试重新安装开源 TensorFlow。如果您需要安装这些库来为您的使用案例选择特定版本,我们建议您考察 2.9 或更高版本的 SageMaker AI TensorFlow DLC Dockerfiles。Dockerfiles 的路径通常采用以下格式:tensorflow/training/docker/<tensorflow-version>/py3/<cuda-version>/Dockerfile.gpu。在 Dockerfiles 中,您应找到代码行来按顺序重新安装 Amazon 管理的 TensorFlow 二进制文件(指定给 TF_URL 环境变量)和其他依赖项。重新安装部分应与以下示例类似:

# tf-models does not respect existing installations of TensorFlow # and always installs open source TensorFlow RUN pip3 install --no-cache-dir -U \ tf-models-official==x.y.z RUN pip3 uninstall -y tensorflow tensorflow-gpu \ ; pip3 install --no-cache-dir -U \ ${TF_URL} \ tensorflow-io==x.y.z \ tensorflow-datasets==x.y.z

构建并推送到 ECR

要构建 Docker 容器并将其推送到 Amazon ECR,请按照以下链接中的说明进行操作:

使用 SageMaker Python SDK 估算器运行

像往常一样使用 SageMaker AI TensorFlow 框架估算器。您必须指定 image_uri 以使用您在 Amazon ECR 中托管的新容器。

import sagemaker, boto3 from sagemaker import get_execution_role from sagemaker.tensorflow import TensorFlow, TrainingCompilerConfig account_id = boto3.client('sts').get_caller_identity().get('Account') ecr_repository = 'tf-custom-container-test' tag = ':latest' region = boto3.session.Session().region_name uri_suffix = 'amazonaws.com' byoc_image_uri = '{}.dkr.ecr.{}.{}/{}'.format( account_id, region, uri_suffix, ecr_repository + tag ) byoc_image_uri # This should return something like # 111122223333.dkr.ecr.us-east-2.amazonaws.com/tf-custom-container-test:latest estimator = TensorFlow( image_uri=image_uri, role=get_execution_role(), base_job_name='tf-custom-container-test-job', instance_count=1, instance_type='ml.p3.8xlarge' compiler_config=TrainingCompilerConfig(), disable_profiler=True, debugger_hook_config=False ) # Start training estimator.fit()

使用 SageMaker AI CreateTrainingJob API 操作启用 SageMaker AI Training Compiler

必须在 CreateTrainingJobAPI 操作的请求语法中使用 AlgorithmSpecificationHyperParameters 字段来指定 SageMaker Training Compiler 配置选项。

"AlgorithmSpecification": { "TrainingImage": "<sagemaker-training-compiler-enabled-dlc-image>" }, "HyperParameters": { "sagemaker_training_compiler_enabled": "true", "sagemaker_training_compiler_debug_mode": "false" }

要查找已实施 SageMaker Training Compiler 的深度学习容器映像 URI 的完整列表,请参阅支持的框架