

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

# Amazon SageMaker 调试器
<a name="train-debugger"></a>

使用 Amazon Debugger 实时调试机器学习训练作业中的模型输出张量，并检测非融合问题。 SageMaker 

## Amazon SageMaker 调试器功能
<a name="debugger-features"></a>

机器学习 (ML) 训练作业可能存在系统瓶颈、过度拟合、饱和激活函数和梯度消失等问题，这些问题会影响模型性能。

SageMaker Debugger 提供了用于调试训练作业和解决此类问题的工具，从而提高模型的性能。Debugger 也提供了一些工具，用于在发现训练异常情况时发送警报，针对问题采取措施，并通过将收集的指标和张量可视化来确定造成问题的根本原因。

SageMaker 调试器支持 Apache MXNet、 PyTorch TensorFlow、和框架。 XGBoost 有关 D SageMaker ebugger 支持的可用框架和版本的更多信息，请参阅[支持的框架和算法](debugger-supported-frameworks.md)。

![\[Amazon SageMaker 调试器的工作原理概述。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-main.png)


Debugger 工作流概述如下：

1. 如果需要，可以使用 `sagemaker-debugger` Python SDK 修改您的训练脚本。

1. 使用 SageMaker 调试器配置 SageMaker 训练作业。
   + 使用 SageMaker AI 估算器 API 进行配置（适用于 Python SDK）。
   + 使用 SageMaker AI [`CreateTrainingJob`请求进行配置（适用于 Boto3 或 CLI](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-createtrainingjob-api.html)）。
   + 使用 SageMaker 调试器配置[自定义训练容](debugger-bring-your-own-container.md)器。

1. 启动训练作业并实时监控训练问题。
   + [Debugger 内置规则列表](debugger-built-in-rules.md).

1. 获取警报并针对训练问题迅速采取措施。
   + 使用 [为规则使用 Debugger 内置操作](debugger-built-in-actions.md)，在发现训练问题时接收短信和电子邮件并停止训练作业。
   + 使用 [Amazon Ev CloudWatch ents 设置您自己的操作，然后 AWS Lambda](debugger-cloudwatch-lambda.md).

1. 探索对训练问题的深入分析。
   + 有关调试模型输出张量的信息，请参阅[在中可视化调试器输出张量 TensorBoard](debugger-enable-tensorboard-summaries.md)。

1. 修复问题，考虑 Debugger 提供的建议，然后重复步骤 1-5，直到模型得到优化并达到目标准确性。

《 SageMaker 调试器开发者指南》将引导您完成以下主题。

**Topics**
+ [Amazon SageMaker 调试器功能](#debugger-features)
+ [支持的框架和算法](debugger-supported-frameworks.md)
+ [Amazon SageMaker 调试器架构](debugger-how-it-works.md)
+ [Debugger 教程](debugger-tutorial.md)
+ [使用 Amazon 调试 SageMaker 器调试训练作业](debugger-debug-training-jobs.md)
+ [Debugger 内置规则列表](debugger-built-in-rules.md)
+ [使用 Debugger 客户端库创建自定义规则](debugger-custom-rules.md)
+ [使用 Debugger 和自定义训练容器](debugger-bring-your-own-container.md)
+ [使用 SageMaker API 配置调试器](debugger-createtrainingjob-api.md)
+ [Amazon SageMaker 调试器参考资料](debugger-reference.md)

# 支持的框架和算法
<a name="debugger-supported-frameworks"></a>

下表显示了 Debugger 支持的 SageMaker AI 机器学习框架和算法。


| 
| 
| **SageMaker AI-supported frameworks and algorithms** |  **Debugging output tensors**  | 
| --- |--- |
|  [TensorFlow](https://sagemaker.readthedocs.io/en/stable/using_tf.html)   |  [AWS TensorFlow 深度学习容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#general-framework-containers) 1.15.4 或更高版本  | 
|  [PyTorch](https://sagemaker.readthedocs.io/en/stable/using_pytorch.html)  |  [AWS PyTorch 深度学习容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#general-framework-containers) 1.5.0 或更高版本  | 
|  [MXNet](https://sagemaker.readthedocs.io/en/stable/using_mxnet.html)   |  [AWS MXNet 深度学习容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#general-framework-containers) 1.6.0 或更高版本  | 
|  [XGBoost](https://sagemaker.readthedocs.io/en/stable/frameworks/xgboost/using_xgboost.html)  |  1.0-1、1.2-1、1.3-1  | 
|  [SageMaker AI 通用估算器](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html)  |  [自定义训练容器](debugger-bring-your-own-container.md)（可用于 TensorFlow PyTorch、 MXNet、 XGBoost 和手动挂钩注册）  | 
+ **调试输出张量** – 跟踪和调试模型参数，例如训练作业的权重、梯度、偏差和标量值。可用的深度学习框架有 Apache MXNet TensorFlow、 PyTorch、和。 XGBoost
**重要**  
对于带有 Keras 的 TensorFlow 框架， SageMaker Debugger 弃用了对使用 2.6 及更高版本`tf.keras`模块构建的调试模型的 TensorFlow 零代码更改支持。这是由于 [TensorFlow 2.6.0 发行](https://github.com/tensorflow/tensorflow/releases/tag/v2.6.0)说明中宣布的重大变更所致。有关如何更新训练脚本的说明，请参阅[调整您的 TensorFlow 训练脚本](debugger-modify-script-tensorflow.md)。
**重要**  
从 PyTorch v1.12.0 及更高版本开始， SageMaker Debugger 弃用了对调试模型的零代码更改支持。  
这是由于重大更改导致 SageMaker 调试器干扰`torch.jit`功能。有关如何更新训练脚本的说明，请参阅[调整您的 PyTorch 训练脚本](debugger-modify-script-pytorch.md)。

如果您要训练和调试的框架或算法未在表中列出，请前往[AWS 讨论论坛](https://forums.aws.amazon.com/)并在 D SageMaker ebugger 上留下反馈。

## AWS 区域
<a name="debugger-support-aws-regions"></a>

Amazon SageMaker Debugger 在使用 Amazon A SageMaker I 的所有地区都可用，但以下区域除外。
+ 亚太地区（雅加达）：`ap-southeast-3`

要了解您的 Amazon SageMaker AI 是否已在 AWS 区域使用，请参阅[AWS 区域服务](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。

## 将 Debugger 与自定义训练容器配合使用
<a name="debugger-byoc-intro"></a>

使用调试器将您的训练容器引入 SageMaker AI，并深入了解您的训练作业。使用监控和调试功能，在 Amazon EC2 实例上优化模型，最大限度地提高工作效率。

有关如何使用 `sagemaker-debugger` 客户端库构建训练容器、将其推送到 Amazon Elastic Container Registry (Amazon ECR)，然后进行监控和调试的更多信息，请参阅[使用 Debugger 和自定义训练容器](debugger-bring-your-own-container.md)。

## 调试器开源存储库 GitHub
<a name="debugger-opensource"></a>

调试 APIs 器通过 SageMaker Python SDK 提供，旨在为 SageMaker AI 和 [ DescribeTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html)API 操作构造调试器挂钩[ CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)和规则配置。`sagemaker-debugger` 客户端库提供工具用于注册*钩子*，并通过其*试验*功能访问训练数据，所有这些都通过灵活而强大的 API 操作来实现。它在 Python 3.6 及更高版本 XGBoost 上支持机器学习框架 TensorFlow PyTorch MXNet、、和。

有关直接介绍 Debugger 和 `sagemaker-debugger` API 操作的资源，请参阅以下链接：
+ [亚马逊 SageMaker Python 软件开发工具包文档](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_debugger.html)
+ [亚马逊 SageMaker Python 软件开发工具包——调试器 APIs](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html)
+ [Amaz `sagemaker-debugger` on D SageMaker ebugger 开源客户端库的](https://github.com/awslabs/sagemaker-debugger#amazon-sagemaker-debugger) [Python 软件开发工具包文档](https://sagemaker-debugger.readthedocs.io/en/website/index.html)
+ [`sagemaker-debugger` PyPI](https://pypi.org/project/smdebug/)

如果您使用适用于 Java 的 SDK 执行 SageMaker 训练作业并想要配置调试器 APIs，请参阅以下参考资料：
+ [Amazon SageMaker 调试器 APIs](debugger-reference.md#debugger-apis)
+ [使用 SageMaker API 配置调试器](debugger-createtrainingjob-api.md)

# Amazon SageMaker 调试器架构
<a name="debugger-how-it-works"></a>

本主题将引导您详细了解 Amazon SageMaker Debugger 工作流程。

Debugger 支持用于*性能优化*的分析功能，以识别计算问题，例如系统瓶颈和利用率不足，并协助大规模优化硬件资源利用率。

Debugger 用于*模型优化*的调试功能用来分析可能出现的不收敛训练问题，在使用优化算法尽可能减少损失函数时可能会出现此类问题，例如梯度下降及其变化。

下图显示了 SageMaker 调试器的架构。带有粗边界线的方框是 Debugger 管理的内容，用来分析您的训练作业。

![\[Amazon SageMaker 调试器的工作原理概述。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger_new_diagram.png)


Debugger 将来自训练作业的以下数据存储在安全的 Amazon S3 存储桶中：
+ **输出张量** – 在训练 ML 模型时，在向前和向后传递期间不断更新的标量和模型参数的集合。输出张量包括标量值（准确性和损失）和矩阵（权重、梯度、输入层和输出层）。
**注意**  
默认情况下，调试器监视和调试 SageMaker 训练作业，而无需在 AI 估算器中配置任何调试器特定的参数。 SageMaker Debugger 每 500 毫秒收集一次系统指标，每 500 个步骤收集一次基本输出张量（损耗和精度等标量输出）。它还运行 `ProfilerReport` 规则来分析系统指标并聚合 Studio Debugger Insights 控制面板和分析报告。Debugger 将输出数据保存在安全的 Amazon S3 存储桶中。

Debugger 内置规则在处理容器上运行，设计为通过处理在 S3 存储桶中收集的训练数据来评估机器学习模型（请参阅[处理数据和评估模型](https://docs.aws.amazon.com//sagemaker/latest/dg/processing-job.html)）。内置规则完全由 Debugger 管理。您也可以创建根据自己的模型自定义的规则，来监控您所关注的任何问题。

# Debugger 教程
<a name="debugger-tutorial"></a>

以下主题将引导您完成从基础知识到高级使用案例的各个教程，了解如何使用 Debugger 来监控、分析和调试 SageMaker 训练作业。探索 Debugger 功能，了解如何使用 Debugger 高效地调试和改进机器学习模型。

**Topics**
+ [Debugger 教程视频](debugger-videos.md)
+ [Debugger 示例笔记本](debugger-notebooks.md)
+ [Debugger 高级演示和可视化](debugger-visualization.md)

# Debugger 教程视频
<a name="debugger-videos"></a>

以下视频介绍了使用 SageMaker Studio 和 A SageMaker I 笔记本实例的 Amazon SageMaker 调试器功能。

**Topics**
+ [在 Studio Classic 中使用亚马逊 SageMaker 调试器调试模型](#debugger-video-get-started)
+ [深入了解 Amazon SageMaker Debugger 和 SageMaker AI 模型监视器](#debugger-video-dive-deep)

## 在 Studio Classic 中使用亚马逊 SageMaker 调试器调试模型
<a name="debugger-video-get-started"></a>

* AWS 技术传播者朱利安·西蒙 \$1 时长：14 分 17 秒*

本教程视频演示了如何使用 Amazon SageMaker Debugger 捕获和检查训练模型中的调试信息。本视频中使用的示例训练模型是一个基于带有后端的 Keras 的简单卷积神经网络 (CNN)。 TensorFlow SageMaker TensorFlow 框架中的 AI 和调试器使您能够使用训练脚本直接构建估算器并调试训练作业。

[![AWS Videos](http://img.youtube.com/vi/https://www.youtube.com/embed/MqPdTj0Znwg/0.jpg)](http://www.youtube.com/watch?v=https://www.youtube.com/embed/MqPdTj0Znwg)


您可以在作者提供的[该 Studio 演示存储库](https://gitlab.com/juliensimon/amazon-studio-demos/-/tree/master)中找到该视频中的示例笔记本。您需要将`debugger.ipynb`笔记本文件和`mnist_keras_tf.py`训练脚本克隆到 SageMaker Studio 或 SageMaker 笔记本实例。在克隆这两个文件后，请指定 `debugger.ipynb` 笔记本中的 `mnist_keras_tf.py` 文件的 `keras_script_path` 路径。例如，如果您将两个文件克隆到同一目录中，请将其设置为 `keras_script_path = "mnist_keras_tf.py"`。

## 深入了解 Amazon SageMaker Debugger 和 SageMaker AI 模型监视器
<a name="debugger-video-dive-deep"></a>

* AWS 技术传播者朱利安·西蒙 \$1 时长：44 分 34 秒*

本视频会议探讨了调试器和 SageMaker 模型监视器的高级功能，这些功能有助于提高工作效率和模型质量。首先，此视频说明了如何使用 Debugger 检测和修复训练问题，对张量进行可视化以及改进模型。接下来，在 22:41，视频展示了如何使用 SageMaker AI Model Monitor 监控生产中的模型并识别预测问题，例如缺少特征或数据漂移。最后，它提供了成本优化技巧，以帮助您充分利用机器学习预算。

[![AWS Videos](http://img.youtube.com/vi/https://www.youtube.com/embed/0zqoeZxakOI/0.jpg)](http://www.youtube.com/watch?v=https://www.youtube.com/embed/0zqoeZxakOI)


您可以在作者提供的此 [AWS Dev Days 2020 存储库](https://gitlab.com/juliensimon/awsdevdays2020/-/tree/master/mls1)中找到视频中的示例笔记本。

# Debugger 示例笔记本
<a name="debugger-notebooks"></a>

SageMaker [aws/ amazon-sagemaker-examples](https://github.com/aws/amazon-sagemaker-examples) 存储库中提供了@@ [调试器示例笔记本](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/)。Debugger 示例笔记本将引导您完成调试和分析训练作业的基本到高级使用场景。

我们建议您在 SageMaker Studio 或笔记本实例上运行示例 SageMaker 笔记本，因为大多数示例都是为 SageMaker 人工智能生态系统中的训练任务而设计的，包括亚马逊 EC2、Amazon S3 和 Amaz SageMaker on Python SDK。

要将示例存储库克隆到 SageMaker Studio，请按照 [Amazon SageMaker Studio Tour](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-studio-end-to-end.html) 中的说明进行操作。

**重要**  
要使用新的调试器功能，你需要升级 SageMaker Python SDK 和`SMDebug`客户端库。在你的 IPython 内核、Jupyter Notebook JupyterLab 或环境中，运行以下代码来安装最新版本的库并重新启动内核。  

```
import sys
import IPython
!{sys.executable} -m pip install -U sagemaker smdebug
IPython.Application.instance().kernel.do_shutdown(True)
```

## 用于剖析训练作业的 Debugger 示例笔记本
<a name="debugger-notebooks-profiling"></a>

以下列表显示了 Debugger 示例笔记本，其中介绍了 Debugger 的调整功能，用于监控并分析各种机器学习模型、数据集和框架的训练作业。


| 笔记本标题 | 框架 | 模型 | 数据集 | 说明 | 
| --- | --- | --- | --- | --- | 
|  [Amazon SageMaker 调试器分析数据分析](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/debugger_interactive_analysis_profiling/interactive_analysis_profiling_data.html)  |  TensorFlow  |  Keras 50 ResNet  | Cifar-10 |  本笔记本介绍了 Deb SageMaker ugger 捕获的分析数据的交互式分析。探索 `SMDebug` 交互式分析工具的全部功能。  | 
|  [使用 Amazon D SageMaker ebugger 分析机器学习训练](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_nlp_sentiment_analysis/sentiment-analysis-tf-distributed-training-bringyourownscript.html)  |  TensorFlow  |  1-D 卷积神经网络  |  IMDB 数据集  |  对 TensorFlow 一维CNN进行分析，对IMDB数据进行情感分析，该数据由标有正面或负面情绪的电影评论组成。浏览 Studio Debugger Insights 和 Debugger 分析报告。  | 
|  [使用各种分布式训练设置分析 TensorFlow ResNet 模型训练](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/tensorflow_profiling)  |  TensorFlow  | ResNet50 | Cifar-10 |  使用各种分布式 TensorFlow 训练设置运行训练作业，监控系统资源利用率，并使用调试器分析模型性能。  | 
|  [使用各种分布式训练设置分析 PyTorch ResNet 模型训练](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/pytorch_profiling)   | PyTorch |  ResNet50  | Cifar-10 |  使用各种分布式 PyTorch 训练设置运行训练作业，监控系统资源利用率，并使用调试器分析模型性能。  | 

## 用于剖析模型参数的 Debugger 示例笔记本
<a name="debugger-notebooks-debugging"></a>

以下列表用于展示 Debugger 示例笔记本，介绍了 Debugger 的调整功能，用于调试各种机器学习模型、数据集和框架的训练作业。


| 笔记本标题 | 框架 | 模型 | 数据集 | 说明 | 
| --- | --- | --- | --- | --- | 
|  [Amazon SageMaker 调试器-使用内置规则](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/tensorflow_builtin_rule)  |  TensorFlow  |  卷积神经网络  | MNIST |  使用 Amazon SageMaker 调试器内置规则调试 TensorFlow模型。  | 
|  [亚马逊 SageMaker 调试器-Tensorflow 2.1](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/tensorflow2)  |  TensorFlow  |  ResNet50  | Cifar-10 |  使用 Amazon SageMaker Debugger 挂钩配置和内置规则，使用 Tensorflow 2.1 框架调试模型。  | 
|  [可视化训练的调试张量 MXNet](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mnist_tensor_plot)  |  MXNet  |  Gluon 卷积神经网络  | Fashion MNIST |  运行训练作业并配置 SageMaker Debugger 以存储此作业中的所有张量，然后在笔记本中可视化这些张量。  | 
|  [使用 Amazon SageMaker 调试器启用现场训练](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mxnet_spot_training)   | MXNet |  Gluon 卷积神经网络  | Fashion MNIST |  了解 Debugger 如何从在竞价型实例上训练的作业中收集张量数据，以及如何使用 Debugger 内置规则进行托管式竞价型实例训练。  | 
| [解释使用 Amazon D SageMaker ebugger 预测个人收入的 XGBoost 模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/xgboost_census_explanations/xgboost-census-debugger-rules.html) | XGBoost |  XGBoost 回归  |  [成人普查数据集](https://archive.ics.uci.edu/ml/datasets/adult)  | 学习如何使用调试器挂钩和内置规则从 XGBoost 回归模型中收集和可视化张量数据，例如损失值、特征和 SHAP 值。 | 

要查找模型参数和使用场景的高级可视化对象，请参阅下个主题 [Debugger 高级演示和可视化](debugger-visualization.md)。

# Debugger 高级演示和可视化
<a name="debugger-visualization"></a>

以下演示将引导您了解使用 Debugger 的高级应用场景和可视化脚本。

**Topics**
+ [使用 Amazon SageMaker 实验和调试器训练和修剪模型](#debugger-visualization-video-model-pruning)
+ [[使用 SageMaker Debugger 监控卷积自动编码器模型训练](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/model_specific_realtime_analysis/autoencoder_mnist/autoencoder_mnist.html)](#debugger-visualization-autoencoder_mnist)
+ [[使用 SageMaker 调试器监控 BERT 模型训练中的注意力](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/model_specific_realtime_analysis/bert_attention_head_view/bert_attention_head_view.html)](#debugger-visualization-bert_attention_head_view)
+ [[使用 SageMaker 调试器可视化卷积神经网络中的类激活地图 () CNNs](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/model_specific_realtime_analysis/cnn_class_activation_maps/cnn_class_activation_maps.html)](#debugger-visualization-cnn_class_activation_maps)

## 使用 Amazon SageMaker 实验和调试器训练和修剪模型
<a name="debugger-visualization-video-model-pruning"></a>

* AWS 应用科学家 Nathalie Rauschmayr 博士 \$1 时长：49 分 26 秒*

[![AWS Videos](http://img.youtube.com/vi/https://www.youtube.com/embed/Tnv6HsT1r4I/0.jpg)](http://www.youtube.com/watch?v=https://www.youtube.com/embed/Tnv6HsT1r4I)


了解 Amazon SageMaker 实验和调试器如何简化训练作业的管理。Amazon SageMaker Debugger 提供对训练作业的透明可见性，并将训练指标保存到您的 Amazon S3 存储桶中。 SageMaker 实验使您可以通过 SageMaker Studio 将训练信息作为*试*用调用，并支持训练作业的可视化。这有助于保持高质量的模型，同时根据重要性排名来减少不太重要的参数。

本视频演示了一种*模型修剪*技术，该技术使预训练的 ResNet 50 和 AlexNet 模型更轻、更实惠，同时保持模型精度的高标准。

SageMaker AI Estimator 在带有 PyTorch 框架的 Dee AWS p Learning Containers 中训练 PyTorch 模型库中提供的算法，Debugger 则从训练过程中提取训练指标。

该视频还演示了如何设置调试器自定义规则，以观察修剪后的模型的精度，在精度达到阈值时触发 Amazon CloudWatch 事件和 AWS Lambda 函数，以及如何自动停止修剪过程以避免冗余迭代。

学习目标如下：
+  学习如何使用 SageMaker AI 来加速 ML 模型训练并提高模型质量。
+  通过自动捕获输入参数、配置和结果，了解如何使用 SageMaker 实验管理训练迭代。
+  了解 Debugger 如何通过自动从卷积神经网络的权重、梯度和激活输出等指标中捕获实时张量数据，使训练过程变得透明。
+ 用于 CloudWatch 在调试器发现问题时触发 Lambda。
+  使用 SageMaker 实验和调试器掌握 SageMaker 训练过程。

你可以从 D [SageMaker ebugger I PyTorch terative Model](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/pytorch_iterative_model_pruning) Pruning 中找到此视频中使用的笔记本和训练脚本。

下图显示了迭代模型修剪过程如何根据激活输出和梯度评估的重要性 AlexNet 等级剪掉 100 个最不重要的滤波器，从而减小的大小。

修剪过程将最初的 5000 万个参数减少到 1800 万个。它还将估计的模型大小从 201 MB 减少到 73 MB。

![\[包含模型修剪结果输出可视化效果的图像\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-model-pruning-results-alexnet.gif)


您还需要跟踪模型精度，下图显示了如何绘制模型修剪过程，以便根据 Studio 中的 SageMaker 参数数量可视化模型精度的变化。

![\[在 Studio 中使用调试器实现张量可视化的图像 SageMaker\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-model-pruning-studio.png)


**在 SageMaker Studio 中，选择 “**实验**” 选项卡，从修剪过程中选择 Debugger 保存的张量列表，然后编写 “试用组件列表” 面板。**选择所有 10 个迭代，然后选择**添加图表**以创建**试验组件图表**。在确定了要部署的模型之后，选择试验组件并选择菜单以执行操作，或者选择**部署模型**。

**注意**  
要使用以下笔记本示例通过 SageMaker Studio 部署模型，请在`train.py`脚本的`train`函数末尾添加一行。  

```
# In the train.py script, look for the train function in line 58.
def train(epochs, batch_size, learning_rate):
    ...
        print('acc:{:.4f}'.format(correct/total))
        hook.save_scalar("accuracy", correct/total, sm_metric=True)

    # Add the following code to line 128 of the train.py script to save the pruned models
    # under the current SageMaker Studio model directory
    torch.save(model.state_dict(), os.environ['SM_MODEL_DIR'] + '/model.pt')
```

## [使用 SageMaker Debugger 监控卷积自动编码器模型训练](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/model_specific_realtime_analysis/autoencoder_mnist/autoencoder_mnist.html)
<a name="debugger-visualization-autoencoder_mnist"></a>

本笔记本演示了 SageMaker Debugger 如何在 MNIST 手写数字图像数据集上可视化来自无监督（或自监督）学习过程的张量。

本笔记本中的训练模型是带有框架的卷积自动编码器。 MXNet卷积自动编码器具有瓶颈形状的卷积神经网络，由编码器部分和解码器部分组成。

此示例中的编码器具有两个卷积层，以生成输入图像的压缩表示（潜在变量）。在这种情况下，编码器从大小（28，28）的原始输入图像中生成大小（1，20）的潜在变量，并显著减少训练数据的大小达 40 倍。

解码器有两个*解卷积*层，并通过重建输出图像来确保潜在变量保留关键信息。

卷积编码器支持具有较小输入数据大小的聚类算法，并可提升聚类算法（例如 k-means、k-NN 和 t-Distributed Stochastic Neighbor (t-SNE) 嵌入）的性能。

此笔记本示例演示如何使用 Debugger 来可视化潜在变量，如下面的动画所示。它还演示 t-SNE 算法如何将潜在变量分为十个聚类并将它们投影到二维空间中。图像右侧的散点图颜色方案反映了真实值，以显示 BERT 模型和 t-SNE 算法将潜在变量组织到聚类中的程度。

![\[卷积自动编码器的概念图\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-cnn-autoencoder-plot.gif)


## [使用 SageMaker 调试器监控 BERT 模型训练中的注意力](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/model_specific_realtime_analysis/bert_attention_head_view/bert_attention_head_view.html)
<a name="debugger-visualization-bert_attention_head_view"></a>

来自转换器的双向编码表示 (BERT) 是一种语言表示模型。正如模型名称所反映的那样，BERT 模型建立在用于自然语言处理 (NLP) 的*迁移学习*和*转换器模型*之上。

BERT 模型接受了不受监督任务的预训练，例如，预测句子中缺失的单词或预测自然接在前一个句子之后的下一个句子。训练数据包含 33 亿个单词（凭排）的英文文本，如维基百科和电子书籍。对于一个简单的例子，BERT 模型可以高度*注意*来自主题令牌的适当动词令牌或代词令牌。

预训练的 BERT 模型可以通过额外的输出层进行微调，以实现 NLP 任务中的 state-of-the-art模型训练，例如自动回答问题、文本分类等。

Debugger 从微调过程中收集张量。在 NLP 的上下文下，神经元的权重被称为*注意力*。

本笔记本演示了如何在斯坦福问答数据集中使用 [GluonNLP 模型库中的预训练的 BERT 模型](https://gluon-nlp.mxnet.io/model_zoo/bert/index.html)，以及如何 SageMaker 设置 Debugger 来监控训练作业。

在查询和关键向量中绘制*注意力分数*和各个神经元有助于识别模型预测不正确的原因。借助 SageMaker AI Debugger，您可以检索张量，并在训练*进行时实时绘制注意力头部视图*，并了解模型正在学习什么。

下面的动画显示在笔记本示例中提供的训练作业中十次迭代的前 20 个输入标记的注意力分数。

![\[注意力分数的动画\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-attention_scores.gif)


## [使用 SageMaker 调试器可视化卷积神经网络中的类激活地图 () CNNs](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/model_specific_realtime_analysis/cnn_class_activation_maps/cnn_class_activation_maps.html)
<a name="debugger-visualization-cnn_class_activation_maps"></a>

本笔记本演示了如何使用 SageMaker Debugger 绘制用于卷积神经网络中图像检测和分类的类激活地图 ()。CNNs在深度学习中，*卷积神经网络（CNN 或 ConvNet）*是一类深度神经网络，最常用于分析视觉图像。采用类激活图的应用之一是自动驾驶汽车，此应用需要对图像进行即时检测和分类，如交通标志、道路和障碍物。

在本笔记本中， PyTorch ResNet 模型使用[德国交通标志数据集进行训练，该数据集](http://benchmark.ini.rub.de/)包含40多类与交通相关的物体，总共超过50,000张图像。

![\[CNN 类激活图的动画\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-cnn-class-activation-maps.gif)


在训练过程中， SageMaker Debugger 会收集张量以实时绘制类激活地图。如动画图像所示，类激活图（也称为*显著图*）以红色突出显示具有高激活率的区域。

使用 Debugger 捕获的张量，您可以直观查看激活图在模型训练期间的演变。在训练作业开始时，模型首先检测左下角的边缘。随着训练进行，焦点转移到中心并检测限速标志，模型成功地将输入图像预测为类别 3，这是限速 60km/h 标志的类别，置信度为 97%。

# 使用 Amazon 调试 SageMaker 器调试训练作业
<a name="debugger-debug-training-jobs"></a>

要准备训练脚本并使用调试 SageMaker 器运行训练作业以调试模型训练进度，您需要遵循典型的两步过程：使用 Python SDK 修改训练脚本，然后使用 `sagemaker-debugger` Python SDK 构建 A SageMaker I 估算器。 SageMaker 浏览以下主题，学习如何使用 SageMaker 调试器的调试功能。

**Topics**
+ [调整训练脚本，注册钩子](debugger-modify-script.md)
+ [使用 SageMaker Python SDK 使用调试器启动训练作业](debugger-configuration-for-debugging.md)
+ [SageMaker 的调试器交互式报告 XGBoost](debugger-report-xgboost.md)
+ [Amazon 上的操作 SageMaker 调试器规则](debugger-action-on-rules.md)
+ [在中可视化 Amazon SageMaker Debugger 输出张量 TensorBoard](debugger-enable-tensorboard-summaries.md)

# 调整训练脚本，注册钩子
<a name="debugger-modify-script"></a>

Amazon D SageMaker ebugger 附带了一个名为 [`sagemaker-debugger`Python SDK](https://sagemaker-debugger.readthedocs.io/en/website) 的客户端库。`sagemaker-debugger` Python SDK 提供了用于在训练之前调整训练脚本的工具，以及在训练后使用的分析工具。在本页面中，您将学习如何使用客户端库调整训练脚本。

`sagemaker-debugger` Python SDK 提供了包装器，可协助注册钩子来提取模型张量，而无需更改训练脚本。要开始收集模型输出张量并对其进行调试以发现训练问题，请在训练脚本中进行以下修改。

**提示**  
在按照本页面的说明操作时，请使用 [`sagemaker-debugger` 开源 SDK 文档](https://sagemaker-debugger.readthedocs.io/en/website/index.html)获取 API 参考。

**Topics**
+ [调整您的 PyTorch 训练脚本](debugger-modify-script-pytorch.md)
+ [调整您的 TensorFlow 训练脚本](debugger-modify-script-tensorflow.md)

# 调整您的 PyTorch 训练脚本
<a name="debugger-modify-script-pytorch"></a>

要开始收集模型输出张量并调试训练问题，请对 PyTorch 训练脚本进行以下修改。

**注意**  
SageMaker 调试器无法从 [https://pytorch.org/docs/stable/nn.functional.html](https://pytorch.org/docs/stable/nn.functional.html)API 操作中收集模型输出张量。在编写 PyTorch 训练脚本时，建议改用这些[https://pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html](https://pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html)模块。

## 对于 PyTorch 1.12.0
<a name="debugger-modify-script-pytorch-1-12-0"></a>

如果您带上 PyTorch 训练脚本，则可以在训练脚本中使用几行额外的代码来运行训练作业并提取模型输出张量。你需要在`sagemaker-debugger`客户端库 APIs中使用[挂钩](https://sagemaker-debugger.readthedocs.io/en/website/hook-api.html)。仔细阅读以下说明，这些说明分别介绍了各个步骤并提供代码示例。

1. 创建钩子。

   **（推荐）用于 SageMaker AI 内部的训练作业**

   ```
   import smdebug.pytorch as smd
   hook=smd.get_hook(create_if_not_exists=True)
   ```

   当您在估算器中[使用 SageMaker Python SDK 使用调试器启动训练作业](debugger-configuration-for-debugging.md)使用任何 DebuggerHookConfig TensorBoardConfig、或规则启动训练作业时， SageMaker AI 会向您的训练实例添加一个 JSON 配置文件，该文件由该`get_hook`函数获取。请注意，如果您在估算器 APIs 中不包含任何配置，则不会有配置文件可供钩子查找，并且函数会返回。`None`

   **（可选）用于在 SageMaker AI 之外训练作业**

   如果您在本地模式下直接在 SageMaker 笔记本实例、Amazon EC2 实例或您自己的本地设备上运行训练作业，请使用`smd.Hook`类来创建挂钩。但是，这种方法只能存储张量集合并可用于可 TensorBoard 视化。 SageMaker 调试器的内置规则不适用于本地模式，因为这些规则要求 SageMaker AI ML 训练实例和 S3 实时存储来自远程实例的输出。在这种情况下，`smd.get_hook` API 会返回 `None`。

   如果您要创建手动钩子以在本地模式下保存张量，请使用以下带有逻辑的代码片段检查 `smd.get_hook` API 是否返回 `None`，并使用 `smd.Hook` 类创建手动钩子。请注意，您可以指定本地计算机中的任何输出目录。

   ```
   import smdebug.pytorch as smd
   hook=smd.get_hook(create_if_not_exists=True)
   
   if hook is None:
       hook=smd.Hook(
           out_dir='/path/to/your/local/output/',
           export_tensorboard=True
       )
   ```

1. 用钩子的类方法包装您的模型。

   `hook.register_module()` 方法获取您的模型并遍历每一层，寻找与您通过 [使用 SageMaker Python SDK 使用调试器启动训练作业](debugger-configuration-for-debugging.md) 中配置提供的正则表达式匹配的任何张量。通过这种钩子方法可以收集到的张量包括权重、偏差、激活、梯度、输入和输出。

   ```
   hook.register_module(model)
   ```
**提示**  
如果您从大型深度学习模型中完整地收集输出张量，则这些集合的总大小会呈指数级增长，并可能导致瓶颈。如果您要保存特定张量，还可以使用 `hook.save_tensor()` 方法。此方法可协助您为特定张量选取变量，并保存到您自己命名的自定义集合中。有关更多信息，请参阅本说明中的[步骤 7](#debugger-modify-script-pytorch-save-custom-tensor)。

1. 用钩子的类方法包装损失函数。

   `hook.register_loss` 方法用于包装损失函数。它会根据您在 [使用 SageMaker Python SDK 使用调试器启动训练作业](debugger-configuration-for-debugging.md) 的配置中设置的 `save_interval` 来提取损失值，并将它们保存到 `"losses"` 集合中。

   ```
   hook.register_loss(loss_function)
   ```

1. 在训练块中添加 `hook.set_mode(ModeKeys.TRAIN)`。这表示张量集合是在训练阶段中提取的。

   ```
   def train():
       ...
       hook.set_mode(ModeKeys.TRAIN)
   ```

1. 在验证块中添加 `hook.set_mode(ModeKeys.EVAL)`。这表示张量集合是在验证阶段中提取的。

   ```
   def validation():
       ...
       hook.set_mode(ModeKeys.EVAL)
   ```

1. 使用 [https://sagemaker-debugger.readthedocs.io/en/website/hook-constructor.html#smdebug.core.hook.BaseHook.save_scalar](https://sagemaker-debugger.readthedocs.io/en/website/hook-constructor.html#smdebug.core.hook.BaseHook.save_scalar) 保存自定义标量。您可以保存模型中没有的标量值。例如，如果您要记录评估期间计算的准确性值，请在计算准确性的行下方添加以下代码行。

   ```
   hook.save_scalar("accuracy", accuracy)
   ```

   请注意，您需要提供字符串作为第一个参数，用于命名自定义标量集合。这个名称将用于可视化中的标量值 TensorBoard，可以是任何你想要的字符串。

1. <a name="debugger-modify-script-pytorch-save-custom-tensor"></a>使用 [https://sagemaker-debugger.readthedocs.io/en/website/hook-constructor.html#smdebug.core.hook.BaseHook.save_tensor](https://sagemaker-debugger.readthedocs.io/en/website/hook-constructor.html#smdebug.core.hook.BaseHook.save_tensor) 保存自定义张量。与 [https://sagemaker-debugger.readthedocs.io/en/website/hook-constructor.html#smdebug.core.hook.BaseHook.save_scalar](https://sagemaker-debugger.readthedocs.io/en/website/hook-constructor.html#smdebug.core.hook.BaseHook.save_scalar) 类似，您可以保存其他张量，并定义自己的张量集合。例如，您可以提取传入模型的输入映像数据，并通过添加以下代码行，将其保存为自定义张量，其中 `"images"` 是自定义张量的示例名称，`image_inputs` 是输入映像数据的示例变量。

   ```
   hook.save_tensor("images", image_inputs)
   ```

   请注意，您必须向第一个参数提供字符串来命名自定义张量。`hook.save_tensor()` 使用第三个参数 `collections_to_write` 来指定张量集合，用于保存自定义张量。默认值为 `collections_to_write="default"`。如果您没有明确指定第三个参数，则自定义张量将保存到 `"default"` 张量集合中。

调整完训练脚本后，继续到 [使用 SageMaker Python SDK 使用调试器启动训练作业](debugger-configuration-for-debugging.md)。

# 调整您的 TensorFlow 训练脚本
<a name="debugger-modify-script-tensorflow"></a>

要开始收集模型输出张量并调试训练问题，请对 TensorFlow 训练脚本进行以下修改。

**创建用于在 SageMaker AI 中训练作业的挂钩**

```
import smdebug.tensorflow as smd

hook=smd.get_hook(hook_type="keras", create_if_not_exists=True)
```

当你开始 SageMaker 训练作业时，这会产生一个挂钩。当您在估算器中[使用 SageMaker Python SDK 使用调试器启动训练作业](debugger-configuration-for-debugging.md)使用任何`DebuggerHookConfig``TensorBoardConfig`、或`Rules`启动训练作业时， SageMaker AI 会向您的训练实例添加一个 JSON 配置文件，该文件由该`smd.get_hook`方法获取。请注意，如果您在估算器 APIs 中不包含任何配置，则不会有配置文件可供钩子查找，并且函数会返回。`None`

**（可选）创建用于在 SageMaker AI 之外训练作业的挂钩**

如果您在本地模式下直接在 SageMaker 笔记本实例、Amazon EC2 实例或您自己的本地设备上运行训练作业，请使用`smd.Hook`类来创建挂钩。但是，这种方法只能存储张量集合并可用于可 TensorBoard视化。 SageMaker 调试器的内置规则不适用于本地模式。在这种情况下，`smd.get_hook` 方法也会返回 `None`。

如果您要创建手动钩子，请使用以下带有逻辑的代码片段来检查钩子是否返回 `None`，并使用 `smd.Hook` 类创建手动钩子。

```
import smdebug.tensorflow as smd

hook=smd.get_hook(hook_type="keras", create_if_not_exists=True) 

if hook is None:
    hook=smd.KerasHook(
        out_dir='/path/to/your/local/output/',
        export_tensorboard=True
    )
```

添加挂钩创建代码后，继续阅读以下 TensorFlow Keras 主题。

**注意**  
SageMaker 调试器目前仅支持 TensorFlow Keras。

## 在你的 TensorFlow Keras 训练脚本中注册挂钩
<a name="debugger-modify-script-tensorflow-keras"></a>

以下过程介绍如何使用钩子及其方法，从模型和优化器中收集输出标量和张量。

1. 用钩子的类方法包装您的 Keras 模型和优化器。

   `hook.register_model()` 方法获取您的模型并遍历每一层，寻找与您通过 [使用 SageMaker Python SDK 使用调试器启动训练作业](debugger-configuration-for-debugging.md) 中配置提供的正则表达式匹配的任何张量。通过这种钩子方法可以收集到的张量包括权重、偏差和激活。

   ```
   model=tf.keras.Model(...)
   hook.register_model(model)
   ```

1. 用 `hook.wrap_optimizer()` 方法包装优化器。

   ```
   optimizer=tf.keras.optimizers.Adam(...)
   optimizer=hook.wrap_optimizer(optimizer)
   ```

1. 在急切模式下编译模型 TensorFlow。

   要从模型中收集张量，例如每层的输入和输出张量，必须在急切模式下运行训练。否则， SageMaker AI 调试器将无法收集张量。但是，模型权重、偏差和损失等其他张量，无需在急切模式下运行即可收集。

   ```
   model.compile(
       loss="categorical_crossentropy", 
       optimizer=optimizer, 
       metrics=["accuracy"],
       # Required for collecting tensors of each layer
       run_eagerly=True
   )
   ```

1. 将钩子注册到 [https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) 方法。

   要从您注册的钩子中收集张量，请将 `callbacks=[hook]` 添加到 Keras `model.fit()` 类方法中。这会将 `sagemaker-debugger` 钩子作为 Keras 回调传递。

   ```
   model.fit(
       X_train, Y_train,
       batch_size=batch_size,
       epochs=epoch,
       validation_data=(X_valid, Y_valid),
       shuffle=True, 
       callbacks=[hook]
   )
   ```

1. TensorFlow 2.x 仅提供不提供对其值的访问的符号渐变变量。要收集梯度，请使用 [https://sagemaker-debugger.readthedocs.io/en/website/hook-methods.html#tensorflow-specific-hook-api](https://sagemaker-debugger.readthedocs.io/en/website/hook-methods.html#tensorflow-specific-hook-api) 方法包装 `tf.GradientTape`，这要求您如下所示编写自己的训练步骤。

   ```
   def training_step(model, dataset):
       with hook.wrap_tape(tf.GradientTape()) as tape:
           pred=model(data)
           loss_value=loss_fn(labels, pred)
       grads=tape.gradient(loss_value, model.trainable_variables)
       optimizer.apply_gradients(zip(grads, model.trainable_variables))
   ```

   通过对磁带进行包装，`sagemaker-debugger` 钩子可以识别输出张量，例如梯度、参数和损失。封装磁带可确保围绕磁带对象函数`hook.wrap_tape()`的方法（例如、、）将设置 D SageMaker ebugger 的编写器并保存作为输入（可训练变量和损失）和`gradient()`（梯度）的输出`gradient()`（渐变）提供的张量。`push_tape()` `pop_tape()` `gradient()`
**注意**  
要使用自定义训练循环进行收集，请确保使用急切模式。否则， SageMaker 调试器无法收集任何张量。

有关钩子 APIs提供的用于构造`sagemaker-debugger`钩子和保存张量的操作的完整列表，请参阅 *`sagemaker-debugger`Python SDK 文档*中的[钩子方法](https://sagemaker-debugger.readthedocs.io/en/website/hook-methods.html)。

调整完训练脚本后，继续到 [使用 SageMaker Python SDK 使用调试器启动训练作业](debugger-configuration-for-debugging.md)。

# 使用 SageMaker Python SDK 使用调试器启动训练作业
<a name="debugger-configuration-for-debugging"></a>

要使用调试器配置 A SageMaker I 估算器，请使用 Amaz [on Pyth SageMaker on 软件开发工具包](https://sagemaker.readthedocs.io/en/stable)并指定 SageMaker 调试器特定的参数。要充分利用调试功能，需要配置三个参数：`debugger_hook_config`、`tensorboard_output_config` 和 `rules`。

**重要**  
在构造和运行估算器拟合方法以启动训练作业之前，请确保按照[调整训练脚本，注册钩子](debugger-modify-script.md)中的说明调整训练脚本。

## 使用调试器特定的参数构建 SageMaker AI 估算器
<a name="debugger-configuration-structure"></a>

本节中的代码示例展示了如何使用调试器特定的 SageMaker 参数构建 AI 估计器。

**注意**  
以下代码示例是用于构建 SageMaker AI 框架估算器的模板，不能直接执行。您需要继续完成下一个部分中的内容，配置 Debugger 特定的参数。

------
#### [ PyTorch ]

```
# An example of constructing a SageMaker AI PyTorch estimator
import boto3
import sagemaker
from sagemaker.pytorch import PyTorch
from sagemaker.debugger import CollectionConfig, DebuggerHookConfig, Rule, rule_configs

session=boto3.session.Session()
region=session.region_name

debugger_hook_config=DebuggerHookConfig(...)
rules=[
    Rule.sagemaker(rule_configs.built_in_rule())
]

estimator=PyTorch(
    entry_point="directory/to/your_training_script.py",
    role=sagemaker.get_execution_role(),
    base_job_name="debugger-demo",
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="1.12.0",
    py_version="py37",
    
    # Debugger-specific parameters
    debugger_hook_config=debugger_hook_config,
    rules=rules
)

estimator.fit(wait=False)
```

------
#### [ TensorFlow ]

```
# An example of constructing a SageMaker AI TensorFlow estimator
import boto3
import sagemaker
from sagemaker.tensorflow import TensorFlow
from sagemaker.debugger import CollectionConfig, DebuggerHookConfig, Rule, rule_configs

session=boto3.session.Session()
region=session.region_name

debugger_hook_config=DebuggerHookConfig(...)
rules=[
    Rule.sagemaker(rule_configs.built_in_rule()),
    ProfilerRule.sagemaker(rule_configs.BuiltInRule())
]

estimator=TensorFlow(
    entry_point="directory/to/your_training_script.py",
    role=sagemaker.get_execution_role(),
    base_job_name="debugger-demo",
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="2.9.0",
    py_version="py39",
    
    # Debugger-specific parameters
    debugger_hook_config=debugger_hook_config,
    rules=rules
)

estimator.fit(wait=False)
```

------
#### [ MXNet ]

```
# An example of constructing a SageMaker AI MXNet estimator
import sagemaker
from sagemaker.mxnet import MXNet
from sagemaker.debugger import CollectionConfig, DebuggerHookConfig, Rule, rule_configs

debugger_hook_config=DebuggerHookConfig(...)
rules=[
    Rule.sagemaker(rule_configs.built_in_rule())
]

estimator=MXNet(
    entry_point="directory/to/your_training_script.py",
    role=sagemaker.get_execution_role(),
    base_job_name="debugger-demo",
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="1.7.0",
    py_version="py37",
    
    # Debugger-specific parameters
    debugger_hook_config=debugger_hook_config,
    rules=rules
)

estimator.fit(wait=False)
```

------
#### [ XGBoost ]

```
# An example of constructing a SageMaker AI XGBoost estimator
import sagemaker
from sagemaker.xgboost.estimator import XGBoost
from sagemaker.debugger import CollectionConfig, DebuggerHookConfig, Rule, rule_configs

debugger_hook_config=DebuggerHookConfig(...)
rules=[
    Rule.sagemaker(rule_configs.built_in_rule())
]

estimator=XGBoost(
    entry_point="directory/to/your_training_script.py",
    role=sagemaker.get_execution_role(),
    base_job_name="debugger-demo",
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="1.5-1",

    # Debugger-specific parameters
    debugger_hook_config=debugger_hook_config,
    rules=rules
)

estimator.fit(wait=False)
```

------
#### [ Generic estimator ]

```
# An example of constructing a SageMaker AI generic estimator using the XGBoost algorithm base image
import boto3
import sagemaker
from sagemaker.estimator import Estimator
from sagemaker import image_uris
from sagemaker.debugger import CollectionConfig, DebuggerHookConfig, Rule, rule_configs

debugger_hook_config=DebuggerHookConfig(...)
rules=[
    Rule.sagemaker(rule_configs.built_in_rule())
]

region=boto3.Session().region_name
xgboost_container=sagemaker.image_uris.retrieve("xgboost", region, "1.5-1")

estimator=Estimator(
    role=sagemaker.get_execution_role()
    image_uri=xgboost_container,
    base_job_name="debugger-demo",
    instance_count=1,
    instance_type="ml.m5.2xlarge",
    
    # Debugger-specific parameters
    debugger_hook_config=debugger_hook_config,
    rules=rules
)

estimator.fit(wait=False)
```

------

配置以下参数以激活 SageMaker 调试器：
+ `debugger_hook_config`（的对象 [https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.DebuggerHookConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.DebuggerHookConfig)）— 需要在调整后的训练脚本中激活挂钩[调整训练脚本，注册钩子](debugger-modify-script.md)，将 SageMaker 训练启动器（估算器）配置为从训练作业中收集输出张量，然后将张量保存到安全的 S3 存储桶或本地计算机中。要了解如何配置 `debugger_hook_config` 参数，请参阅[配置 SageMaker 调试器以保存张量](debugger-configure-hook.md)。
+ `rules`（[https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.Rule](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.Rule)对象列表）— 配置此参数以激活要实时运行的 SageMaker Debugger 内置规则。内置规则是逻辑，用于自动调试模型的训练进度，并通过分析保存在安全 S3 存储桶中的输出张量来发现训练问题。要了解如何配置 `rules` 参数，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。要查找用于调试输出张量的内置规则的完整列表，请参阅[Debugger 规则](debugger-built-in-rules.md#debugger-built-in-rules-Rule)。如果您想创建自己的逻辑来检测任意训练问题，请参阅[使用 Debugger 客户端库创建自定义规则](debugger-custom-rules.md)。
**注意**  
内置规则只能通过 SageMaker 训练实例使用。您不能在本地模式下使用它们。
+ `tensorboard_output_config`（的对象 [https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.TensorBoardOutputConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.TensorBoardOutputConfig)）— 将 SageMaker Debugger 配置为以 TensorBoard兼容格式收集输出张量并保存到对象中指定的 S3 输出路径。`TensorBoardOutputConfig`要了解更多信息，请参阅[在中可视化 Amazon SageMaker Debugger 输出张量 TensorBoard](debugger-enable-tensorboard-summaries.md)。
**注意**  
`tensorboard_output_config` 必须使用 `debugger_hook_config` 参数进行配置，这还要求您添加 `sagemaker-debugger` 钩子以调整训练脚本。

**注意**  
SageMaker 调试器将输出张量安全地保存在 S3 存储桶的子文件夹中。例如，账户中默认 S3 存储桶 URI 的格式为 `s3://amzn-s3-demo-bucket-sagemaker-<region>-<12digit_account_id>/<base-job-name>/<debugger-subfolders>/`。 SageMaker 调试器创建了两个子文件夹：`debug-output`、和。`rule-output`如果您添加 `tensorboard_output_config` 参数，则还会找到 `tensorboard-output` 文件夹。

请参阅以下主题，查找更多详细说明如何配置 Debugger 特定参数的示例。

**Topics**
+ [使用调试器特定的参数构建 SageMaker AI 估算器](#debugger-configuration-structure)
+ [配置 SageMaker 调试器以保存张量](debugger-configure-hook.md)
+ [如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)
+ [关闭 Debugger](debugger-turn-off.md)
+ [调试器有用的 SageMaker AI 估算器类方法](debugger-estimator-classmethods.md)

# 配置 SageMaker 调试器以保存张量
<a name="debugger-configure-hook"></a>

*张量*是每次训练迭代的向后和向前传递的更新参数的数据集合。 SageMaker 调试器收集输出张量以分析训练作业的状态。 SageMaker 调试器[https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig)和 [https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.DebuggerHookConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.DebuggerHookConfig)API 操作提供了将张量分组为*集合*并将其保存到目标 S3 存储桶的方法。以下主题将介绍如何使用 `CollectionConfig` 和 `DebuggerHookConfig` API 操作，并举例说明如何使用 Debugger 钩子保存、访问和可视化输出张量。

在构造 A SageMaker I 估计器时，通过指定参数来激活 SageMaker 调试器。`debugger_hook_config`以下主题提供的示例说明了如何使用 `CollectionConfig` 和 `DebuggerHookConfig` API 操作设置 `debugger_hook_config`，以从训练作业中提取张量并保存它们。

**注意**  
除非另有说明，否则在正确配置和激活后， SageMaker Debugger 会将输出张量保存在默认 S3 存储桶中。默认 S3 存储桶 URI 的格式为 `s3://amzn-s3-demo-bucket-sagemaker-<region>-<12digit_account_id>/<training-job-name>/debug-output/`。

**Topics**
+ [使用 `CollectionConfig` API 配置张量集合](debugger-configure-tensor-collections.md)
+ [配置 `DebuggerHookConfig` API 以保存张量](debugger-configure-tensor-hook.md)
+ [配置 Debugger 钩子的示例笔记本和代码示例](debugger-save-tensors.md)

# 使用 `CollectionConfig` API 配置张量集合
<a name="debugger-configure-tensor-collections"></a>

使用 `CollectionConfig` API 操作配置张量集合。在使用 Debugger 支持的深度学习框架和机器学习算法时，Debugger 提供预构建的张量集合，涵盖了参数的各种正则表达式 (regex)。如以下示例代码所示，添加要调试的内置张量集合。

```
from sagemaker.debugger import CollectionConfig

collection_configs=[
    CollectionConfig(name="weights"),
    CollectionConfig(name="gradients")
]
```

前面的集合设置 Debugger 钩子基于默认 `"save_interval"` 值，每 500 个步骤保存一次张量值。

有关可用的 Debugger 内置集合的完整列表，请参阅 [Debugger 内置集合](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#collection)。

如果您希望自定义内置集合，例如更改保存时间间隔和张量正则表达式，请使用以下 `CollectionConfig` 模板来调整参数。

```
from sagemaker.debugger import CollectionConfig

collection_configs=[
    CollectionConfig(
        name="tensor_collection",
        parameters={
            "key_1": "value_1",
            "key_2": "value_2",
            ...
            "key_n": "value_n"
        }
    )
]
```

有关可用参数密钥的更多信息，请参阅 [Amaz SageMaker on Python 软件开发工具包[CollectionConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig)](https://sagemaker.readthedocs.io/en/stable)中的。例如，以下代码示例展示了如何调整在训练的不同阶段保存“losses”张量集合的时间间隔：在训练阶段每 100 个步骤保存一次损失，在验证阶段每 10 个步骤保存一次验证损失。

```
from sagemaker.debugger import CollectionConfig

collection_configs=[
    CollectionConfig(
        name="losses",
        parameters={
            "train.save_interval": "100",
            "eval.save_interval": "10"
        }
    )
]
```

**提示**  
此张量集合配置对象既可用于规则 API 操作 [DebuggerHookConfig](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-configure-hook.html#debugger-configure-tensor-hook)，也可用于[规则](https://docs.aws.amazon.com/sagemaker/latest/dg/use-debugger-built-in-rules.html#debugger-built-in-rules-configuration-param-change) API 操作。

# 配置 `DebuggerHookConfig` API 以保存张量
<a name="debugger-configure-tensor-hook"></a>

使用 [DebuggerHookConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html                 #sagemaker.debugger.DebuggerHookConfig)API 使用您在上一步中创建的`collection_configs`对象创建对象。`debugger_hook_config`

```
from sagemaker.debugger import DebuggerHookConfig

debugger_hook_config=DebuggerHookConfig(
    collection_configs=collection_configs
)
```

Debugger 将模型训练输出张量保存到默认 S3 存储桶中。默认 S3 存储桶 URI 的格式为 `s3://amzn-s3-demo-bucket-sagemaker-<region>-<12digit_account_id>/<training-job-name>/debug-output/.`

如果您要指定确切的 S3 存储桶 URI，请使用以下代码示例：

```
from sagemaker.debugger import DebuggerHookConfig

debugger_hook_config=DebuggerHookConfig(
    s3_output_path="specify-uri"
    collection_configs=collection_configs
)
```

有关更多信息，请参阅[亚马逊 SageMaker Python 软件开发工具包[DebuggerHookConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.DebuggerHookConfig)](https://sagemaker.readthedocs.io/en/stable)中的。

# 配置 Debugger 钩子的示例笔记本和代码示例
<a name="debugger-save-tensors"></a>

以下部分提供了如何使用 Debugger 钩子保存、访问并可视化输出张量的笔记本和代码示例。

**Topics**
+ [张量可视化示例笔记本](#debugger-tensor-visualization-notebooks)
+ [使用 Debugger 内置集合保存张量](#debugger-save-built-in-collections)
+ [通过修改 Debugger 内置集合保存张量](#debugger-save-modified-built-in-collections)
+ [使用 Debugger 自定义集合保存张量](#debugger-save-custom-collections)

## 张量可视化示例笔记本
<a name="debugger-tensor-visualization-notebooks"></a>

以下两个笔记本示例演示了 Amazon SageMaker Debugger 在可视化张量方面的高级用法。Debugger 提供了对训练深度学习模型的透明视图。
+ [ SageMaker Studio 笔记本中的交互式张量分析 MXNet](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mnist_tensor_analysis)

  此笔记本示例展示了如何使用 Amazon Deb SageMaker ugger 可视化保存的张量。通过可视化张量，您可以在训练深度学习算法时查看张量值如何变化。本笔记本包含一个神经网络配置不佳的训练作业，它使用 Amazon D SageMaker ebugger 来聚合和分析张量，包括梯度、激活输出和权重。例如，下图显示了出现梯度消失问题的卷积层的梯度分布情况。  
![\[绘制梯度分布图。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-vanishing-gradient.gif)

  该笔记本还说明了正确的初始超参数设置如何生成相同的张量分布图，从而改进了训练过程。
+ [通过模型训练对张量进行可视化和调试 MXNet ](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mnist_tensor_plot)

   此笔记本示例展示了如何使用 Amazon Debugger 保存和可视化 MXNet Gluon SageMaker 模型训练作业中的张量。它说明了 Debugger 设置为将所有张量保存到 Amazon S3 存储桶中，并检索可视化的 ReLu 激活输出。下图显示了 ReLu 激活输出的三维可视化。颜色方案设置为以蓝色表示接近于 0 的值，以黄色表示接近于 1 的值。  
![\[ReLU 激活输出的可视化\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/tensorplot.gif)

  在此笔记本中，从中导入的`TensorPlot`类`tensor_plot.py`旨在绘制以二维图像作为输入的卷积神经网络 (CNNs)。笔记本附带的 `tensor_plot.py` 脚本使用 Debugger 检索张量，并对 CNN 进行可视化。你可以在 SageMaker Studio 上运行这个笔记本来重现张量可视化并实现自己的卷积神经网络模型。
+ [在 SageMaker 笔记本中进行实时张量分析 MXNet](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mxnet_realtime_analysis)

  此示例将指导您安装在 Amazon SageMaker 训练作业中发射张量所需的组件，并在训练运行时使用调试器 API 操作访问这些张量。gluon CNN 模型在 Fashion MNIST 数据集上进行训练。在作业运行期间，您将看到 Debugger 如何从 100 个批次的每个批次中检索第一个卷积层的激活输出并对其进行可视化。此外，它还会向您展示作业完成后如何对权重进行可视化。

## 使用 Debugger 内置集合保存张量
<a name="debugger-save-built-in-collections"></a>

您可以通过 `CollectionConfig` API 使用内置张量集合，并通过 `DebuggerHookConfig` API 保存它们。以下示例说明如何使用调试器挂钩配置的默认设置来构建 A SageMaker I TensorFlow 估计器。您也可以将其用于 MXNet PyTorch、和 XGBoost估算器。

**注意**  
在以下示例代码中，`DebuggerHookConfig` 的 `s3_output_path` 参数可选。如果您未指定，Debugger 会将张量保存在中`s3://<output_path>/debug-output/`，其中`<output_path>`是 SageMaker 训练作业的默认输出路径。例如：  

```
"s3://sagemaker-us-east-1-111122223333/sagemaker-debugger-training-YYYY-MM-DD-HH-MM-SS-123/debug-output"
```

```
import sagemaker
from sagemaker.tensorflow import TensorFlow
from sagemaker.debugger import DebuggerHookConfig, CollectionConfig

# use Debugger CollectionConfig to call built-in collections
collection_configs=[
        CollectionConfig(name="weights"),
        CollectionConfig(name="gradients"),
        CollectionConfig(name="losses"),
        CollectionConfig(name="biases")
    ]

# configure Debugger hook
# set a target S3 bucket as you want
sagemaker_session=sagemaker.Session()
BUCKET_NAME=sagemaker_session.default_bucket()
LOCATION_IN_BUCKET='debugger-built-in-collections-hook'

hook_config=DebuggerHookConfig(
    s3_output_path='s3://{BUCKET_NAME}/{LOCATION_IN_BUCKET}'.
                    format(BUCKET_NAME=BUCKET_NAME, 
                           LOCATION_IN_BUCKET=LOCATION_IN_BUCKET),
    collection_configs=collection_configs
)

# construct a SageMaker TensorFlow estimator
sagemaker_estimator=TensorFlow(
    entry_point='directory/to/your_training_script.py',
    role=sm.get_execution_role(),
    base_job_name='debugger-demo-job',
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="2.9.0",
    py_version="py39",
    
    # debugger-specific hook argument below
    debugger_hook_config=hook_config
)

sagemaker_estimator.fit()
```

要查看 Debugger 内置集合的列表，请参阅 [Debugger 内置集合](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#collection)。

## 通过修改 Debugger 内置集合保存张量
<a name="debugger-save-modified-built-in-collections"></a>

您可以使用 `CollectionConfig` API 操作修改 Debugger 内置集合。以下示例说明如何调整内置`losses`集合并构造 A SageMaker I TensorFlow 估计器。您也可以将其用于 MXNet PyTorch、和 XGBoost 估计器。

```
import sagemaker
from sagemaker.tensorflow import TensorFlow
from sagemaker.debugger import DebuggerHookConfig, CollectionConfig

# use Debugger CollectionConfig to call and modify built-in collections
collection_configs=[
    CollectionConfig(
                name="losses", 
                parameters={"save_interval": "50"})]

# configure Debugger hook
# set a target S3 bucket as you want
sagemaker_session=sagemaker.Session()
BUCKET_NAME=sagemaker_session.default_bucket()
LOCATION_IN_BUCKET='debugger-modified-collections-hook'

hook_config=DebuggerHookConfig(
    s3_output_path='s3://{BUCKET_NAME}/{LOCATION_IN_BUCKET}'.
                    format(BUCKET_NAME=BUCKET_NAME, 
                           LOCATION_IN_BUCKET=LOCATION_IN_BUCKET),
    collection_configs=collection_configs
)

# construct a SageMaker TensorFlow estimator
sagemaker_estimator=TensorFlow(
    entry_point='directory/to/your_training_script.py',
    role=sm.get_execution_role(),
    base_job_name='debugger-demo-job',
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="2.9.0",
    py_version="py39",
    
    # debugger-specific hook argument below
    debugger_hook_config=hook_config
)

sagemaker_estimator.fit()
```

有关`CollectionConfig`参数的完整列表，请参阅[调试器 CollectionConfig API](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#configuring-collection-using-sagemaker-python-sdk)。

## 使用 Debugger 自定义集合保存张量
<a name="debugger-save-custom-collections"></a>

您也可以选择保存精简数量的张量而不是完整的张量集（例如，当您希望减少保存在 Amazon S3 存储桶中的数据量时）。以下示例说明了如何自定义 Debugger 钩子配置以指定要保存的目标张量。你可以将其用于 TensorFlow、 MXNet PyTorch、和 XGBoost 估计器。

```
import sagemaker
from sagemaker.tensorflow import TensorFlow
from sagemaker.debugger import DebuggerHookConfig, CollectionConfig

# use Debugger CollectionConfig to create a custom collection
collection_configs=[
        CollectionConfig(
            name="custom_activations_collection",
            parameters={
                "include_regex": "relu|tanh", # Required
                "reductions": "mean,variance,max,abs_mean,abs_variance,abs_max"
            })
    ]
    
# configure Debugger hook
# set a target S3 bucket as you want
sagemaker_session=sagemaker.Session()
BUCKET_NAME=sagemaker_session.default_bucket()
LOCATION_IN_BUCKET='debugger-custom-collections-hook'

hook_config=DebuggerHookConfig(
    s3_output_path='s3://{BUCKET_NAME}/{LOCATION_IN_BUCKET}'.
                    format(BUCKET_NAME=BUCKET_NAME, 
                           LOCATION_IN_BUCKET=LOCATION_IN_BUCKET),
    collection_configs=collection_configs
)

# construct a SageMaker TensorFlow estimator
sagemaker_estimator=TensorFlow(
    entry_point='directory/to/your_training_script.py',
    role=sm.get_execution_role(),
    base_job_name='debugger-demo-job',
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="2.9.0",
    py_version="py39",
    
    # debugger-specific hook argument below
    debugger_hook_config=hook_config
)

sagemaker_estimator.fit()
```

有关`CollectionConfig`参数的完整列表，请参阅[调试器 CollectionConfig](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#configuring-collection-using-sagemaker-python-sdk)。

# 如何配置 Debugger 内置规则
<a name="use-debugger-built-in-rules"></a>

在以下主题中，您将学习如何使用 SageMaker 调试器内置规则。Amazon SageMaker Debugger 的内置规则分析模型训练期间发出的张量。 SageMaker AI Debugger 提供了 `Rule` API 操作，用于监控训练作业进度和错误，确保模型成功训练。例如，规则可以检测梯度变得过大还是太小，模型是过度拟合还是过度训练，以及训练作业是否没有减少损失函数和实现改善。要查看可用内置规则的完整列表，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

**Topics**
+ [使用带有默认参数设置的 Debugger 内置规则](debugger-built-in-rules-configuration.md)
+ [使用带有自定义参数值的 Debugger 内置规则](debugger-built-in-rules-configuration-param-change.md)
+ [配置 Debugger 规则的笔记本示例和代码示例](debugger-built-in-rules-example.md)

# 使用带有默认参数设置的 Debugger 内置规则
<a name="debugger-built-in-rules-configuration"></a>

要在估算器中指定 Debugger 内置规则，您需要配置列表对象。以下示例代码显示了列出 Debugger 内置规则的基本结构：

```
from sagemaker.debugger import Rule, rule_configs

rules=[
    Rule.sagemaker(rule_configs.built_in_rule_name_1()),
    Rule.sagemaker(rule_configs.built_in_rule_name_2()),
    ...
    Rule.sagemaker(rule_configs.built_in_rule_name_n()),
    ... # You can also append more profiler rules in the ProfilerRule.sagemaker(rule_configs.*()) format.
]
```

有关内置规则的默认参数值和说明的详细信息，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

要查找 SageMaker 调试器 API 参考，请参阅[https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.sagemaker.debugger.rule_configs](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.sagemaker.debugger.rule_configs)和。[https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.Rule](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.Rule)

例如，要检查模型的整体训练性能和进度，请使用以下内置规则配置构建 SageMaker AI 估算器。

```
from sagemaker.debugger import Rule, rule_configs

rules=[
    Rule.sagemaker(rule_configs.loss_not_decreasing()),
    Rule.sagemaker(rule_configs.overfit()),
    Rule.sagemaker(rule_configs.overtraining()),
    Rule.sagemaker(rule_configs.stalled_training_rule())
]
```

当您启动训练作业时，默认情况下，Debugger 每 500 毫秒收集一次系统资源利用率数据，每 500 个步骤收集一次损失和准确性值。Debugger 分析资源利用率，以确定您的模型是否存在瓶颈问题。`loss_not_decreasing`、`overfit`、`overtraining` 和 `stalled_training_rule` 监控模型是否在优化损失函数而没有这些训练问题。当规则检测到训练异常时，规则评估状态将更改为 `IssueFound`。您可以设置自动操作，例如使用 Amazon Ev CloudWatch ents 和，通知培训问题和停止训练作业。 AWS Lambda有关更多信息，请参阅 [Amazon 上的操作 SageMaker 调试器规则](debugger-action-on-rules.md)。



# 使用带有自定义参数值的 Debugger 内置规则
<a name="debugger-built-in-rules-configuration-param-change"></a>

如果您要调整内置的规则参数值并自定义张量集合正则表达式，请配置 `ProfilerRule.sagemaker` 和 `Rule.sagemaker` 类方法的 `base_config` 和 `rule_parameters` 参数。使用 `Rule.sagemaker` 类方法时，您也可以通过 `collections_to_save` 参数自定义张量集合。[使用 `CollectionConfig` API 配置张量集合](debugger-configure-tensor-collections.md) 中提供了如何使用 `CollectionConfig` 类的说明。

为内置规则使用以下配置模板来自定义参数值。通过根据需要更改规则参数，您可以调整规则触发的敏感度。
+ 您在 `base_config` 参数中调用内置规则方法。
+ `rule_parameters` 参数用于调整 [Debugger 内置规则列表](debugger-built-in-rules.md) 中列出的内置规则的默认键值。
+ `collections_to_save` 参数通过 `CollectionConfig` API 获取张量配置，这需要 `name` 和 `parameters` 参数。
  + 要查找 `name` 的可用张量集合，请参阅 [Debugger 内置张量集合](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#built-in-collections)。
  + 有关可调整项的完整列表`parameters`，请参阅调[试器 CollectionConfig API](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#configuring-collection-using-sagemaker-python-sdk)。

有关调试器规则类、方法和参数的更多信息，请参阅 [SageMaker Amaz [on Pyth SageMaker on](https://sagemaker.readthedocs.io/en/stable) SDK 中的 AI 调试器规则类](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html)。

```
from sagemaker.debugger import Rule, ProfilerRule, rule_configs, CollectionConfig

rules=[
    Rule.sagemaker(
        base_config=rule_configs.built_in_rule_name(),
        rule_parameters={
                "key": "value"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="tensor_collection_name", 
                parameters={
                    "key": "value"
                } 
            )
        ]
    )
]
```

各个规则的参数描述和值自定义示例均在 [Debugger 内置规则列表](debugger-built-in-rules.md) 中提供。

# 配置 Debugger 规则的笔记本示例和代码示例
<a name="debugger-built-in-rules-example"></a>

以下各节提供了有关如何使用调试器规则监控 SageMaker 训练作业的笔记本和代码示例。

**Topics**
+ [Debugger 内置规则示例笔记本](#debugger-built-in-rules-notebook-example)
+ [Debugger 内置规则示例代码](#debugger-deploy-built-in-rules)
+ [使用 Debugger 内置规则并修改参数](#debugger-deploy-modified-built-in-rules)

## Debugger 内置规则示例笔记本
<a name="debugger-built-in-rules-notebook-example"></a>

以下示例笔记本展示了在使用 Amazon A SageMaker I 运行训练作业时如何使用调试器内置规则：
+ [使用调 SageMaker 试器内置规则 TensorFlow](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/tensorflow_builtin_rule)
+ [将 SageMaker 调试器内置规则与托管点训练配合使用 MXNet](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mxnet_spot_training)
+ [使用带有参数修改的 SageMaker 调试器内置规则进行实时训练作业分析 XGBoost](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/xgboost_realtime_analysis)

在 SageMaker Studio 中运行示例笔记本时，您可以在 Studi **o 实验列表**选项卡上找到创建的训练作业试用版。例如，如以下屏幕截图所示，您可以找到并打开当前训练作业的**描述试验组件**窗口。在“Debugger”选项卡上，您可以检查 Debugger 规则 `vanishing_gradient()` 和 `loss_not_decreasing()` 是否并行监视训练会话。有关如何在 Studio 用户界面中查找训练作业试用组件的完整说明，请参阅 [SageMaker Studio-查看实验、试用和试用组件](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-tasks.html#studio-tasks-experiments)。

![\[在 Studio 中激活了调试器内置规则的情况下运行训练作业的 SageMaker 图像\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-built-in-rule-studio.png)


在 SageMaker AI 环境中使用调试器内置规则的方法有两种：在准备好内置规则时部署内置规则，或者根据需要调整其参数。以下主题向您演示了如何将内置规则与示例代码结合使用。

## Debugger 内置规则示例代码
<a name="debugger-deploy-built-in-rules"></a>

以下代码示例演示如何使用 `Rule.sagemaker` 方法设置 Debugger 内置规则。要指定所要运行的内置规则，请使用 `rules_configs` API 操作调用内置规则。要查找 Debugger 内置规则和默认参数值的完整列表，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

```
import sagemaker
from sagemaker.tensorflow import TensorFlow
from sagemaker.debugger import Rule, CollectionConfig, rule_configs

# call built-in rules that you want to use.
built_in_rules=[ 
            Rule.sagemaker(rule_configs.vanishing_gradient())
            Rule.sagemaker(rule_configs.loss_not_decreasing())
]

# construct a SageMaker AI estimator with the Debugger built-in rules
sagemaker_estimator=TensorFlow(
    entry_point='directory/to/your_training_script.py',
    role=sm.get_execution_role(),
    base_job_name='debugger-built-in-rules-demo',
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="2.9.0",
    py_version="py39",

    # debugger-specific arguments below
    rules=built_in_rules
)
sagemaker_estimator.fit()
```

**注意**  
Debugger 内置规则与您的训练作业并行运行。训练作业的内置规则容器的最大数量为 20 个。

有关调试器规则类、方法和参数的更多信息，请参阅 Amaz [on Pyth SageMaker on](https://sagemaker.readthedocs.io/en/stable) SDK 中的[SageMaker 调试器规则类](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html)。

要查找如何调整 Debugger 规则参数的示例，请参阅以下 [使用 Debugger 内置规则并修改参数](#debugger-deploy-modified-built-in-rules) 部分。

## 使用 Debugger 内置规则并修改参数
<a name="debugger-deploy-modified-built-in-rules"></a>

下面的代码示例显示了用于调整参数的内置规则的结构。在此示例中，`stalled_training_rule` 每 50 个步骤收集一次 `losses` 张量，每 10 个步骤评估一次阶段。如果训练过程开始停滞并且在 120 秒内没有收集到任何张量输出，那么 `stalled_training_rule` 停止训练作业。

```
import sagemaker
from sagemaker.tensorflow import TensorFlow
from sagemaker.debugger import Rule, CollectionConfig, rule_configs

# call the built-in rules and modify the CollectionConfig parameters

base_job_name_prefix= 'smdebug-stalled-demo-' + str(int(time.time()))

built_in_rules_modified=[
    Rule.sagemaker(
        base_config=rule_configs.stalled_training_rule(),
        rule_parameters={
                'threshold': '120',
                'training_job_name_prefix': base_job_name_prefix,
                'stop_training_on_fire' : 'True'
        }
        collections_to_save=[ 
            CollectionConfig(
                name="losses", 
                parameters={
                      "train.save_interval": "50"
                      "eval.save_interval": "10"
                } 
            )
        ]
    )
]

# construct a SageMaker AI estimator with the modified Debugger built-in rule
sagemaker_estimator=TensorFlow(
    entry_point='directory/to/your_training_script.py',
    role=sm.get_execution_role(),
    base_job_name=base_job_name_prefix,
    instance_count=1,
    instance_type="ml.p3.2xlarge",
    framework_version="2.9.0",
    py_version="py39",

    # debugger-specific arguments below
    rules=built_in_rules_modified
)
sagemaker_estimator.fit()
```

有关使用 `CreateTrainingJob` API 对 Debugger 内置规则进行高级配置的信息，请参阅[使用 SageMaker API 配置调试器](debugger-createtrainingjob-api.md)。

# 关闭 Debugger
<a name="debugger-turn-off"></a>

如果您要完全关闭 Debugger，请执行下面的任一操作：
+ 在开始训练作业前，请执行以下操作：

  要停止监控和分析功能，请在您的估算器中包括 `disable_profiler` 参数并将其设置为`True`。
**警告**  
如果您将其禁用，则将无法查看综合 Studio Debugger Insights 控制面板和自动生成的分析报告。

  要禁用调试，请将 `debugger_hook_config` 参数设置为 `False`。
**警告**  
如果您将其禁用，则无法收集输出张量，也无法调试模型参数。

  ```
  estimator=Estimator(
      ...
      disable_profiler=True
      debugger_hook_config=False
  )
  ```

  [有关调试器特定参数的更多信息，请参阅 [SageMaker Amazon Python SDK 中的 AI Estimat](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator) or。 SageMaker ](https://sagemaker.readthedocs.io/en/stable)
+ 在训练作业正在运行时，执行以下操作：

  要在训练作业运行期间禁用监控和分析功能，请使用以下估算器类方法：

  ```
  estimator.disable_profiling()
  ```

  要仅禁用框架分析并保留系统监控，请使用 `update_profiler` 方法：

  ```
  estimator.update_profiler(disable_framework_metrics=true)
  ```

  [https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator.update_profiler](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator.update_profiler)

# 调试器有用的 SageMaker AI 估算器类方法
<a name="debugger-estimator-classmethods"></a>

以下估算器类方法对于访问您的 SageMaker 训练作业信息和检索 Debugger 收集的训练数据的输出路径非常有用。在您使用 `estimator.fit()` 方法启动训练作业之后，可以执行以下方法。
+ 要检查 SageMaker 训练作业的基本 S3 存储桶 URI，请执行以下操作：

  ```
  estimator.output_path
  ```
+ 要查看 SageMaker 训练作业的基本作业名称，请执行以下操作：

  ```
  estimator.latest_training_job.job_name
  ```
+ 要查看 SageMaker 训练作业的完整 `CreateTrainingJob` API 操作配置，请执行以下操作：

  ```
  estimator.latest_training_job.describe()
  ```
+ 要在 SageMaker 训练作业运行时查看调试器规则的完整列表，请执行以下操作：

  ```
  estimator.latest_training_job.rule_job_summary()
  ```
+ 要查看保存模型参数数据（输出张量）的 S3 存储桶 URI，请执行以下操作：

  ```
  estimator.latest_job_debugger_artifacts_path()
  ```
+ 要查看保存模型性能数据（系统和框架指标）的 S3 存储桶 URI，请执行以下操作：

  ```
  estimator.latest_job_profiler_artifacts_path()
  ```
+ 要查看用于调试输出张量的 Debugger 规则配置，请执行以下操作：

  ```
  estimator.debugger_rule_configs
  ```
+ 要查看用于在 SageMaker 训练作业运行时进行调试的调试器规则列表，请执行以下操作：

  ```
  estimator.debugger_rules
  ```
+ 要查看用于监控和分析系统及框架指标的 Debugger 规则配置，请执行以下操作：

  ```
  estimator.profiler_rule_configs
  ```
+ 要查看用于在 SageMaker 训练作业运行时进行监控和分析的调试器规则列表，请执行以下操作：

  ```
  estimator.profiler_rules
  ```

[有关 SageMaker AI 估算器类及其方法的更多信息，请参阅 Amazon Python SDK [中的估算器](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator) API。 SageMaker ](https://sagemaker.readthedocs.io/en/stable)

# SageMaker 的调试器交互式报告 XGBoost
<a name="debugger-report-xgboost"></a>

接收 Debugger 自动生成的训练报告。Debugger 报告提供了有关您训练作业的见解，并给出改善模型性能的建议。对于 SageMaker AI XGBoost 训练作业，请使用调试器[CreateXgboostReport](debugger-built-in-rules.md#create-xgboost-report)规则接收有关训练进度和结果的全面训练报告。按照本指南，在构建 XGBoost 估算器时指定[CreateXgboostReport](debugger-built-in-rules.md#create-xgboost-report)规则，使用 Amaz [on Python SDK 或 Amaz SageMaker on](https://sagemaker.readthedocs.io/en/stable) S3 控制台下载报告，并深入了解训练结果。

**注意**  
您可以在训练作业运行期间或作业完成后下载 Debugger 报告。在训练期间，Debugger 同时更新报告，反映当前规则的评估状态。只有在训练作业完成后，您才能下载完整的 Debugger 报告。

**重要**  
报告中提供的图表和建议仅供参考，并不确保准确无误。您应负责对其中的信息进行单独评测。

**Topics**
+ [使用调试 XGBoost 器报告规则构建 SageMaker AI XGBoost 估算器](debugger-training-xgboost-report-estimator.md)
+ [下载调试器 XGBoost 培训报告](debugger-training-xgboost-report-download.md)
+ [调试器 XGBoost 训练报告演练](debugger-training-xgboost-report-walkthrough.md)

# 使用调试 XGBoost 器报告规则构建 SageMaker AI XGBoost 估算器
<a name="debugger-training-xgboost-report-estimator"></a>

[CreateXgboostReport](debugger-built-in-rules.md#create-xgboost-report) 规则从您的训练作业中收集以下输出张量：
+ `hyperparameters` – 在第 1 步时保存。
+ `metrics` – 每 5 步保存损失和准确性。
+ `feature_importance` – 每 5 步保存一次。
+ `predictions` – 每 5 步保存一次。
+ `labels` – 每 5 步保存一次。

输出张量保存在默认 S3 存储桶中。例如 `s3://sagemaker-<region>-<12digit_account_id>/<base-job-name>/debug-output/`。

在为 XGBoost 训练作业构建 A SageMaker I 估算器时，请指定规则，如以下示例代码所示。

------
#### [ Using the SageMaker AI generic estimator ]

```
import boto3
import sagemaker
from sagemaker.estimator import Estimator
from sagemaker import image_uris
from sagemaker.debugger import Rule, rule_configs

rules=[
    Rule.sagemaker(rule_configs.create_xgboost_report())
]

region = boto3.Session().region_name
xgboost_container=sagemaker.image_uris.retrieve("xgboost", region, "1.2-1")

estimator=Estimator(
    role=sagemaker.get_execution_role()
    image_uri=xgboost_container,
    base_job_name="debugger-xgboost-report-demo",
    instance_count=1,
    instance_type="ml.m5.2xlarge",
    
    # Add the Debugger XGBoost report rule
    rules=rules
)

estimator.fit(wait=False)
```

------

# 下载调试器 XGBoost 培训报告
<a name="debugger-training-xgboost-report-download"></a>

使用 [Amaz SageMaker on Python SDK](https://sagemaker.readthedocs.io/en/stable) 和 AWS Command Line Interface (CLI) 在训练作业运行时或任务完成后下载调试器 XGBoost 训练报告。

------
#### [ Download using the SageMaker Python SDK and AWS CLI ]

1. 检查当前作业的默认 S3 输出基础 URI。

   ```
   estimator.output_path
   ```

1. 检查当前作业名称。

   ```
   estimator.latest_training_job.job_name
   ```

1. 调试器 XGBoost 报告存储在`<default-s3-output-base-uri>/<training-job-name>/rule-output`。如下所示配置规则输出路径：

   ```
   rule_output_path = estimator.output_path + "/" + estimator.latest_training_job.job_name + "/rule-output"
   ```

1. 要检查报告是否已生成，请在 `rule_output_path` 下，使用 `aws s3 ls` 以及 `--recursive` 选项递归列出目录和文件。

   ```
   ! aws s3 ls {rule_output_path} --recursive
   ```

   这应返回自动生成的文件夹（名为 `CreateXgboostReport` 和 `ProfilerReport-1234567890`）下的文件完整列表。 XGBoost 训练报告存储在中`CreateXgboostReport`，分析报告存储在`ProfilerReport-1234567890`文件夹中。要了解有关 XGBoost训练作业默认生成的分析报告的更多信息，请参阅[SageMaker 调试器交互式报告](debugger-profiling-report.md)。  
![\[规则输出的示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-xgboost-report-ls.png)

   `xgboost_report.html`是 Debugger 自动生成的 XGBoost 训练报告。`xgboost_report.ipynb` 是一个 Jupyter 笔记本，用于将训练结果聚合到报告中。您可以下载所有文件、浏览 HTML 报告文件，并使用笔记本修改报告。

1. 使用 `aws s3 cp` 递归下载文件。以下命令将所有规则输出文件保存到 `ProfilerReport-1234567890` 文件夹下的当前工作目录中。

   ```
   ! aws s3 cp {rule_output_path} ./ --recursive
   ```
**提示**  
如果您使用的是 Jupyter 笔记本服务器，请运行 `!pwd` 以验证当前的工作目录。

1. 在 `/CreateXgboostReport` 目录下，打开 `xgboost_report.html`。如果您正在使用 JupyterLab，请选择 T **rust HTML** 以查看自动生成的调试器训练报告。  
![\[规则输出的示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-xgboost-report-open-trust.png)

1. 打开 `xgboost_report.ipynb` 文件以浏览报告的生成方式。您可以使用 Jupyter 笔记本文件自定义和扩展训练报告。

------
#### [ Download using the Amazon S3 console ]

1. 登录 AWS 管理控制台 并打开 Amazon S3 控制台，网址为[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)。

1. 搜索基本 S3 存储桶。例如，如果您尚未指定任何基本作业名称，则基本 S3 存储桶名称应采用以下格式：`sagemaker-<region>-111122223333`。通过**按名称查找存储桶**字段，查找基本 S3 存储桶。  
![\[Amazon S3 控制台中的“按名称查找存储桶”字段。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-report-download-s3console-0.png)

1. 在基本 S3 存储桶中，在**按前缀查找对象**中输入您的作业名称前缀来查找训练作业名称，然后选择训练作业名称。  
![\[Amazon S3 控制台中的“按前缀查找对象”字段。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-report-download-s3console-1.png)

1. 在训练作业的 S3 存储桶中，选择 **rule-output/** 子文件夹。对于 Debugger 收集的训练数据，必须要有三个子文件夹：**debug-output/**、**profiler-output/** 和 **rule-output/**。  
![\[规则输出 S3 存储桶 URI 的示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-report-download-s3console-2.png)

1. **在 **rule-output/ 文件夹中，选择/**文件夹。CreateXgboostReport**文件夹中包含 **xbgoost\$1report.html**（自动生成的报告，html 格式）和 **xbgoost\$1report.ipynb**（用于生成报告的 Jupyter 笔记本和脚本）。

1. 选择 **xbgoost\$1report.html** 文件，选择**下载操作**，然后选择**下载**。  
![\[规则输出 S3 存储桶 URI 的示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-xgboost-report-s3-download.png)

1. 在 Web 浏览器中打开下载的 **xbgoost\$1report.html** 文件。

------

# 调试器 XGBoost 训练报告演练
<a name="debugger-training-xgboost-report-walkthrough"></a>

本节将引导您完成调试器 XGBoost 训练报告。报告会根据输出张量正则表达式自动聚合，识别您的训练作业属于二进制分类、多分类器还是回归类型。

**重要**  
报告中提供的图表和建议仅供参考，并不确保准确无误。您应负责对其中的信息进行单独评测。

**Topics**
+ [数据集的真实标签分布](#debugger-training-xgboost-report-walkthrough-dist-label)
+ [损失与步骤图](#debugger-training-xgboost-report-walkthrough-loss-vs-step)
+ [特征重要性](#debugger-training-xgboost-report-walkthrough-feature-importance)
+ [混淆矩阵](#debugger-training-xgboost-report-walkthrough-confusion-matrix)
+ [混淆矩阵的评估](#debugger-training-xgboost-report-walkthrough-eval-conf-matrix)
+ [迭代中每个对角元素的准确率](#debugger-training-xgboost-report-walkthrough-accuracy-rate)
+ [接收者操作特征曲线](#debugger-training-xgboost-report-walkthrough-rec-op-char)
+ [最后保存步骤的残差分布](#debugger-training-xgboost-report-walkthrough-dist-residual)
+ [迭代期间每个标签箱的绝对验证误差](#debugger-training-xgboost-report-walkthrough-val-error-per-label-bin)

## 数据集的真实标签分布
<a name="debugger-training-xgboost-report-walkthrough-dist-label"></a>

此直方图显示原始数据集内的标注类（用于分类）或值（用于回归）的分布情况。数据集内的偏斜可能会导致不准确的情况。此可视化对象可用于以下模型类型：二进制分类、多分类和回归。

![\[数据集图表的真实标签分布的示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-dist-label.png)


## 损失与步骤图
<a name="debugger-training-xgboost-report-walkthrough-loss-vs-step"></a>

此折线图显示整个训练步骤中，训练数据和验证数据上损失的进展。损失由您在目标函数中定义，例如平方误差。您可以根据此图来衡量模型是过度拟合还是欠拟合。此部分还提供了深入分析，您可以用来确定如何解决过度拟合和欠拟合的问题。此可视化对象可用于以下模型类型：二进制分类、多分类和回归。

![\[损失与步骤图的示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-loss-vs-step.png)


## 特征重要性
<a name="debugger-training-xgboost-report-walkthrough-feature-importance"></a>

可视化效果中提供了三种不同类型的特征重要性：权重、增益和覆盖率。我们在报告中为三者分别提供了详细的定义。特征重要性可视化对象可协助您了解训练数据集内的哪些特征对预测作出了贡献。功能重要性可视化对象可用于以下模型类型：二进制分类、多分类器和回归。

![\[特征重要性图的示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-feature-importance.png)


## 混淆矩阵
<a name="debugger-training-xgboost-report-walkthrough-confusion-matrix"></a>

此可视化对象仅可用于二进制分类和多分类器模型。仅仅依靠准确性可能不足以评估模型性能。对于某些使用场景，例如医疗保健和欺诈检测，了解假阳性率和假阴性率也很重要。混淆矩阵为您提供了其他用于评估模型性能的维度。

![\[混淆矩阵的示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-confusion-matrix.png)


## 混淆矩阵的评估
<a name="debugger-training-xgboost-report-walkthrough-eval-conf-matrix"></a>

此部分为您提供了有关模型查准率、查全率和 F1 分数的微观、宏观和加权指标的更多见解。

![\[评估混淆矩阵。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-eval-conf-matrix.png)


## 迭代中每个对角元素的准确率
<a name="debugger-training-xgboost-report-walkthrough-accuracy-rate"></a>

此可视化对象仅可用于二进制分类和多分类器模型。此折线图描绘了各个类的整个训练步骤中，混淆矩阵中的对角线值。此图显示在整个训练步骤中，各个类的准确性进展情况。您可以从此图确定表现不佳的类。

![\[迭代中各个对角元素的准确率图示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-accuracy-rate.gif)


## 接收者操作特征曲线
<a name="debugger-training-xgboost-report-walkthrough-rec-op-char"></a>

此可视化对象仅适用于二进制分类模型。接收者操作特征曲线通常用于评估二进制分类模型的性能。曲线的 y 轴为真阳性率 (TPR)，x 轴为假阳性率 (FPR)。该图还显示曲线下面积 (AUC) 的值。AUC 值越高，分类器的预测能力就越好。您还可以使用 ROC 曲线了解 TPR 和 FPR 之间的权衡，并确定您的使用场景的最佳分类阈值。分类阈值可以调整，用以调整模型的行为，来减少类型多个错误或另一种类型的错误 (FP/FN)。

![\[接收者操作特征曲线图示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-rec-op-char.png)


## 最后保存步骤的残差分布
<a name="debugger-training-xgboost-report-walkthrough-dist-residual"></a>

此可视化对象是一个柱状图，显示 Debugger 在最后的步骤中捕获的残余分布。在此可视化对象中，您可以检查残差分布是否接近以零为中心的正态分布。如果残差出现偏斜，则您的特征可能不足以预测标签。

![\[最后保存步骤中残差分布图示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-dist-residual.png)


## 迭代期间每个标签箱的绝对验证误差
<a name="debugger-training-xgboost-report-walkthrough-val-error-per-label-bin"></a>

此可视化对象仅适用于回归模型。实际目标值拆分为 10 个间隔。此可视化对象显示了折线图中，对于整个训练步骤，每个间隔的验证错误的进展情况。绝对验证误差是验证期间，预测值与实际值之差的绝对值。您可以从此可视化对象中识别性能不佳的间隔。

![\[迭代期间每个标签箱的绝对验证误差图示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-val-error-per-label-bin.png)


# Amazon 上的操作 SageMaker 调试器规则
<a name="debugger-action-on-rules"></a>

根据 Debugger 规则评估状态，您可以设置自动操作，例如停止训练作业并使用 Amazon Simple Notification Service (Amazon SNS) 发送通知。您还可以使用 Amazon Ev CloudWatch ents 和 AWS Lambda. 创建自己的操作。要了解如何根据 Debugger 规则评估状态设置自动操作，请参阅以下主题。

**Topics**
+ [为规则使用 Debugger 内置操作](debugger-built-in-actions.md)
+ [使用 Amazon 对规则执行操作 CloudWatch 以及 AWS Lambda](debugger-cloudwatch-lambda.md)

# 为规则使用 Debugger 内置操作
<a name="debugger-built-in-actions"></a>

使用 Debugger 内置操作来响应 [Debugger 规则](debugger-built-in-rules.md#debugger-built-in-rules-Rule) 发现的问题。Debugger `rule_configs` 类提供了工具来配置操作列表，包括自动停止训练作业，以及在 Debugger 规则发现训练问题时使用 Amazon Simple Notification Service (Amazon SNS) 发送通知。以下主题将介绍完成这些任务的步骤。

**Topics**
+ [设置 Amazon SNS，创建 `SMDebugRules` 主题，并订阅该主题](#debugger-built-in-actions-sns)
+ [设置 IAM 角色以附加所需策略](#debugger-built-in-actions-iam)
+ [使用内置操作配置 Debugger 规则](#debugger-built-in-actions-on-rule)
+ [使用 Debugger 内置操作的注意事项](#debugger-built-in-actions-considerations)

## 设置 Amazon SNS，创建 `SMDebugRules` 主题，并订阅该主题
<a name="debugger-built-in-actions-sns"></a>

此部分将向您介绍如何设置 Amazon SNS **SMDebugRules** 主题、订阅该主题以及如何确认订阅，以便接收来自 Debugger 规则的通知。

**注意**  
[有关亚马逊 SNS 账单的更多信息，请参阅亚马逊 SNS 定价和[亚马逊 SNS](https://aws.amazon.com/sns/pricing/)。 FAQs](https://aws.amazon.com/sns/faqs/)

**创建 SMDebug规则主题**

1. [登录 AWS 管理控制台 并在 v3/home 上打开亚马逊 SNS 控制台。https://console.aws.amazon.com/sns/](https://console.aws.amazon.com/sns/v3/home)

1. 在左侧导航窗格中，选择**主题**。

1. 在 **Topics**（主题）页面上，选择 **Create topic**（创建主题）。

1. 在 **Create topic**（创建主题）页面上，在 **Details**（详细信息）部分中，执行以下操作：

   1. 对于**类型**，选择**标准**作为主题类型。

   1. 在**名称**中，输入 **SMDebugRules**。

1. 跳过所有其他可选设置，然后选择**创建主题**。如果您希望了解有关可选设置的更多信息，请参阅[创建 Amazon SNS 主题](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)。

**订阅 SMDebug规则主题**

1. [在 v3/home 上打开亚马逊 SNS 控制台。https://console.aws.amazon.com/sns/](https://console.aws.amazon.com/sns/v3/home)

1. 在左侧导航窗格中，选择**订阅**。

1. 在**订阅**页面上，选择**创建订阅**。

1. 在**创建订阅**页上的**详细信息**部分，执行以下操作：

   1. 对于**主题 ARN**，选择**SMDebug规则**主题 ARN。ARN 的格式应为 `arn:aws:sns:<region-id>:111122223333:SMDebugRules`。

   1. 对于**协议**，选择**电子邮件**或 **SMS**。

   1. 对于**端点**，请输入端点值，例如您用于接收通知的电子邮件地址或电话号码。
**注意**  
确保键入正确的电子邮件地址和电话号码。电话号码必须包括 `+`、国家/地区代码和电话号码，不含特殊字符或空格。例如，电话号码 \$11 (222) 333-4444 的格式为 **\$112223334444**。

1. 跳过所有其他可选设置，然后选择**创建订阅**。如果您想了解有关可选设置的更多信息，请参阅[订阅 Amazon SNS 主题](https://docs.aws.amazon.com/sns/latest/dg/sns-create-subscribe-endpoint-to-topic.html)。

订阅**SMDebug规则**主题后，您将通过电子邮件或电话收到以下确认消息：

![\[Amazon SNS SMDebug规则主题的订阅确认电子邮件。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-built-in-action-subscription-confirmation.png)


有关 Amazon SNS 的更多信息，请参阅**《Amazon SNS 开发人员指南》中的[移动文本消息 (SMS)](https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html)和[电子邮件通知](https://docs.aws.amazon.com/sns/latest/dg/sns-email-notifications.html)。

## 设置 IAM 角色以附加所需策略
<a name="debugger-built-in-actions-iam"></a>

在此步骤中，您将所需的策略添加到 IAM 角色中。

**向 IAM 角色添加所需的策略**

1. 登录 AWS 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在左侧导航窗格中选择**策略**，然后选择**创建策略**。

1. 在**创建策略**页面上，请执行以下操作以创建新的 sns-access 策略：

   1. 选择 **JSON** 选项卡。

   1. 将以下代码中以粗体格式化的 JSON 字符串粘贴到中`"Statement"`，将 12 位数的 AWS 账户 ID 替换为您的 AWS 账户 ID。

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Sid": "VisualEditor0",
                  "Effect": "Allow",
                  "Action": [
                      "sns:Publish",
                      "sns:CreateTopic",
                      "sns:Subscribe"
                  ],
                  "Resource": "arn:aws:sns:*:111122223333:SMDebugRules"
              }
          ]
      }
      ```

------

   1. 在页面底部，选择**查看策略**。

   1. 在**查看策略**页面上，对于**名称**，输入 **sns-access**。

   1. 在页面底部，选择**创建策略**。

1. 返回 IAM 控制台，然后在左侧导航窗格中选择**角色**。

1. 查找您用于 A SageMaker I 模型训练的 IAM 角色并选择该 IAM 角色。

1. 在**摘要**页面的**权限**选项卡上，选择**附加策略**。

1. 搜索 **sns-access** 策略，选中该策略旁边的复选框，然后选择**附加策略**。

有关为 Amazon SNS 设置 IAM 策略的更多示例，请参阅 [Amazon SNS 访问控制示例](https://docs.aws.amazon.com/sns/latest/dg/sns-access-policy-use-cases.html)。

## 使用内置操作配置 Debugger 规则
<a name="debugger-built-in-actions-on-rule"></a>

在上述步骤中成功完成所需的设置后，您可以针对调试规则配置 Debugger 内置操作，如以下示例脚本所示。您可以选择在构建 `actions` 列表对象时使用哪些内置操作。`rule_configs` 是一个帮助程序模块，提供了用于配置 Debugger 内置规则和操作的高级工具。以下内置操作可用于 Debugger：
+ `rule_configs.StopTraining()` – 在 Debugger 规则发现问题时停止训练作业。
+ `rule_configs.Email("abc@abc.com")` – 在 Debugger 规则发现问题时通过电子邮件发送通知。使用您在设置 SNS 主题订阅时使用的电子邮件地址。
+ `rule_configs.SMS("+1234567890")` – 在 Debugger 规则发现问题时通过短信发送通知。使用您在设置 SNS 主题订阅时使用的电话号码。
**注意**  
确保键入正确的电子邮件地址和电话号码。电话号码必须包括 `+`、国家/地区代码和电话号码，不含特殊字符或空格。例如，电话号码 \$11 (222) 333-4444 的格式为 **\$112223334444**。

您可以使用获取内置操作并配置操作列表的 `rule_configs.ActionList()` 方法进行包装，以此来使用内置操作或操作的子集。

**将所有三个内置操作添加到单个规则**

如果要将所有三个内置操作分配给单个规则，请在构造估算器时配置 Debugger 内置操作列表。使用以下模板来构造估算器，Debugger 将根据您用于监控训练作业进度的任意规则停止训练作业，并通过电子邮件和文本发送通知。

```
from sagemaker.debugger import Rule, rule_configs

# Configure an action list object for Debugger rules
actions = rule_configs.ActionList(
    rule_configs.StopTraining(), 
    rule_configs.Email("abc@abc.com"), 
    rule_configs.SMS("+1234567890")
)

# Configure rules for debugging with the actions parameter
rules = [
    Rule.sagemaker(
        base_config=rule_configs.built_in_rule(),         # Required
        rule_parameters={"paramter_key": value },        # Optional
        actions=actions
    )
]

estimator = Estimator(
    ...
    rules = rules
)

estimator.fit(wait=False)
```

**创建多个内置操作对象以将不同的操作分配给单个规则**

如果您要指定根据单个规则的不同阈值来触发内置操作，则可以创建多个内置操作对象，如以下脚本所示。要在运行相同的规则时避免冲突错误，您必须提交不同的规则作业名称（为规则的 `name` 属性指定不同的字符串），如以下示例脚本模板所示。此示例说明了如何设置 [StalledTrainingRule](debugger-built-in-rules.md#stalled-training) 来采取两种不同的操作：当训练作业停顿 60 秒时发送电子邮件至 `abc@abc.com`，如果停顿 120 秒则停止训练作业。

```
from sagemaker.debugger import Rule, rule_configs
import time

base_job_name_prefix= 'smdebug-stalled-demo-' + str(int(time.time()))

# Configure an action object for StopTraining
action_stop_training = rule_configs.ActionList(
    rule_configs.StopTraining()
)

# Configure an action object for Email
action_email = rule_configs.ActionList(
    rule_configs.Email("abc@abc.com")
)

# Configure a rule with the Email built-in action to trigger if a training job stalls for 60 seconds
stalled_training_job_rule_email = Rule.sagemaker(
        base_config=rule_configs.stalled_training_rule(),
        rule_parameters={
                "threshold": "60", 
                "training_job_name_prefix": base_job_name_prefix
        },
        actions=action_email
)
stalled_training_job_rule_text.name="StalledTrainingJobRuleEmail"

# Configure a rule with the StopTraining built-in action to trigger if a training job stalls for 120 seconds
stalled_training_job_rule = Rule.sagemaker(
        base_config=rule_configs.stalled_training_rule(),
        rule_parameters={
                "threshold": "120", 
                "training_job_name_prefix": base_job_name_prefix
        },
        actions=action_stop_training
)
stalled_training_job_rule.name="StalledTrainingJobRuleStopTraining"

estimator = Estimator(
    ...
    rules = [stalled_training_job_rule_email, stalled_training_job_rule]
)

estimator.fit(wait=False)
```

在训练作业运行时，只要规则发现训练作业中存在问题，Debugger 内置操作就会发送通知电子邮件和文本消息。以下屏幕截图显示了在出现训练作业停顿问题时，训练作业的电子邮件通知示例。

![\[调试器检测到 StalledTraining 问题时发送的电子邮件通知示例。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-built-in-action-email.png)


以下屏幕截图显示了调试器在规则发现 StalledTraining 问题时发送的示例文本通知。

![\[调试器检测到 StalledTraining 问题时发送的示例文本通知。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-built-in-action-text.png)


## 使用 Debugger 内置操作的注意事项
<a name="debugger-built-in-actions-considerations"></a>
+ 使用 Debugger 内置操作需要互联网连接。Amazon A SageMaker I 或 Amazon VPC 提供的网络隔离模式不支持此功能。
+ 内置操作不能用于 [探查器规则](debugger-built-in-profiler-rules.md#debugger-built-in-profiler-rules-ProfilerRule)。
+ 内置操作不能用于会出现竞价型实例训练中断的训练作业。
+ 在电子邮件或短信通知中，`None` 会显示在消息的末尾。此文本没有任何意义，因此您可以忽略文本 `None`。

# 使用 Amazon 对规则执行操作 CloudWatch 以及 AWS Lambda
<a name="debugger-cloudwatch-lambda"></a>

亚马逊 CloudWatch 收集亚马逊 A SageMaker I 模型训练作业日志和 Amazon SageMaker Debugger 规则处理任务日志。使用 Amazon Ev CloudWatch ents 配置调试器 AWS Lambda ，并根据调试器规则评估状态采取行动。

## 示例笔记本
<a name="debugger-test-stop-training"></a>

您可以运行以下示例笔记本，这些笔记本已准备就绪，可以使用 Ama CloudWatch zon 和，使用调试器内置规则上的操作来尝试停止训练作业。 AWS Lambda
+ [Amazon SageMaker 调试器-对来自规则 CloudWatch 的事件做出反应](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_action_on_rule/tf-mnist-stop-training-job.html)

  此示例笔记本运行的训练作业存在梯度消失问题。构建 SageMaker AI TensorFlow 估计器时使用调试器[VanishingGradient](debugger-built-in-rules.md#vanishing-gradient)内置规则。当 Debugger 规则检测到问题时，训练作业即告终止。
+ [使用调试器规则检测停滞的训练并 SageMaker 调用操作](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_action_on_rule/detect_stalled_training_job_and_actions.html)

  此示例笔记本运行一个训练脚本，有一行代码会强制脚本休眠 10 分钟。Debugger [StalledTrainingRule](debugger-built-in-rules.md#stalled-training) 内置规则调用问题并停止训练作业。

**Topics**
+ [示例笔记本](#debugger-test-stop-training)
+ [调试器规则和训练作业的访问 CloudWatch 日志](debugger-cloudwatch-metric.md)
+ [使用 CloudWatch 和 Lambda 设置调试器以自动终止训练作业](debugger-stop-training.md)
+ [禁用 CloudWatch 事件规则以停止使用自动终止训练作业](debugger-disable-cw.md)

# 调试器规则和训练作业的访问 CloudWatch 日志
<a name="debugger-cloudwatch-metric"></a>

当存在训练问题时，您可以使用 CloudWatch 日志中的训练和调试器规则作业状态来采取进一步的措施。以下过程说明如何访问相关日 CloudWatch 志。有关使用监控训练作业的更多信息 CloudWatch，请参阅[监控 Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/latest/dg/monitoring-overview.html)。

**访问训练作业日志和 Debugger 规则作业日志**

1. 打开 CloudWatch 控制台，网址为[https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)。

1. 在左侧导航窗格的**日志**节点下，选择**日志组**。

1. 在日志组列表中，执行以下操作：
   + aws/sagemaker/TrainingJobs为训练作业日志选择**/**。
   + aws/sagemaker/ProcessingJobs为调试器规则作业日志选择**/**。

# 使用 CloudWatch 和 Lambda 设置调试器以自动终止训练作业
<a name="debugger-stop-training"></a>

调试器规则监控训练作业状态， CloudWatch 事件规则监视调试器规则训练作业评估状态。以下各节概述了使用 using CloudWatch 和 Lambda 自动终止训练任务所需的流程。

**Topics**
+ [第 1 步：创建 Lambda 函数](#debugger-lambda-function-create)
+ [步骤 2：配置 Lambda 函数](#debugger-lambda-function-configure)
+ [步骤 3：为调试器创建 CloudWatch 事件规则并链接到 Lambda 函数](#debugger-cloudwatch-events)

## 第 1 步：创建 Lambda 函数
<a name="debugger-lambda-function-create"></a>

**创建 Lambda 函数**

1. 打开 AWS Lambda 控制台，网址为[https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/)。

1. 在左侧导航窗格中，选择**函数**，然后选择**创建函数**。

1. 在**创建函数**页面上，选择**从头开始创作**。

1. 在**基本信息**部分，输入**函数名称**（例如，**debugger-rule-stop-training-job**）。

1. 对于**运行时系统**，选择 **Python 3.7**。

1. 对于**权限**，展开下拉选项，然后选择**更改默认执行角色**。

1. 对于**执行角色**，选择**使用现有角色**并选择用于在 A SageMaker I 上训练任务的 IAM 角色。
**注意**  
请确保您使用附加了 `AmazonSageMakerFullAccess` 和 `AWSLambdaBasicExecutionRole` 的执行角色。否则，Lambda 函数将无法正确响应训练作业的 Debugger 规则状态变化。如果您不确定正在使用哪个执行角色，请在 Jupyter 笔记本单元中运行以下代码来检索执行角色输出：  

   ```
   import sagemaker
   sagemaker.get_execution_role()
   ```

1. 在页面底部，选择**创建函数**。

下图显示了**创建函数**页面的示例，其中已完成了输入字段和选择。

![\[“创建函数”页面。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-lambda-create.png)


## 步骤 2：配置 Lambda 函数
<a name="debugger-lambda-function-configure"></a>

**配置 Lambda 函数**

1. 在配置页面的**函数代码**部分，将以下 Python 脚本粘贴到 Lambda 代码编辑器窗格中。该`lambda_handler`函数监控收集的调试器规则评估状态 CloudWatch 并触发 `StopTrainingJob` API 操作。f 适用于 Python (Boto3) 的 AWS SDK `client` o SageMaker r AI 提供了一种高级方法`stop_training_job`，用于触发 `StopTrainingJob` API 操作。

   ```
   import json
   import boto3
   import logging
   
   logger = logging.getLogger()
   logger.setLevel(logging.INFO)
   
   def lambda_handler(event, context):
       training_job_name = event.get("detail").get("TrainingJobName")
       logging.info(f'Evaluating Debugger rules for training job: {training_job_name}')
       eval_statuses = event.get("detail").get("DebugRuleEvaluationStatuses", None)
   
       if eval_statuses is None or len(eval_statuses) == 0:
           logging.info("Couldn't find any debug rule statuses, skipping...")
           return {
               'statusCode': 200,
               'body': json.dumps('Nothing to do')
           }
   
       # should only attempt stopping jobs with InProgress status
       training_job_status = event.get("detail").get("TrainingJobStatus", None)
       if training_job_status != 'InProgress':
           logging.debug(f"Current Training job status({training_job_status}) is not 'InProgress'. Exiting")
           return {
               'statusCode': 200,
               'body': json.dumps('Nothing to do')
           }
   
       client = boto3.client('sagemaker')
   
       for status in eval_statuses:
           logging.info(status.get("RuleEvaluationStatus") + ', RuleEvaluationStatus=' + str(status))
           if status.get("RuleEvaluationStatus") == "IssuesFound":
               secondary_status = event.get("detail").get("SecondaryStatus", None)
               logging.info(
                   f'About to stop training job, since evaluation of rule configuration {status.get("RuleConfigurationName")} resulted in "IssuesFound". ' +
                   f'\ntraining job "{training_job_name}" status is "{training_job_status}", secondary status is "{secondary_status}"' +
                   f'\nAttempting to stop training job "{training_job_name}"'
               )
               try:
                   client.stop_training_job(
                       TrainingJobName=training_job_name
                   )
               except Exception as e:
                   logging.error(
                       "Encountered error while trying to "
                       "stop training job {}: {}".format(
                           training_job_name, str(e)
                       )
                   )
                   raise e
       return None
   ```

   有关 Lambda 代码编辑器界面的更多信息，请参阅[使用 Lambda AWS 控制台编辑器创建函数](https://docs.aws.amazon.com/lambda/latest/dg/code-editor.html)。

1. 跳过所有其他设置，然后在配置页面顶部选择**保存**。

## 步骤 3：为调试器创建 CloudWatch 事件规则并链接到 Lambda 函数
<a name="debugger-cloudwatch-events"></a>

**为调试器创建 CloudWatch 事件规则并链接到 Lambda 函数**

1. 打开 CloudWatch 控制台，网址为[https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)。

1. 在左侧导航窗格中，选择**事件**节点下的**规则**。

1. 选择 **Create rule**（创建规则）。

1. 在 “**步骤 1：创建规则**” 页面的 “**事件源**” 部分，为 “**服务名称**” 选择 “**SageMaker AI**”，为 “**事件类型**” 选择 “**SageMaker AI Training Job 状态更改**”。事件模式预览应该类似于以下示例 JSON 字符串：

   ```
   {
       "source": [
           "aws.sagemaker"
       ],
       "detail-type": [
           "SageMaker Training Job State Change"
       ]
   }
   ```

1. 在**目标**部分，选择**添加目标\$1，然后选择您创建的-** jo **debugger-rule-stop-trainingb** Lambda 函数。此步骤将 CloudWatch 事件规则与 Lambda 函数关联起来。

1. 选择**配置详细信息**，然后转到**步骤 2：配置规则详细信息页面**。

1. 指定 CloudWatch 规则定义名称。例如 **debugger-cw-event-rule**。

1. 选择**创建规则**以完成操作。

1. 返回 Lambda 函数配置页面并刷新页面。在**设计器**面板中确认已正确配置函数。应将 CloudWatch 事件规则注册为 Lambda 函数的触发器。配置设计应类似于以下示例。  
<a name="lambda-designer-example"></a>![\[CloudWatch 配置的设计器面板。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-lambda-designer.png)

# 禁用 CloudWatch 事件规则以停止使用自动终止训练作业
<a name="debugger-disable-cw"></a>

如果要禁用自动终止训练作业，则需要禁用 CloudWatch 事件规则。在 Lambda **设计器**面板中，选择链接到 Lambda 函数的 **EventBridge （CloudWatch 事件）**模块。这会在 “**设计器 **EventBridge****” 面板下方显示一个面板（例如，参见上一个屏幕截图）。选中 **EventBridge （CloudWatch 事件）:** 旁边的复选框 debugger-cw-event-rule，然后选择**禁用**。如果您想稍后使用自动终止功能，可以再次启用 CloudWatch 事件规则。

# 在中可视化 Amazon SageMaker Debugger 输出张量 TensorBoard
<a name="debugger-enable-tensorboard-summaries"></a>

**重要**  
本页面已被弃用，取而代之的是使用 SageMaker Amazon AI TensoBoard，它提供了与 A SageMaker I 域的 SageMaker 培训和访问控制功能集成的全面 TensorBoard 体验。要了解更多信息，请参阅[TensorBoard 在亚马逊 A SageMaker I 中](tensorboard-on-sagemaker.md)。

使用 SageMaker Debugger 创建与兼容的输出张量文件。 TensorBoard加载文件以可视化 TensorBoard 并分析您的 SageMaker 训练作业。调试器会自动生成与兼容的输出张量文件。 TensorBoard对于您为保存输出张量而自定义的任何挂钩配置，Debugger 可以灵活地创建可以导入的标量摘要、分布和直方图。 TensorBoard

![\[Debugger 输出张量保存机制的架构图。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-tensorboard-concept.png)


您可以通过将 `DebuggerHookConfig` 和 `TensorBoardOutputConfig` 对象传递到 `estimator` 来启用此功能。

以下过程说明了如何将标量、权重和偏差保存为可视化的完整张量、直方图和分布。 TensorBoardDebugger 将它们保存到训练容器的本地路径（默认路径为 `/opt/ml/output/tensors`），并同步到通过 Debugger 输出配置对象传递的 Amazon S3 位置。

**使用调试 TensorBoard 器保存兼容的输出张量文件**

1. 使用 Debugger `TensorBoardOutputConfig` 类设置`tensorboard_output_config`配置对象以保存 TensorBoard 输出。对于`s3_output_path`参数，请指定当前 SageMaker AI 会话的默认 S3 存储桶或首选 S3 存储桶。此示例不会添加 `container_local_output_path` 参数；相反，它被设置为默认的本地路径 `/opt/ml/output/tensors`。

   ```
   import sagemaker
   from sagemaker.debugger import TensorBoardOutputConfig
   
   bucket = sagemaker.Session().default_bucket()
   tensorboard_output_config = TensorBoardOutputConfig(
       s3_output_path='s3://{}'.format(bucket)
   )
   ```

   有关更多信息，请参阅 [Amaz SageMaker on Python 软件开发工具包](https://sagemaker.readthedocs.io/en/stable)中的调试器 `[TensorBoardOutputConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.TensorBoardOutputConfig)` API。

1. 配置 Debugger 钩子并自定义挂钩参数值。例如，以下代码将 Debugger 钩子配置为在训练阶段每 100 步保存一次所有标量输出，在验证阶段每 10 步保存一次所有标量输出，每 500 步保存一次 `weights` 参数（保存张量集合的默认 `save_interval` 值为 500），每 10 个全局步骤保存一次 `bias` 参数，直到全局步骤数达到 500。

   ```
   from sagemaker.debugger import CollectionConfig, DebuggerHookConfig
   
   hook_config = DebuggerHookConfig(
       hook_parameters={
           "train.save_interval": "100",
           "eval.save_interval": "10"
       },
       collection_configs=[
           CollectionConfig("weights"),
           CollectionConfig(
               name="biases",
               parameters={
                   "save_interval": "10",
                   "end_step": "500",
                   "save_histogram": "True"
               }
           ),
       ]
   )
   ```

   有关调试器配置的更多信息 APIs，请参阅调试器`[CollectionConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig)`和 Amaz [on Pyth SageMaker on](https://sagemaker.readthedocs.io/en/stable) 软件开发工具包`[DebuggerHookConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.DebuggerHookConfig)` APIs 中的。

1. 使用传递配置 SageMaker 对象的调试器参数构造一个 AI 估计器。以下示例模板展示了如何创建通用 SageMaker AI 估算器。你可以`Estimator`用其他 SageMaker AI 框架的估算器父类`estimator`和估算器类替换和。此功能的可用的 SageMaker AI 框架估算器有`[TensorFlow](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html#create-an-estimator)``[PyTorch](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#create-an-estimator)`、和。`[MXNet](https://sagemaker.readthedocs.io/en/stable/frameworks/mxnet/using_mxnet.html#create-an-estimator)`

   ```
   from sagemaker.estimator import Estimator
   
   estimator = Estimator(
       ...
       # Debugger parameters
       debugger_hook_config=hook_config,
       tensorboard_output_config=tensorboard_output_config
   )
   estimator.fit()
   ```

   该`estimator.fit()`方法启动训练作业，然后 Debugger 将输出张量文件实时写入调试器 S3 输出路径和 S3 输出路径。 TensorBoard 要检索输出路径，请使用以下估算器方法：
   + 对于 Debugger S3 输出路径，请使用 `estimator.latest_job_debugger_artifacts_path()`。
   + 对于 S TensorBoard 3 输出路径，请使用`estimator.latest_job_tensorboard_artifacts_path()`。

1. 训练完成后，请检查保存的输出张量的名称：

   ```
   from smdebug.trials import create_trial
   trial = create_trial(estimator.latest_job_debugger_artifacts_path())
   trial.tensor_names()
   ```

1. 检查 Amazon S3 中的 TensorBoard 输出数据：

   ```
   tensorboard_output_path=estimator.latest_job_tensorboard_artifacts_path()
   print(tensorboard_output_path)
   !aws s3 ls {tensorboard_output_path}/
   ```

1. 将 TensorBoard 输出数据下载到您的笔记本实例。例如，以下 AWS CLI 命令将 TensorBoard 文件下载到笔记本实例的当前工作目录`/logs/fit`下。

   ```
   !aws s3 cp --recursive {tensorboard_output_path} ./logs/fit
   ```

1. 将文件目录压缩为 TAR 文件以下载到本地计算机。

   ```
   !tar -cf logs.tar logs
   ```

1. 将 Tensorboard TAR 文件下载并解压缩到设备上的某个目录中，启动 Jupyter 笔记本服务器，打开一个新的笔记本，然后运行该应用程序。 TensorBoard

   ```
   !tar -xf logs.tar
   %load_ext tensorboard
   %tensorboard --logdir logs/fit
   ```

以下动画屏幕截图介绍了步骤 5 至 8。它演示了如何下载 Debugger TensorBoard TAR 文件并将该文件加载到本地设备上的 Jupyter 笔记本中。

![\[关于如何在本地计算机上下载和加载调试器 TensorBoard文件的动画。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/debugger/debugger-tensorboard.gif)


# Debugger 内置规则列表
<a name="debugger-built-in-rules"></a>

您可以使用 Amazon SageMaker Debugger 提供的 Debugger 内置规则，分析在训练模型时收集的指标和张量。下面列出了 Debugger 规则，包括如何配置和部署每个内置规则的信息和示例。

Debugger 内置规则监控对成功运行训练作业至关重要的各种常见条件。您可以使用 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 或者是低级别的 SageMaker API 操作调用内置规则。

使用内置规则不会产生额外费用。有关计费的更多信息，请参阅 [Amazon SageMaker 定价](https://aws.amazon.com/sagemaker/pricing/)页面。

**注意**  
在一个训练作业上可以附加的内置规则的最大数量为 20。SageMaker Debugger 完全管理内置规则，并同步分析您的训练作业。

**重要**  
要使用新的 Debugger 功能，您需要升级 SageMaker Python SDK 和 SMDebug 客户端库。在您的 iPython 内核、Jupyter 笔记本或 JupyterLab 环境中，运行以下代码以安装最新版本的库并重新启动内核。  

```
import sys
import IPython
!{sys.executable} -m pip install -U sagemaker smdebug
IPython.Application.instance().kernel.do_shutdown(True)
```

## Debugger 规则
<a name="debugger-built-in-rules-Rule"></a>

以下规则是可使用 `Rule.sagemaker` 类方法调用的 Debugger 内置规则。

用于生成训练报告的 Debugger 内置规则


| 有效性范围 | 内置规则 | 
| --- | --- | 
| SageMaker AI XGboost 训练作业的训练报告 |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/debugger-built-in-rules.html)  | 

用于调试模型训练数据（输出张量）的 Debugger 内置规则


| 有效性范围 | 内置规则 | 
| --- | --- | 
| 深度学习框架（TensorFlow、MXNet 和 PyTorch） |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/debugger-built-in-rules.html)  | 
| 深度学习框架（TensorFlow、MXNet 和 PyTorch）和 XGBoost 算法  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/debugger-built-in-rules.html)  | 
| 深度学习应用程序 |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/debugger-built-in-rules.html)  | 
| XGBoost 算法 |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/debugger-built-in-rules.html)  | 

**使用内置规则及默认参数值** – 使用以下配置格式：

```
from sagemaker.debugger import Rule, ProfilerRule, rule_configs

rules = [
    Rule.sagemaker(rule_configs.built_in_rule_name_1()),
    Rule.sagemaker(rule_configs.built_in_rule_name_2()),
    ...
    Rule.sagemaker(rule_configs.built_in_rule_name_n())
]
```

**使用内置规则及自定义参数值** – 使用以下配置格式：

```
from sagemaker.debugger import Rule, ProfilerRule, rule_configs

rules = [
    Rule.sagemaker(
        base_config=rule_configs.built_in_rule_name(),
        rule_parameters={
                "key": "value"
        }
        collections_to_save=[ 
            CollectionConfig(
                name="tensor_collection_name", 
                parameters={
                    "key": "value"
                } 
            )
        ]
    )
]
```

要查找 `rule_parameters` 参数的可用键，请参阅参数描述表。

针对每个内置规则，参数描述表下方提供了示例规则配置代码。
+ 有关使用 Debugger 内置规则的完整说明和示例，请参阅 [Debugger 内置规则示例代码](debugger-built-in-rules-example.md#debugger-deploy-built-in-rules)。
+ 有关在低级 SageMaker API 操作中使用内置规则的完整说明，请参阅[使用 SageMaker API 配置调试器](debugger-createtrainingjob-api.md)。

## CreateXgboostReport
<a name="create-xgboost-report"></a>

CreateXgboostReport 规则从 XGBoost 训练作业收集输出张量，并自动生成综合训练报告。您可以在训练作业运行期间或训练作业完成后，下载综合分析报告，以查看训练的进度或训练作业的最终结果。默认情况下，CreateXgboostReport 规则收集以下输出张量：
+ `hyperparameters` – 在第一个步骤保存
+ `metrics` – 每 5 个步骤保存损失和准确性
+ `feature_importance` – 每 5 个步骤保存一次
+ `predictions` – 每 5 个步骤保存一次
+ `labels` – 每 5 个步骤保存一次

CreateXgboostReport 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial | 基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 

```
rules=[
    Rule.sagemaker(
        rule_configs.create_xgboost_report()
    )  
]
```

## DeadRelu
<a name="dead-relu"></a>

此规则检测试验中的修正线性单元 (ReLU) 激活函数的百分比是否因它们的激活活动已降至阈值以下而被视为死亡。如果层中非活跃 ReLU 的百分比大于非活跃 ReLU 的 `threshold_layer` 值，则该规则会返回 `True`。

DeadRelu 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| tensor\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串列表或逗号分隔的字符串  默认值：`".*relu_output"`  | 
| threshold\$1inactivity |  定义一个活动级别，低于该级别的 ReLU 将被视为死亡。ReLU 可能在试验开始时处于活动状态，然后在训练过程中慢慢死亡。如果 ReLU 处于活动状态并低于 `threshold_inactivity`，则将其视为死亡。 **可选** 有效值：浮点值 默认值：`1.0`（百分比）  | 
| threshold\$1layer |  如果层中非活跃 ReLU 百分比大于 `threshold_layer`，则返回 `True`。 如果层中非活跃 ReLU 百分比小于 `threshold_layer`，则返回 `False`。 **可选** 有效值：浮点值 默认值：`50.0`（百分比）  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.dead_relu(),
        rule_parameters={
                "tensor_regex": ".*relu_output|.*ReLU_output",
                "threshold_inactivity": "1.0",
                "threshold_layer": "50.0"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="custom_relu_collection", 
                parameters={
                    "include_regex: ".*relu_output|.*ReLU_output",
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

**注意**  
此规则对 XGBoost 算法不可用。

## ExplodingTensor
<a name="exploding-tensor"></a>

此规则检测训练期间发射的张量是否具有非有限值，即无限值或 NaN（不是数字）。如果检测到非有限值，则该规则返回 `True`。

ExplodingTensor 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| collection\$1names |  该规则检查其张量的集合名称列表。 **可选** 有效值：字符串 默认值：`None`  | 
| tensor\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串  默认值：`None`  | 
| only\$1nan |   如果为 `True`，则仅监视 `base_trial` 张量是否为 `NaN` 值，而不监视无穷大。 如果为 `False`，则将 `NaN` 和无穷大都视为爆炸值并监视两者。 **可选** 默认值：`False`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.exploding_tensor(),
        rule_parameters={
                "tensor_regex": ".*gradient",
                "only_nan": "False"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="gradients", 
                parameters={
                    "save_interval": "500"
                }
            )
        ]
    )
]
```

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

**注意**  
此规则对 XGBoost 算法不可用。

## PoorWeightInitialization
<a name="poor-weight-initialization"></a>

 此规则检测模型参数是否初始化不当。

良好的初始化会破坏神经网络中权重和梯度的对称性，并在各层之间保持相应的激活方差。否则，神经网络无法有效地学习。诸如 Xavier 之类的初始化程序旨在使激活之间的方差保持恒定，这对于训练非常深的神经网络尤其重要。初始化太小可能会导致梯度消失。初始化过大可能会导致梯度爆炸。此规则检查各层激活输入的方差、梯度分布以及初始步骤的损失收敛性，确定神经网络是否初始化不当。

PoorWeightInitialization 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| activation\$1inputs\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串 默认值：`".*relu_input"`  | 
| threshold |  如果每个层的权重的最小方差和最大方差之间的比率超过某个步骤中的 `threshold`，则该规则返回 `True`。 **可选** 有效值：浮点值 默认值：`10.0`  | 
| distribution\$1range |  如果梯度分布的第 5 百分位数和第 95 百分位数之间的最小差值小于 `distribution_range`，则该规则返回 `True`。 **可选** 有效值：浮点值 默认值：`0.001`  | 
| patience |  等到损失被认为不再减少的步骤数。 **可选** 有效值：整数 默认值：`5`  | 
| steps |  此规则分析的步骤数。您通常只需要检查前几次迭代。 **可选** 有效值：浮点值 默认值：`10`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.poor_weight_initialization(),
        rule_parameters={
                "activation_inputs_regex": ".*relu_input|.*ReLU_input",
                "threshold": "10.0",
                "distribution_range": "0.001",
                "patience": "5",
                "steps": "10"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="custom_relu_collection", 
                parameters={
                    "include_regex": ".*relu_input|.*ReLU_input",
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

**注意**  
此规则对 XGBoost 算法不可用。

## SaturatedActivation
<a name="saturated-activation"></a>

此规则检测 tanh 和 sigmoid 激活层是否正在变得饱和。当层的输入接近激活函数的最大或最小值时，激活层将饱和。tanh 和 sigmoid 激活函数的最小和最大值由它们各自的 `min_threshold` 和 `max_thresholds` 值定义。如果节点的活动降到 `threshold_inactivity` 百分比以下，则将其视为饱和。如果超过 `threshold_layer` 百分比的节点处于饱和状态，则该规则返回 `True`。

SaturatedActivation 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| collection\$1names |  该规则检查其张量的集合名称列表。 **可选** 有效值：字符串列表或逗号分隔的字符串 默认值：无  | 
| tensor\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串  默认值：`".*tanh_input\|.*sigmoid_input".`  | 
| threshold\$1tanh\$1min |  定义 tanh 激活函数输入极值的最小和最大阈值，定义为：`(min_threshold, max_threshold)`。默认值是根据梯度消失阈值 0.0000001 确定的。 **可选** 有效值：浮点值 默认值：`-9.4999`  | 
| threshold\$1tanh\$1max |  定义 tanh 激活函数输入极值的最小和最大阈值，定义为：`(min_threshold, max_threshold)`。默认值是根据梯度消失阈值 0.0000001 确定的。 **可选** 有效值：浮点值 默认值：`9.4999`  | 
| threshold\$1sigmoid\$1min |  定义 sigmoid 激活函数输入极值的最小和最大阈值，定义为：`(min_threshold, max_threshold)`。默认值是根据梯度消失阈值 0.0000001 确定的。 **可选** 有效值：浮点值 默认值：`-23`  | 
| threshold\$1sigmoid\$1max |  定义 sigmoid 激活函数输入极值的最小和最大阈值，定义为：`(min_threshold, max_threshold)`。默认值是根据梯度消失阈值 0.0000001 确定的。 **可选** 有效值：浮点值 默认值：`16.99999`  | 
| threshold\$1inactivity |  不活动百分比，低于该百分比的激活层被视为饱和。激活可能在试验开始时处于活动状态，然后在训练过程中逐渐变得不那么活跃。 **可选** 有效值：浮点值 默认值：`1.0`  | 
| threshold\$1layer |  如果层中的饱和激活数大于 `threshold_layer` 百分比，则返回 `True`。 如果层中的饱和激活数小于 `threshold_layer` 百分比，则返回 `False`。 **可选** 有效值：浮点值 默认值：`50.0`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.saturated_activation(),
        rule_parameters={
                "tensor_regex": ".*tanh_input|.*sigmoid_input",
                "threshold_tanh_min": "-9.4999",
                "threshold_tanh_max": "9.4999",
                "threshold_sigmoid_min": "-23",
                "threshold_sigmoid_max": "16.99999",
                "threshold_inactivity": "1.0",
                "threshold_layer": "50.0"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="custom_activations_collection",
                parameters={
                    "include_regex": ".*tanh_input|.*sigmoid_input"
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

**注意**  
此规则对 XGBoost 算法不可用。

## VanishingGradient
<a name="vanishing-gradient"></a>

该规则检测试验中的梯度是否变得非常小或降至零幅度。如果梯度绝对值的平均值低于指定的 `threshold`，则该规则返回 `True`。

VanishingGradient 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| threshold | 确定梯度消失的值。**可选**有效值：浮点值默认值：`0.0000001`。 | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.vanishing_gradient(),
        rule_parameters={
                "threshold": "0.0000001"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="gradients", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

**注意**  
此规则对 XGBoost 算法不可用。

## WeightUpdateRatio
<a name="weight-update-ratio"></a>

此规则跟踪训练期间更新与权重的比率，并检测该比率是过大还是过小。如果更新与权重的比率大于 `large_threshold value` 或者此比率小于 `small_threshold`，则该规则返回 `True`。

当更新与梯度相当时，训练条件是最佳的。过大的更新会使权重远离最佳值，而过小的更新会导致收敛速度非常慢。此规则要求权重可用于两个训练步骤，因此 `train.save_interval` 需要设置为 `num_steps`。

WeightUpdateRatio 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| num\$1steps |  该规则检查以确定张量是否已更改的步骤数。 要比较权重比率的步骤数。如果未传递任何值，则默认情况下，将针对当前步骤和紧接的上一个保存步骤运行该规则。如果您通过传递此参数的值来覆盖默认值，则会在步骤 `s` 和步骤 `>= s - num_steps` 的权重之间进行比较。 **可选** 有效值：整数 默认值：`None`  | 
| large\$1threshold |  要执行加权的更新比率可以取的最大值，超过该值时规则将返回 `True`。 **可选** 有效值：浮点值 默认值：`10.0`  | 
| small\$1threshold |  要执行加权的更新比率可以取的最小值，低于该值时规则将返回 `True`。 **可选** 有效值：浮点值 默认值：`0.00000001`  | 
| epsilon |  一个小常量，用于确保 Debugger 在计算加权的更新比率时不会被零除。 **可选** 有效值：浮点值 默认值：`0.000000001`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.weight_update_ratio(),
        rule_parameters={
                "num_steps": "100",
                "large_threshold": "10.0",
                "small_threshold": "0.00000001",
                "epsilon": "0.000000001"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="weights", 
                parameters={
                    "train.save_interval": "100"
                } 
            )
        ]
    )
]
```

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

**注意**  
此规则对 XGBoost 算法不可用。

## AllZero
<a name="all-zero"></a>

此规则检测张量中的全部值还是指定百分比的值为零。

此规则可应用于受支持的深度学习框架（TensorFlow、MXNet 和 PyTorch）之一，也可以应用于 XGBoost 算法。必须指定 `collection_names` 或 `tensor_regex` 参数。如果指定了这两个参数，则规则将检查两个集合内张量的并集。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

AllZero 的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| collection\$1names |  该规则检查其张量的集合名称列表。 **可选** 有效值：字符串列表或逗号分隔的字符串 默认值：`None`  | 
| tensor\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串列表或逗号分隔的字符串 默认值：`None`  | 
| threshold |  指定张量中必须为零才能调用此规则的值的百分比。 **可选** 有效值：浮点值 默认值：100（百分比）  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.all_zero(),
        rule_parameters={
                "tensor_regex": ".*",
                "threshold": "100"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="all", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## ClassImbalance
<a name="class-imbalance"></a>

此规则用于衡量分类之间的采样不平衡，如果不平衡状况超过阈值，或者由于不平衡而导致代表性不足的分类发生太多错误预测，则会引发错误。

分类模型需要训练数据集内的分类保持良好平衡，或者在训练期间对分类执行适当的加权/取样。该规则执行以下检查：
+  它计算每个分类的发生次数。如果最小分类和最大分类之间的样本数比率大于 `threshold_imbalance`，则会引发错误。
+  它检查每个分类的预测精度。如果未正确应用重采样或加权，则模型对于具有许多训练样本的分类来说可以达到较高的精度，但对于训练样本少的分类来说，精度较低。如果某个分类的错误预测比例大于 `threshold_misprediction`，则会引发错误。

此规则可应用于受支持的深度学习框架（TensorFlow、MXNet 和 PyTorch）之一，也可以应用于 XGBoost 算法。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

ClassImbalance 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| threshold\$1imbalance |  最小分类和最大分类中样本数之间可接受的不平衡。超过此阈值会引发错误。 **可选** 有效值：浮点值 默认值：`10`  | 
| threshold\$1misprediction |  对每个分类允许的错误预测部分的限制。超过此阈值会引发错误。代表性不足的分类最有可能超过此阈值。 **可选** 有效值：浮点值 默认值：`0.7`  | 
| samples |  在评估不平衡之前必须处理的标签数。在多个步骤中看到足够的样本之前，可能不会触发该规则。数据集包含的分类越多，此 `sample` 数值应越大。 **可选** 有效值：整数 默认值：`500`（假设像 MNIST 这样的数据集有 10 个类）  | 
| argmax |  如果为 `True`，则 [np.argmax](https://docs.scipy.org/doc/numpy-1.9.3/reference/generated/numpy.argmax.html) 应用于预测张量。当您对每个分类都有概率向量时，此项是必需的。它用于确定哪个分类具有最高概率。 **条件** 有效值：布尔值 默认值：`False`  | 
| labels\$1regex |  包含标签的张量的名称。 **可选** 有效值：字符串 默认值：`".*labels"`  | 
| predictions\$1regex |  包含预测的张量的名称。 **可选** 有效值：字符串 默认值：`".*predictions"`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.class_imbalance(),
        rule_parameters={
                "threshold_imbalance": "10",
                "threshold_misprediction": "0.7",
                "samples": "500",
                "argmax": "False",
                "labels_regex": ".*labels",
                "predictions_regex": ".*predictions"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="custom_output_collection",
                parameters={
                    "include_regex": ".*labels|.*predictions",
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## LossNotDecreasing
<a name="loss-not-decreasing"></a>

此规则检测值损失是否以适当的速度减少。这些损失必须是标量。

此规则可应用于受支持的深度学习框架（TensorFlow、MXNet 和 PyTorch）之一，也可以应用于 XGBoost 算法。必须指定 `collection_names` 或 `tensor_regex` 参数。如果指定了这两个参数，则规则将检查两个集合内张量的并集。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

LossNotDecreasing 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| collection\$1names |  该规则检查其张量的集合名称列表。 **可选** 有效值：字符串列表或逗号分隔的字符串 默认值：`None`  | 
| tensor\$1regex |  一个正则表达式模式列表，用于将此比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串列表或逗号分隔的字符串  默认值：`None`  | 
| use\$1losses\$1collection |  如果设置为 `True`，则当名为“losses”的集合存在时，查找该集合中的损失。 **可选** 有效值：布尔值 默认值：`True`  | 
| num\$1steps |  该规则检查损失是否已减少的最小步骤数。规则评估每 `num_steps` 个步骤发生一次。该规则将此步骤的损失与至少比当前步骤落后 `num_steps` 的步骤的损失进行比较。例如，假设每三个步骤保存一次损失，但 `num_steps` 设置为 10。在步骤 21 中，将步骤 21 的损失与步骤 9 的损失进行比较。检查损失的下一个步骤是步骤 33，因为步骤 21 之后的第十个步骤是步骤 31，并且在步骤 31 和步骤 32 中不保存损失。 **可选** 有效值：整数 默认值：`10`  | 
| diff\$1percent |  在 `num_steps` 个步骤之间，损失应减少的最小百分比差异。 **可选** 有效值：`0.0` < 浮点值 < `100` 默认值：`0.1`（百分比）  | 
| increase\$1threshold\$1percent |  在损失一直在增加的情况下，允许损失增加的最大阈值百分比 **可选** 有效值：`0` < 浮点值 < `100` 默认值：`5`（百分比）  | 
| mode |  用于查询张量值以进行规则检查的 Debugger 模式的名称。如果未传递该参数，规则默认按顺序进行检查，先检查 `mode.EVAL`，然后检查 `mode.TRAIN`，最后检查 `mode.GLOBAL`。 **可选** 有效值：字符串（`EVAL`、`TRAIN` 或 `GLOBAL`） 默认值：`GLOBAL`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.loss_not_decreasing(),
        rule_parameters={
                "tensor_regex": ".*",
                "use_losses_collection": "True",
                "num_steps": "10",
                "diff_percent": "0.1",
                "increase_threshold_percent": "5",
                "mode": "GLOBAL"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="losses", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## Overfit
<a name="overfit"></a>

此规则通过比较验证和训练损失来检测模型是否与训练数据过度拟合。

此规则可应用于受支持的深度学习框架（TensorFlow、MXNet 和 PyTorch）之一，也可以应用于 XGBoost 算法。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

**注意**  
防止过度拟合的标准方法是对模型进行规范化。

Overfit 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| tensor\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串列表或逗号分隔的字符串  默认值：无  | 
| start\$1step |  开始比较验证和训练损失的步骤。 **可选** 有效值：整数 默认值：`0`  | 
| patience |  在模型被视为过度拟合之前允许 `ratio_threshold` 超过设置的值的步数。 **可选** 有效值：整数 默认值：`1`  | 
| ratio\$1threshold |  平均验证损失和平均训练损失之间的差异与平均训练损失的最大比率。如果 `patience` 个步骤超过此阈值，则表示模型过度拟合，并且规则返回 `True`。 **可选** 有效值：浮点值 默认值：`0.1`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.overfit(),
        rule_parameters={
                "tensor_regex": ".*",
                "start_step": "0",
                "patience": "1",
                "ratio_threshold": "0.1"
        },
        collections_to_save=[
            CollectionConfig(
                name="losses", 
                parameters={
                    "train.save_interval": "100",
                    "eval.save_interval": "10"
                } 
            )
        ]
    )
]
```

## Overtraining
<a name="overtraining"></a>

此规则检测模型是否过度训练。在对行为良好的模型进行了多次训练迭代（训练和验证损失均减少）之后，模型接近损失函数的最低限度，并且不再改善。如果模型继续训练，则可能会发生验证损失开始增加的情况，因为模型开始过度拟合。此规则设置阈值和条件，以确定模型是否没有改进，并防止由于过度训练导致的过度拟合问题。

此规则可应用于受支持的深度学习框架（TensorFlow、MXNet 和 PyTorch）之一，也可以应用于 XGBoost 算法。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

**注意**  
可以通过提前停止来避免过度训练。有关提前停止的信息，请参阅[提前停止训练作业](automatic-model-tuning-early-stopping.md)。有关演示如何对 Debugger 使用竞价型实例训练的示例，请参阅[对 Amazon SageMaker Debugger 启用竞价型实例训练](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/mxnet_spot_training/mxnet-spot-training-with-sagemakerdebugger.html)。

Overtraining 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| patience\$1train |  在认为训练损失不再有改进之前等待的步骤数。 **可选** 有效值：整数 默认值：`5`  | 
| patience\$1validation | 在认为验证损失不再有改进之前等待的步骤数。**可选**有效值：整数默认值：`10` | 
| delta |  误差被视为新的最佳值之前应改进的误差程度的最小阈值。 **可选** 有效值：浮点值 默认值：`0.01`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.overtraining(),
        rule_parameters={
                "patience_train": "5",
                "patience_validation": "10",
                "delta": "0.01"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="losses", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## SimilarAcrossRuns
<a name="similar-across-runs"></a>

此规则将从基本试验中收集的张量与从另一试验中收集的张量进行比较。

此规则可应用于受支持的深度学习框架（TensorFlow、MXNet 和 PyTorch）之一，也可以应用于 XGBoost 算法。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

SimilarAcrossRuns 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| other\$1trials |  已完成的训练作业名称，您需要将其张量与从当前 `base_trial` 收集的张量进行比较。 **必填** 有效值：字符串  | 
| collection\$1names |  该规则检查其张量的集合名称列表。 **可选** 有效值：字符串列表或逗号分隔的字符串 默认值：无  | 
| tensor\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串列表或逗号分隔的字符串  默认值：无  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.similar_across_runs(),
        rule_parameters={
                "other_trials": "<specify-another-job-name>",
                "collection_names": "losses",
                "tensor_regex": ".*"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="losses", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## StalledTrainingRule
<a name="stalled-training"></a>

StalledTrainingRule 检测训练作业是否没有进展，如果规则触发，则停止训练作业。此规则要求按照其 `threshold` 参数定义的时间间隔定期保存张量。此规则会继续监控新张量，如果没有发出新的张量，将触发阈值间隔规则。

StalledTrainingRule 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| threshold |  定义规则等待张量输出时间长度（以秒为单位）的阈值，超过该值后会触发停滞训练问题。默认值为 1800 秒。 **可选** 有效值：整数 默认值：`1800`  | 
| stop\$1training\$1on\$1fire |  如果设置为 `True`，则监视基础训练作业是否在“`threshold`”秒内输出张量。 **可选** 有效值：布尔值 默认值：`False`  | 
| training\$1job\$1name\$1prefix |  基础训练作业名称的前缀。如果 `stop_training_on_fire` 为 true，则该规则将在相同账户中搜索带有此前缀的 SageMaker 训练作业。如果发现不活动状态，则规则执行 `StopTrainingJob` 操作。请注意，如果找到多个具有相同前缀的作业，则规则将跳过终止。因此务必要为每个训练作业设置唯一的前缀。 **可选** 有效值：字符串  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.stalled_training_rule(),
        rule_parameters={
                "threshold": "1800",
                "stop_training_on_fire": "True",
                "training_job_name_prefix": "<specify-training-base-job-name>"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="losses", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## TensorVariance
<a name="tensor-variance"></a>

该规则检测您是否具有方差非常高或非常低的张量。张量中的非常高或非常低的方差可能会导致神经元饱和，从而降低神经网络的学习能力。张量非常高的方差最终还会产生张量爆炸问题。使用此规则可以提前检测出此类问题。

此规则可应用于受支持的深度学习框架（TensorFlow、MXNet 和 PyTorch）之一，也可以应用于 XGBoost 算法。必须指定 `collection_names` 或 `tensor_regex` 参数。如果指定了这两个参数，则规则将检查两个集合内张量的并集。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

TensorVariance 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| collection\$1names |  该规则检查其张量的集合名称列表。 **可选** 有效值：字符串列表或逗号分隔的字符串 默认值：无  | 
| tensor\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串列表或逗号分隔的字符串  默认值：无  | 
| max\$1threshold |  张量方差上限的阈值。 **可选** 有效值：浮点值 默认值：无  | 
| min\$1threshold |  张量方差下限的阈值。 **可选** 有效值：浮点值 默认值：无  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.tensor_variance(),
        rule_parameters={
                "collection_names": "weights",
                "max_threshold": "10",
                "min_threshold": "0.00001",
        },
        collections_to_save=[ 
            CollectionConfig(
                name="weights", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## UnchangedTensor
<a name="unchanged-tensor"></a>

此规则检测张量是否不再随步骤而发生更改。

此规则运行 [numpy.allclose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html) 方法来检查张量是否未发生更改。

此规则可应用于受支持的深度学习框架（TensorFlow、MXNet 和 PyTorch）之一，也可以应用于 XGBoost 算法。必须指定 `collection_names` 或 `tensor_regex` 参数。如果指定了这两个参数，则规则将检查两个集合内张量的并集。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

UnchangedTensor 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| collection\$1names |  该规则检查其张量的集合名称列表。 **可选** 有效值：字符串列表或逗号分隔的字符串 默认值：无  | 
| tensor\$1regex |  正则表达式模式列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串列表或逗号分隔的字符串  默认值：无  | 
| num\$1steps |  该规则检查以确定张量是否已更改的步骤数。 规则将检查可用的最后 `num_steps` 个步骤。步骤不必是连续的。如果 `num_steps` 是 2，则在第 s 个步骤处，规则不一定检查第 s-1 个步骤和第 s 个步骤。如果第 s-1 个步骤不可用，规则会检查最后一个可用步骤以及第 s 个步骤。在这种情况下，规则会检查最后一个可用步骤及当前步骤。 **可选** 有效值：整数 默认值：`3`  | 
| rtol |  要传递给 `[numpy.allclose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html)` 方法的相对容差参数。 **可选** 有效值：浮点值 默认值：`1e-05`  | 
| atol |  要传递给 `[numpy.allclose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html)` 方法的绝对容差参数。 **可选** 有效值：浮点值 默认值：`1e-08`  | 
| equal\$1nan |  比较 NaN 时是否视为相等。如果为 `True`，则在输出数组中将输入数组 a 中的 NaN 视为等于输入数组 b 中的 NaN。此参数传递给 `[numpy.allclose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html)` 方法。 **可选** 有效值：布尔值 默认值：`False`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.unchanged_tensor(),
        rule_parameters={
                "collection_names": "losses",
                "tensor_regex": "",
                "num_steps": "3",
                "rtol": "1e-05",
                "atol": "1e-08",
                "equal_nan": "False"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="losses", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## CheckInputImages
<a name="checkinput-mages"></a>

此规则检查输入图像是否已正确归一化。具体而言，规则会检测样本数据的平均值与零之间的差异是否超过阈值。许多计算机视觉模型要求输入数据的平均值和单位方差为零。

此规则适用于深度学习应用程序。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

CheckInputImages 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| threshold\$1mean |  一个阈值，该阈值定义输入数据的平均值可以与 0 相差多少。 **可选** 有效值：浮点值 默认值：`0.2`  | 
| threshold\$1samples |  在引发错误之前必须采样的图像数量。如果值过低，则对数据集平均值的估计将不准确。 **可选** 有效值：整数 默认值：`500`  | 
| regex |  输入数据张量的名称。 **可选** 有效值：字符串 默认值：`".*hybridsequential0_input_0"`（使用 HybridSequential 的 Apache MXNet 模型的输入张量的名称）  | 
| channel |  颜色通道在输入张量形状数组中的位置。 **可选** 有效值：整数 默认值：`1`（例如，MXNet 需要输入数据采用以下形式：(batch\$1size, channel, height, width)  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.check_input_images(),
        rule_parameters={
                "threshold_mean": "0.2",
                "threshold_samples": "500",
                "regex": ".*hybridsequential0_input_0",
                "channel": "1"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="custom_inputs_collection", 
                parameters={
                    "include_regex": ".*hybridsequential0_input_0",
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## NLPSequenceRatio
<a name="nlp-sequence-ratio"></a>

给定其余输入序列（对于优化性能很有用）的情况下，此规则将计算特定令牌的比率。例如，您可以计算输入序列中填充句尾 (EOS) 令牌的百分比。如果 EOS 令牌数量过高，则应执行替代分桶策略。您还可以计算输入序列中未知令牌的百分比。如果未知单词的数量过高，可以使用替代词汇表。

此规则适用于深度学习应用程序。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

NLPSequenceRatio 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| tensor\$1regex |  正则表达式规律列表，用于将该比较限制为特定的标量值张量。该规则仅检查与列表中指定的正则表达式规律匹配的张量。如果未传递任何规律，则该规则默认情况下比较试验中收集的所有张量。只能匹配标量值张量。 **可选** 有效值：字符串列表或逗号分隔的字符串  默认值：`".*embedding0_input_0"`（假设作为网络的初始层嵌入）  | 
| token\$1values |  一个由令牌数值列表构成的字符串。例如，"3, 0"。 **可选** 有效值：以逗号分隔的数值字符串 默认值：`0`  | 
| token\$1thresholds\$1percent |  一个字符串，由与 `token_values` 的每个令牌对应的阈值（以百分比为单位）列表构成。例如，"50.0, 50.0"。 **可选** 有效值：以逗号分隔的浮点值字符串 默认值：`"50"`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.nlp_sequence_ratio(),
        rule_parameters={
                "tensor_regex": ".*embedding0_input_0",
                "token_values": "0",
                "token_thresholds_percent": "50"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="custom_inputs_collection", 
                parameters={
                    "include_regex": ".*embedding0_input_0"
                } 
            )
        ]
    )
]
```

## Confusion
<a name="confusion"></a>

此规则评估分类问题的混淆矩阵的优点。

它创建一个大小为 `category_no*category_no` 的矩阵，并使用来自 (`labels`, `predictions`) 对的数据填充该矩阵。对于每个 (`labels`, `predictions`) 对，`confusion[labels][predictions]` 中的计数增加 1。当完全填充矩阵后，按以下所示计算数据对角线值和非对角线值的比率：
+ 对于对角线上的元素：`confusion[i][i]/sum_j(confusion[j][j])>=min_diag`
+ 对于非对角线上的元素：`confusion[j][i])/sum_j(confusion[j][i])<=max_off_diag`

此规则可应用于 XGBoost 算法。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

Confusion 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| category\$1no |  类别的数量。 **可选** 有效值：≥2 的整数 默认值：`"None"`  | 
| labels |  `labels` 张量集合或真实标签的一维矢量。 **可选** 有效值：字符串 默认值：`"labels"`  | 
| predictions |  `predictions` 张量集合或估算标签的一维矢量。 **可选** 有效值：字符串 默认值：`"predictions"`  | 
| labels\$1collection |  该规则针对 `labels` 检查此集合中的张量。 **可选** 有效值：字符串 默认值：`"labels"`  | 
| predictions\$1collection |  该规则针对 `predictions` 检查此集合中的张量。 **可选** 有效值：字符串 默认值：`"predictions"`  | 
| min\$1diag |  对角线上数据比率的最小值。 **可选** 有效值：`0` ≤ 浮点值 ≤ `1` 默认值：`0.9`  | 
| max\$1off\$1diag |  对角线以外的数据比率的最大值。 **可选** 有效值：`0` ≤ 浮点值 ≤ `1` 默认值：`0.1`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.confusion(),
        rule_parameters={
                "category_no": "10",
                "labels": "labels",
                "predictions": "predictions",
                "labels_collection": "labels",
                "predictions_collection": "predictions",
                "min_diag": "0.9",
                "max_off_diag": "0.1"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="labels",
                parameters={
                    "save_interval": "500"
                } 
            ),
            CollectionConfig(
                name="predictions",
                parameters={
                    "include_regex": "500"
                } 
            )
        ]
    )
]
```

**注意**  
如果未指定可选参数的值，则此规则会推断采用默认值。

## FeatureImportanceOverweight
<a name="feature_importance_overweight"></a>

此规则累积每个步骤的 n 个最大特征重要性值的权重，并确保它们不会超过阈值。例如，您可以将前 3 个特征的阈值设置为不超过模型总权重的 80%。

此规则仅对 XGBoost 算法有效。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

FeatureImportanceOverweight 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| threshold |  定义 `n` 个最大特征的累积和占比的阈值。数字 `n` 由 `nfeatures` 参数定义。 **可选** 有效值：浮点值 默认值：`0.8`  | 
| nfeatures |  最大特征的数量。 **可选** 有效值：整数 默认值：`3`  | 
| tensor\$1regex |  规则要分析的张量名称的正则表达式 (regex)。 **可选** 有效值：字符串 默认值：`".*feature_importance/weight"`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.feature_importance_overweight(),
        rule_parameters={
                "threshold": "0.8",
                "nfeatures": "3",
                "tensor_regex": ".*feature_importance/weight"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="feature_importance", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

## TreeDepth
<a name="tree-depth"></a>

此规则测量 XGBoost 模型中树的深度。如果拆分不能改进损失，则 XGBoost 会拒绝拆分。这会将训练规范化。因此，树的深度可能不会达到 `depth` 参数定义的深度。

此规则仅对 XGBoost 算法有效。

有关如何配置和部署内置规则的示例，请参阅[如何配置 Debugger 内置规则](use-debugger-built-in-rules.md)。

TreeDepth 规则的参数描述


| 参数名称 | 描述 | 
| --- | --- | 
| base\$1trial |  基本试验训练作业名称。Amazon SageMaker Debugger 会自动将此参数设置为当前的训练作业。 **必填** 有效值：字符串  | 
| depth |  树的深度。通过计算最大节点 ID 的以 2 为底的对数，可以获得树的深度。 **可选** 有效值：浮点值 默认值：`4`  | 

```
built_in_rules = [
    Rule.sagemaker(
        base_config=rule_configs.tree_depth(),
        rule_parameters={
                "depth": "4"
        },
        collections_to_save=[ 
            CollectionConfig(
                name="tree", 
                parameters={
                    "save_interval": "500"
                } 
            )
        ]
    )
]
```

# 使用 Debugger 客户端库创建自定义规则
<a name="debugger-custom-rules"></a>

您可以使用调试器规则 APIs 和提供用于构建自己的规则容器的工具的开源 [`smdebug`Python 库](https://github.com/awslabs/sagemaker-debugger/)来创建自定义规则来监控您的训练作业。

## 创建自定义规则的先决条件
<a name="debugger-custom-rules-prerequisite"></a>

要创建 Debugger 自定义规则，您需要满足以下先决条件。
+ [SageMaker 调试器规则. 自定义 API](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.Rule.custom)
+ [开源 smdebug Python 库](https://github.com/awslabs/sagemaker-debugger/)
+ 您自己的自定义规则 python 脚本
+ [URIs 适用于自定义规则评估者的 Amazon SageMaker 调试器图片](debugger-reference.md#debuger-custom-rule-registry-ids)

**Topics**
+ [创建自定义规则的先决条件](#debugger-custom-rules-prerequisite)
+ [使用 `smdebug` 客户端库以 Python 脚本创建自定义规则](debugger-custom-rules-python-script.md)
+ [使用调试器 APIs 运行您自己的自定义规则](debugger-custom-rules-python-sdk.md)

# 使用 `smdebug` 客户端库以 Python 脚本创建自定义规则
<a name="debugger-custom-rules-python-script"></a>

`smdebug` 规则 API 提供了一个接口，用于设置自己的自定义规则。以下 Python 脚本示例演示了如何构造自定义规则 `CustomGradientRule`。本教程的自定义规则监控梯度变是否太大并将默认阈值设置为 10。自定义规则采用 A SageMaker I 估算器在启动训练作业时创建的基础试验。

```
from smdebug.rules.rule import Rule

class CustomGradientRule(Rule):
    def __init__(self, base_trial, threshold=10.0):
        super().__init__(base_trial)
        self.threshold = float(threshold)

    def invoke_at_step(self, step):
        for tname in self.base_trial.tensor_names(collection="gradients"):
            t = self.base_trial.tensor(tname)
            abs_mean = t.reduction_value(step, "mean", abs=True)
            if abs_mean > self.threshold:
                return True
        return False
```

您可以在同一个 python 脚本中按需要添加任意数量的自定义规则类，并通过在下个部分中构造自定义规则对象，来将它们部署到任何训练作业试验中。

# 使用调试器 APIs 运行您自己的自定义规则
<a name="debugger-custom-rules-python-sdk"></a>

以下代码示例展示了如何使用 [Amaz SageMaker on Python 软件开发工具包](https://sagemaker.readthedocs.io/en/stable)配置自定义规则。此示例假设您在上一步中创建的自定义规则脚本位于 '*path/to/my\$1custom\$1rule.py*'。

```
from sagemaker.debugger import Rule, CollectionConfig

custom_rule = Rule.custom(
    name='MyCustomRule',
    image_uri='759209512951.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rule-evaluator:latest', 
    instance_type='ml.t3.medium',     
    source='path/to/my_custom_rule.py', 
    rule_to_invoke='CustomGradientRule',     
    collections_to_save=[CollectionConfig("gradients")], 
    rule_parameters={"threshold": "20.0"}
)
```

下面的列表解释了 Debugger `Rule.custom` API 参数。
+ `name`（字符串）：指定所需的自定义规则名称。
+ `image_uri`（字符串）：这是容器的映像，该容器中具有了解您的自定义规则的逻辑。它获取您保存在训练作业中的指定张量集合并进行评估。您可以从[URIs 适用于自定义规则评估者的 Amazon SageMaker 调试器图片](debugger-reference.md#debuger-custom-rule-registry-ids)中找到开源 SageMaker AI 规则评估器图像列表。
+ `instance_type`（字符串）：您需要指定一个实例来构建规则 Docker 容器。这将启动一个与训练容器并行的实例。
+ `source`（字符串）：这是自定义规则脚本的本地路径或 Amazon S3 URI。
+ `rule_to_invoke`(str)：这指定了自定义规则脚本中特定的规则类实现。 SageMaker 在规则作业中，AI 一次仅支持对一条规则进行评估。
+ `collections_to_save`（字符串）：此项指定了要保存哪些张量集合用于要运行的规则。
+ `rule_parameters`（字典）：这将接受字典格式的参数输入。您可以调整在自定义规则脚本中配置的参数。

设置`custom_rule`对象后，您可以使用它为任何训练作业构建 A SageMaker I 估算器。对您的训练脚本指定 `entry_point`。您不需要对训练脚本进行任何更改。

```
from sagemaker.tensorflow import TensorFlow

estimator = TensorFlow(
                role=sagemaker.get_execution_role(),
                base_job_name='smdebug-custom-rule-demo-tf-keras',
                entry_point='path/to/your_training_script.py'
                train_instance_type='ml.p2.xlarge'
                ...
                
                # debugger-specific arguments below
                rules = [custom_rule]
)

estimator.fit()
```

有关使用 Debugger 自定义规则的更多变体和高级示例，请参阅以下示例笔记本。
+ [使用 Amazon SageMaker Debugger 自定义规则监控您的训练作业](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_keras_custom_rule/tf-keras-custom-rule.html)
+ [PyTorch 迭代模型修剪和 ResNet AlexNet](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/pytorch_iterative_model_pruning)
+ [使用调试器规则触发 Amazon CloudWatch 事件，根据训练状态执行操作 TensorFlow](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/tensorflow_action_on_rule)

# 使用 Debugger 和自定义训练容器
<a name="debugger-bring-your-own-container"></a>

Amazon SageMaker Debugger 适用于你带到 Amazon A SageMaker I 的任何深度学习模型。 SageMaker A `Estimator` I API 和调试器 APIs 使您能够使用任何 Docker 基础镜像来构建和自定义容器来训练模型。 AWS CLI要将 Debugger 与自定义容器结合使用，您只需对训练脚本进行极少的更改，以实施 Debugger 钩子回调并从训练作业中检索张量。以下部分介绍了如何使用 Debugger 和自定义训练容器。

您需要以下资源来使用 Debugger 构建自定义容器。
+ [亚马逊 SageMaker Python 软件开发工具包](https://sagemaker.readthedocs.io/en/stable)
+ [ SMDebug 开源客户端库](https://github.com/awslabs/sagemaker-debugger)
+ 您选择的 Docker 基本映像
+ 您的训练脚本并注册了 Debugger 钩子 – 有关将 Debugger 钩子注册到训练脚本的更多信息，请参阅[在训练脚本中注册 Debugger 钩子](#debugger-script-mode)。

有关在自定义训练容器中使用 Debugger 的示 end-to-end例，请参阅以下示例笔记本。
+ [使用 Debugger 构建自定义训练容器和调试训练作业](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/build_your_own_container_with_debugger/debugger_byoc.html)

**提示**  
此带 Debugger 的自定义容器指南是对[调整自己的训练容器](adapt-training-container.md)指南的扩展，向您详细介绍如何构建自定义训练容器并将其推送到 Amazon ECR。

## 准备构建自定义训练容器
<a name="debugger-bring-your-own-container-1"></a>

要构建 Docker 容器，文件的基本结构应如下所示：

```
├── debugger_custom_container_test_notebook.ipynb      # a notebook to run python snippet codes
└── debugger_custom_container_test_folder              # this is a docker folder
    ├──  your-training-script.py                       # your training script with Debugger hook
    └──  Dockerfile                                    # a Dockerfile to build your own container
```

## 在训练脚本中注册 Debugger 钩子
<a name="debugger-script-mode"></a>

要调试模型训练，您需要在训练脚本中添加 Debugger 钩子。

**注意**  
此步骤是收集模型参数（输出张量）以调试模型训练所必需的。如果您只想进行监控和分析，则可以跳过此钩子注册步骤，并在构造估算器时排除 `debugger_hook_config` 参数。

以下示例代码显示了使用 Keras ResNet 50 模型的训练脚本的结构，以及如何将调试器挂钩作为 Keras 回调传递以进行调试。要查找完整的训练脚本，请参阅[带有 SageMaker Debugger 挂钩的TensorFlow 训练脚本](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-debugger/build_your_own_container_with_debugger/docker/tf_keras_resnet_byoc.py)。

```
# An example of training script (your-training-script.py)
import tensorflow.compat.v2 as tf
from tensorflow.keras.applications.resnet50 import ResNet50
import smdebug.tensorflow as smd

def train(batch_size, epoch, model, hook):

    ...
    model.fit(X_train, Y_train,
              batch_size=batch_size,
              epochs=epoch,
              validation_data=(X_valid, Y_valid),
              shuffle=True,

              # smdebug modification: Pass the Debugger hook in the main() as a Keras callback
              callbacks=[hook])

def main():
    parser=argparse.ArgumentParser(description="Train resnet50 cifar10")

    # hyperparameter settings
    parser.add_argument(...)
    
    args = parser.parse_args()

    model=ResNet50(weights=None, input_shape=(32,32,3), classes=10)

    # Add the following line to register the Debugger hook for Keras.
    hook=smd.KerasHook.create_from_json_file()

    # Start the training.
    train(args.batch_size, args.epoch, model, hook)

if __name__ == "__main__":
    main()
```

有关为支持的框架和算法注册 Debugger 挂钩的更多信息，请参阅 SMDebug 客户端库中的以下链接：
+ [SMDebug TensorFlow hook](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/tensorflow.md)
+ [SMDebug PyTorch hook](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/pytorch.md)
+ [SMDebug MXNet hook](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/mxnet.md)
+ [SMDebug XGBoost hook](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/xgboost.md)

在以下示例笔记本的训练脚本中，您可以找到更多示例，详细说明了如何将 Debugger 钩子添加到训练脚本和收集输出张量：
+ [使用 TensorFlow 2.1 框架的脚本模式调试器](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow2/tensorflow2_keras_custom_container/tf2-keras-custom-container.html)

  要查看在深度学习容器中使用调试器与在脚本模式下使用调试器的区别，请打开此笔记本并将其与[之前的调试器并排放在深度学习容器 TensorFlow v2.1 笔记本示例中](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow2/tensorflow2_zero_code_change/tf2-keras-default-container.html)。

   在脚本模式下，挂钩配置部分将从您设置评估程序的脚本中删除。取而代之的是，调试器挂钩功能被合并到训练脚本中，即脚本模式下的 [ TensorFlow Keras ResNet 训练脚本](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-debugger/tensorflow2/tensorflow2_keras_custom_container/src/tf_keras_resnet_byoc.py)。训练脚本将`smdebug`库导入所需的 TensorFlow Keras 环境中，以便与 TensorFlow ResNet 50 算法进行通信。它还通过在`train`函数中添加`callbacks=[hook]`参数（在第 49 行）和添加通过 SageMaker Python SDK 提供的手动挂钩配置（在第 89 行中）来手动实现挂钩功能。`smdebug`

  该脚本模式示例在 TF 2.1 框架中运行训练作业，以便与 TF 2.1 示例中的零脚本更改进行直接比较。在脚本模式下设置调试器的好处是，可以灵活地选择 Dee AWS p Learning Containers 未涵盖的框架版本。
+ [在脚本模式下在 PyTorch 容 SageMaker 器中使用 Amazon 调试器](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/pytorch_custom_container)

  此笔记本在 PyTorch v1.3.1 框架中启用脚本模式下的调试器。 PyTorchv1.3.1 受 A SageMaker I 容器支持，此示例显示了如何修改训练脚本的详细信息。

  默认 SageMaker 情况下，AI PyTorch 估算器已处于脚本模式。在该笔记本中，在评估程序配置中不包含激活 `script_mode` 的行。

  本笔记本显示了将[原始 PyTorch 训练脚本](https://github.com/pytorch/examples/blob/master/mnist/main.py)更改为修改版本以启用 Debugger 的详细步骤。此外，该示例还说明了如何使用 Debugger 内置规则检测训练问题（如梯度消失问题），以及如何使用 Debugger 试验功能调用和分析保存的张量。

## 创建和配置 Dockerfile
<a name="debugger-bring-your-own-container-2"></a>

打开您的 SageMaker AI JupyterLab 并创建一个新文件夹，在此示例`debugger_custom_container_test_folder`中，用于保存您的训练脚本和`Dockerfile`。以下代码示例是 `Dockerfile`，其中包括了必要的 Docker 构建注释。将以下代码粘贴到 `Dockerfile` 文本文件中并保存。将训练脚本上传到同一个文件夹。

```
# Specify a docker base image
FROM tensorflow/tensorflow:2.2.0rc2-gpu-py3
RUN /usr/bin/python3 -m pip install --upgrade pip
RUN pip install --upgrade protobuf

# Install required packages to enable the SageMaker Python SDK and the smdebug library
RUN pip install sagemaker-training
RUN pip install smdebug
CMD ["bin/bash"]
```

如果你想使用预先构建的 AWS 深度学习容器镜像，请参阅[可用的 AWS 深度学习容器镜像](https://aws.amazon.com/releasenotes/available-deep-learning-containers-images/)。

## 创建并向 Amazon ECR 推送自定义训练映像
<a name="debugger-bring-your-own-container-3"></a>

创建测试笔记本 `debugger_custom_container_test_notebook.ipynb`，然后在笔记本单元中运行以下代码。这将访问 `debugger_byoc_test_docker` 目录，使用指定的 `algorithm_name` 构建 Docker，然后将 Docker 容器推送到 Amazon ECR 中。

```
import boto3

account_id = boto3.client('sts').get_caller_identity().get('Account')
ecr_repository = 'sagemaker-debugger-mnist-byoc-tf2'
tag = ':latest'

region = boto3.session.Session().region_name

uri_suffix = 'amazonaws.com'
if region in ['cn-north-1', 'cn-northwest-1']:
    uri_suffix = 'amazonaws.com.cn'
byoc_image_uri = '{}.dkr.ecr.{}.{}/{}'.format(account_id, region, uri_suffix, ecr_repository + tag)

!docker build -t $ecr_repository docker
!$(aws ecr get-login --region $region --registry-ids $account_id --no-include-email)
!aws ecr create-repository --repository-name $ecr_repository
!docker tag {ecr_repository + tag} $byoc_image_uri
!docker push $byoc_image_uri
```

**提示**  
如果您使用 AWS 深度学习容器基础映像之一，请运行以下代码登录 Amazon ECR 并访问深度学习容器镜像存储库。  

```
! aws ecr get-login-password --region {region} | docker login --username AWS --password-stdin 763104351884.dkr.ecr.us-east-1.amazonaws.com
```

## 使用自定义训练容器运行和调试训练作业
<a name="debugger-bring-your-own-container-4"></a>

在构建 docker 容器并将其推送到 Amazon ECR 后，请使用您的训练脚本和调试器特定的参数配置 SageMaker AI 估算器。执行 `estimator.fit()` 之后，Debugger 将收集输出张量、监控它们并检测训练问题。使用保存的张量，您可以使用 `smdebug` 核心功能和工具进一步分析训练作业。使用 Amazon Ev CloudWatch ents 配置调试器规则监控流程的工作流程 AWS Lambda，每当调试器规则发现训练问题时，您就可以自动停止训练作业流程。

```
import sagemaker
from sagemaker.estimator import Estimator
from sagemaker.debugger import Rule, DebuggerHookConfig, CollectionConfig, rule_configs

profiler_config=ProfilerConfig(...)
debugger_hook_config=DebuggerHookConfig(...)
rules=[
    Rule.sagemaker(rule_configs.built_in_rule()),
    ProfilerRule.sagemaker(rule_configs.BuiltInRule())
]

estimator=Estimator(
    image_uri=byoc_image_uri,
    entry_point="./debugger_custom_container_test_folder/your-training-script.py"
    role=sagemaker.get_execution_role(),
    base_job_name='debugger-custom-container-test',
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    
    # Debugger-specific parameters
    profiler_config=profiler_config,
    debugger_hook_config=debugger_hook_config,
    rules=rules
)

# start training
estimator.fit()
```

# 使用 SageMaker API 配置调试器
<a name="debugger-createtrainingjob-api"></a>

 前面的主题重点介绍如何通过 Amaz SageMaker on Python SDK 使用调试器，该软件开发工具包是一个封装程序 适用于 Python (Boto3) 的 AWS SDK 和 SageMaker API 操作。这提供了访问亚马逊 SageMaker API 操作的高级体验。如果您需要使用 AWS Boto3 或 (CLI) 手动配置 SageMaker AP AWS Command Line Interface I 操作 SDKs，例如 Java、Go 和 C\$1\$1，则本节将介绍如何配置以下低级 API 操作。

**Topics**
+ [JSON (AWS CLI)](debugger-built-in-rules-api.CLI.md)
+ [适用于 Python 的 SDK（Boto3）](debugger-built-in-rules-api.Boto3.md)

# JSON (AWS CLI)
<a name="debugger-built-in-rules-api.CLI"></a>

可以通过 A [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)I AP SageMaker I 操作使用[DebugHookConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html)、[DebugRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html)、[ProfilerConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerConfig.html)和[ProfilerRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleConfiguration.html)对象为训练作业配置 Amazon D SageMaker ebugger 内置规则。您需要在`RuleEvaluatorImage`参数中指定正确的图片 URI，以下示例将引导您完成如何设置要请求的 JSON 字符串[CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)。

以下代码显示了一个完整的 JSON 模板，用于使用所需设置和 Debugger 配置来运行训练作业。将模板另存为工作目录中的 JSON 文件，然后使用 AWS CLI 运行训练作业。例如，将以下代码另存为 `debugger-training-job-cli.json`。

**注意**  
确保使用正确的 Docker 容器映像。要查找 AWS 深度学习容器镜像，请参阅[可用的 Deep Learning Containers 镜像](https://github.com/aws/deep-learning-containers/blob/master/available_images.md)。要查找使用 Debugger 规则时可用的 Docker 映像的完整列表，请参阅[用于 Debugger 规则的 Docker 映像](debugger-reference.md#debugger-docker-images-rules)。

```
{
   "TrainingJobName": "debugger-aws-cli-test",
   "RoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonSageMaker-ExecutionRole-YYYYMMDDT123456",
   "AlgorithmSpecification": {
      // Specify a training Docker container image URI (Deep Learning Container or your own training container) to TrainingImage.
      "TrainingImage": "763104351884.dkr.ecr.us-west-2.amazonaws.com/tensorflow-training:2.4.1-gpu-py37-cu110-ubuntu18.04",
      "TrainingInputMode": "File",
      "EnableSageMakerMetricsTimeSeries": false
   },
   "HyperParameters": {
      "sagemaker_program": "entry_point/tf-hvd-train.py",
      "sagemaker_submit_directory": "s3://sagemaker-us-west-2-111122223333/debugger-boto3-profiling-test/source.tar.gz"
   },
   "OutputDataConfig": { 
      "S3OutputPath": "s3://sagemaker-us-west-2-111122223333/debugger-aws-cli-test/output"
   },
   "DebugHookConfig": { 
      "S3OutputPath": "s3://sagemaker-us-west-2-111122223333/debugger-aws-cli-test/debug-output",
      "CollectionConfigurations": [
         {
            "CollectionName": "losses",
            "CollectionParameters" : {
                "train.save_interval": "50"
            }
         }
      ]
   },
   "DebugRuleConfigurations": [ 
      { 
         "RuleConfigurationName": "LossNotDecreasing",
         "RuleEvaluatorImage": "895741380848.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rules:latest",
         "RuleParameters": {"rule_to_invoke": "LossNotDecreasing"}
      }
   ],
   "ProfilerConfig": { 
      "S3OutputPath": "s3://sagemaker-us-west-2-111122223333/debugger-aws-cli-test/profiler-output",
      "ProfilingIntervalInMilliseconds": 500,
      "ProfilingParameters": {
          "DataloaderProfilingConfig": "{\"StartStep\": 5, \"NumSteps\": 3, \"MetricsRegex\": \".*\", }",
          "DetailedProfilingConfig": "{\"StartStep\": 5, \"NumSteps\": 3, }",
          "PythonProfilingConfig": "{\"StartStep\": 5, \"NumSteps\": 3, \"ProfilerName\": \"cprofile\", \"cProfileTimer\": \"total_time\"}",
          "LocalPath": "/opt/ml/output/profiler/" 
      }
   },
   "ProfilerRuleConfigurations": [ 
      { 
         "RuleConfigurationName": "ProfilerReport",
         "RuleEvaluatorImage": "895741380848.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rules:latest",
         "RuleParameters": {"rule_to_invoke": "ProfilerReport"}
      }
   ],
   "ResourceConfig": { 
      "InstanceType": "ml.p3.8xlarge",
      "InstanceCount": 1,
      "VolumeSizeInGB": 30
   },
   
   "StoppingCondition": { 
      "MaxRuntimeInSeconds": 86400
   }
}
```

保存 JSON 文件后，在终端中运行以下命令。（如果您使用 Jupyter 笔记本，则在行的开头使用 `!`。）

```
aws sagemaker create-training-job --cli-input-json file://debugger-training-job-cli.json
```

## 配置 Debugger 规则以调试模型参数
<a name="debugger-built-in-rules-api-debug.CLI"></a>

以下代码示例展示了如何使用此 SageMaker API 配置内置`VanishingGradient`规则。

**启用 Debugger 收集输出张量**

按如下方式指定 Debugger 钩子配置：

```
"DebugHookConfig": {
    "S3OutputPath": "s3://<default-bucket>/<training-job-name>/debug-output",
    "CollectionConfigurations": [
        {
            "CollectionName": "gradients",
            "CollectionParameters" : {
                "save_interval": "500"
            }
        }
    ]
}
```

这将使训练作业按每 500 个步骤的 `save_interval` 保存一次 `gradients` 张量集合。要查找可用`CollectionName`值，请参阅*SMDebug 客户端库文档*中的[调试器内置集合](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#built-in-collections)。要查找可用的`CollectionParameters`参数键和值，请参阅 *SageMaker Python SDK 文档*中的[https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig)类。

**启用 Debugger 规则来调试输出张量**

以下`DebugRuleConfigurations` API 示例说明了如何对已保存的 `gradients` 集合运行内置 `VanishingGradient` 规则。

```
"DebugRuleConfigurations": [
    {
        "RuleConfigurationName": "VanishingGradient",
        "RuleEvaluatorImage": "503895931360.dkr.ecr.us-east-1.amazonaws.com/sagemaker-debugger-rules:latest",
        "RuleParameters": {
            "rule_to_invoke": "VanishingGradient",
            "threshold": "20.0"
        }
    }
]
```

通过类似于此示例中的配置，Debugger 使用 `VanishingGradient` 规则，在 `gradients` 张量的集合上为您的训练作业启动规则评估作业。要查找使用 Debugger 规则时可用的 Docker 映像的完整列表，请参阅[用于 Debugger 规则的 Docker 映像](debugger-reference.md#debugger-docker-images-rules)。要查找 `RuleParameters` 的键值对，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

## 为分析系统和框架指标配置 Debugger 内置规则
<a name="debugger-built-in-rules-api-profile.CLI"></a>

以下示例代码演示如何指定 ProfilerConfig API 操作以启用收集系统和框架指标。

**启用 Debugger 分析以收集系统和框架指标**

------
#### [ Target Step ]

```
"ProfilerConfig": { 
    // Optional. Path to an S3 bucket to save profiling outputs
    "S3OutputPath": "s3://<default-bucket>/<training-job-name>/profiler-output", 
    // Available values for ProfilingIntervalInMilliseconds: 100, 200, 500, 1000 (1 second), 5000 (5 seconds), and 60000 (1 minute) milliseconds.
    "ProfilingIntervalInMilliseconds": 500, 
    "ProfilingParameters": {
        "DataloaderProfilingConfig": "{ \"StartStep\": 5, \"NumSteps\": 3, \"MetricsRegex\": \".*\" }",
        "DetailedProfilingConfig": "{ \"StartStep\": 5, \"NumSteps\": 3 }",
        // For PythonProfilingConfig,
        // available ProfilerName options: cProfile, Pyinstrument
        // available cProfileTimer options only when using cProfile: cpu, off_cpu, total_time
        "PythonProfilingConfig": "{ \"StartStep\": 5, \"NumSteps\": 3, \"ProfilerName\": \"cProfile\", \"cProfileTimer\": \"total_time\" }",
        // Optional. Local path for profiling outputs
        "LocalPath": "/opt/ml/output/profiler/" 
    }
}
```

------
#### [ Target Time Duration ]

```
"ProfilerConfig": { 
    // Optional. Path to an S3 bucket to save profiling outputs
    "S3OutputPath": "s3://<default-bucket>/<training-job-name>/profiler-output", 
    // Available values for ProfilingIntervalInMilliseconds: 100, 200, 500, 1000 (1 second), 5000 (5 seconds), and 60000 (1 minute) milliseconds.
    "ProfilingIntervalInMilliseconds": 500,
    "ProfilingParameters": {
        "DataloaderProfilingConfig": "{ \"StartTimeInSecSinceEpoch\": 12345567789, \"DurationInSeconds\": 10, \"MetricsRegex\": \".*\" }",
        "DetailedProfilingConfig": "{ \"StartTimeInSecSinceEpoch\": 12345567789, \"DurationInSeconds\": 10 }",
        // For PythonProfilingConfig,
        // available ProfilerName options: cProfile, Pyinstrument
        // available cProfileTimer options only when using cProfile: cpu, off_cpu, total_time
        "PythonProfilingConfig": "{ \"StartTimeInSecSinceEpoch\": 12345567789, \"DurationInSeconds\": 10, \"ProfilerName\": \"cProfile\", \"cProfileTimer\": \"total_time\" }",
        // Optional. Local path for profiling outputs
        "LocalPath": "/opt/ml/output/profiler/"  
    }
}
```

------

**启用 Debugger 规则来分析指标**

以下示例代码显示了如何配置 `ProfilerReport` 规则。

```
"ProfilerRuleConfigurations": [ 
    {
        "RuleConfigurationName": "ProfilerReport",
        "RuleEvaluatorImage": "895741380848.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rules:latest",
        "RuleParameters": {
            "rule_to_invoke": "ProfilerReport",
            "CPUBottleneck_cpu_threshold": "90",
            "IOBottleneck_threshold": "90"
        }
    }
]
```

要查找使用 Debugger 规则时可用的 Docker 映像的完整列表，请参阅[用于 Debugger 规则的 Docker 映像](debugger-reference.md#debugger-docker-images-rules)。要查找 `RuleParameters` 的键值对，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

## 使用 `UpdateTrainingJob` API 更新 Debugger 剖析配置
<a name="debugger-updatetrainingjob-api.CLI"></a>

在训练作业运行期间，可以使用 [UpdateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateTrainingJob.html)API 操作更新调试器分析配置。配置新的[ProfilerConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerConfig.html)和[ProfilerRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleConfiguration.html)对象，并在`TrainingJobName`参数中指定训练作业名称。

```
{
    "ProfilerConfig": { 
        "DisableProfiler": boolean,
        "ProfilingIntervalInMilliseconds": number,
        "ProfilingParameters": { 
            "string" : "string" 
        }
    },
    "ProfilerRuleConfigurations": [ 
        { 
            "RuleConfigurationName": "string",
            "RuleEvaluatorImage": "string",
            "RuleParameters": { 
                "string" : "string" 
            }
        }
    ],
    "TrainingJobName": "your-training-job-name-YYYY-MM-DD-HH-MM-SS-SSS"
}
```

## 在 `CreateTrainingJob` API 中添加 Debugger 自定义规则配置
<a name="debugger-custom-rules-api.CLI"></a>

可以在 [ CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)API 操作中使用[ DebugHookConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html)和[ DebugRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html)对象为训练作业配置自定义规则。以下代码示例显示了如何使用此 SageMaker API 操作配置使用 *smdebug* 库编写的自定义`ImproperActivation`规则。此示例假定您已在 *custom\$1rules.py* 文件中编写自定义规则，并将其上传到 Amazon S3 存储桶。该示例提供了预构建的 Docker 映像，您可以使用这些映像运行自定义规则。[URIs 适用于自定义规则评估者的 Amazon SageMaker 调试器图片](debugger-reference.md#debuger-custom-rule-registry-ids) 中列出了这些映像。您可以在 `RuleEvaluatorImage` 参数中为预构建的 Docker 映像指定 URL 注册表地址。

```
"DebugHookConfig": {
    "S3OutputPath": "s3://<default-bucket>/<training-job-name>/debug-output",
    "CollectionConfigurations": [
        {
            "CollectionName": "relu_activations",
            "CollectionParameters": {
                "include_regex": "relu",
                "save_interval": "500",
                "end_step": "5000"
            }
        }
    ]
},
"DebugRulesConfigurations": [
    {
        "RuleConfigurationName": "improper_activation_job",
        "RuleEvaluatorImage": "552407032007.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-debugger-rule-evaluator:latest",
        "InstanceType": "ml.c4.xlarge",
        "VolumeSizeInGB": 400,
        "RuleParameters": {
           "source_s3_uri": "s3://bucket/custom_rules.py",
           "rule_to_invoke": "ImproperActivation",
           "collection_names": "relu_activations"
        }
    }
]
```

要查找使用 Debugger 规则时可用的 Docker 映像的完整列表，请参阅[用于 Debugger 规则的 Docker 映像](debugger-reference.md#debugger-docker-images-rules)。要查找 `RuleParameters` 的键值对，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

# 适用于 Python 的 SDK（Boto3）
<a name="debugger-built-in-rules-api.Boto3"></a>

可以使用 B AWS oto3 SageMaker AI 客户端的[https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_training_job](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_training_job)功能为训练作业配置 Amazon D SageMaker ebugger 内置规则。您需要在 `RuleEvaluatorImage` 参数中指定正确的映像 URI，以下示例演示如何为 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_training_job](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_training_job) 函数设置请求正文。

以下代码显示了一个完整的示例，说明如何为`create_training_job()`请求正文配置 Debugger 并在中`us-west-2`启动训练作业（假设使用 TensorFlow准备了训练脚本`entry_point/train.py`）。要查找 end-to-end示例笔记本，请参阅[使用 Amazon D SageMaker ebugger 分析多 GPU TensorFlow 多节点训练 Job (Boto3)](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node-boto3.html)。

**注意**  
确保使用正确的 Docker 容器映像。要查找可用的 AWS 深度学习容器镜像，请参阅[可用的 Deep Learning Containers 镜像](https://github.com/aws/deep-learning-containers/blob/master/available_images.md)。要查找使用 Debugger 规则时可用的 Docker 映像的完整列表，请参阅[用于 Debugger 规则的 Docker 映像](debugger-reference.md#debugger-docker-images-rules)。

```
import sagemaker, boto3
import datetime, tarfile

# Start setting up a SageMaker session and a Boto3 SageMaker client
session = sagemaker.Session()
region = session.boto_region_name
bucket = session.default_bucket()

# Upload a training script to a default Amazon S3 bucket of the current SageMaker session
source = 'source.tar.gz'
project = 'debugger-boto3-test'

tar = tarfile.open(source, 'w:gz')
tar.add ('entry_point/train.py') # Specify the directory and name of your training script
tar.close()

s3 = boto3.client('s3')
s3.upload_file(source, bucket, project+'/'+source)

# Set up a Boto3 session client for SageMaker
sm = boto3.Session(region_name=region).client("sagemaker")

# Start a training job
sm.create_training_job(
    TrainingJobName='debugger-boto3-'+datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'),
    HyperParameters={
        'sagemaker_submit_directory': 's3://'+bucket+'/'+project+'/'+source,
        'sagemaker_program': '/entry_point/train.py' # training scrip file location and name under the sagemaker_submit_directory
    },
    AlgorithmSpecification={
        # Specify a training Docker container image URI (Deep Learning Container or your own training container) to TrainingImage.
        'TrainingImage': '763104351884.dkr.ecr.us-west-2.amazonaws.com/tensorflow-training:2.4.1-gpu-py37-cu110-ubuntu18.04',
        'TrainingInputMode': 'File',
        'EnableSageMakerMetricsTimeSeries': False
    },
    RoleArn='arn:aws:iam::111122223333:role/service-role/AmazonSageMaker-ExecutionRole-20201014T161125',
    OutputDataConfig={'S3OutputPath': 's3://'+bucket+'/'+project+'/output'},
    ResourceConfig={
        'InstanceType': 'ml.p3.8xlarge',
        'InstanceCount': 1,
        'VolumeSizeInGB': 30
    },
    StoppingCondition={
        'MaxRuntimeInSeconds': 86400
    },
    DebugHookConfig={
        'S3OutputPath': 's3://'+bucket+'/'+project+'/debug-output',
        'CollectionConfigurations': [
            {
                'CollectionName': 'losses',
                'CollectionParameters' : {
                    'train.save_interval': '500',
                    'eval.save_interval': '50'
                }
            }
        ]
    },
    DebugRuleConfigurations=[
        {
            'RuleConfigurationName': 'LossNotDecreasing',
            'RuleEvaluatorImage': '895741380848.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rules:latest',
            'RuleParameters': {'rule_to_invoke': 'LossNotDecreasing'}
        }
    ],
    ProfilerConfig={
        'S3OutputPath': 's3://'+bucket+'/'+project+'/profiler-output',
        'ProfilingIntervalInMilliseconds': 500,
        'ProfilingParameters': {
            'DataloaderProfilingConfig': '{"StartStep": 5, "NumSteps": 3, "MetricsRegex": ".*", }',
            'DetailedProfilingConfig': '{"StartStep": 5, "NumSteps": 3, }',
            'PythonProfilingConfig': '{"StartStep": 5, "NumSteps": 3, "ProfilerName": "cprofile", "cProfileTimer": "total_time"}',
            'LocalPath': '/opt/ml/output/profiler/' # Optional. Local path for profiling outputs
        }
    },
    ProfilerRuleConfigurations=[
        {
            'RuleConfigurationName': 'ProfilerReport',
            'RuleEvaluatorImage': '895741380848.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rules:latest',
            'RuleParameters': {'rule_to_invoke': 'ProfilerReport'}
        }
    ]
)
```

## 配置 Debugger 规则以调试模型参数
<a name="debugger-built-in-rules-api-debug.Boto3"></a>

以下代码示例展示了如何使用此 SageMaker API 配置内置`VanishingGradient`规则。

**启用 Debugger 收集输出张量**

按如下方式指定 Debugger 钩子配置：

```
DebugHookConfig={
    'S3OutputPath': 's3://<default-bucket>/<training-job-name>/debug-output',
    'CollectionConfigurations': [
        {
            'CollectionName': 'gradients',
            'CollectionParameters' : {
                'train.save_interval': '500',
                'eval.save_interval': '50'
            }
        }
    ]
}
```

这将使训练作业按每 500 个步骤的 `save_interval` 保存一次 `gradients` 张量集合。要查找可用`CollectionName`值，请参阅*SMDebug 客户端库文档*中的[调试器内置集合](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#built-in-collections)。要查找可用的`CollectionParameters`参数键和值，请参阅 *SageMaker Python SDK 文档*中的[https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig)类。

**启用 Debugger 规则来调试输出张量**

以下`DebugRuleConfigurations` API 示例说明了如何对已保存的 `gradients` 集合运行内置 `VanishingGradient` 规则。

```
DebugRuleConfigurations=[
    {
        'RuleConfigurationName': 'VanishingGradient',
        'RuleEvaluatorImage': '895741380848.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rules:latest',
        'RuleParameters': {
            'rule_to_invoke': 'VanishingGradient',
            'threshold': '20.0'
        }
    }
]
```

通过类似于此示例中的配置，Debugger 使用 `VanishingGradient` 规则，在 `gradients` 张量的集合上为您的训练作业启动规则评估作业。要查找使用 Debugger 规则时可用的 Docker 映像的完整列表，请参阅[用于 Debugger 规则的 Docker 映像](debugger-reference.md#debugger-docker-images-rules)。要查找 `RuleParameters` 的键值对，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

## 为分析系统和框架指标配置 Debugger 内置规则
<a name="debugger-built-in-rules-api-profile.Boto3"></a>

以下示例代码演示如何指定 ProfilerConfig API 操作以启用收集系统和框架指标。

**启用 Debugger 分析以收集系统和框架指标**

------
#### [ Target Step ]

```
ProfilerConfig={ 
    'S3OutputPath': 's3://<default-bucket>/<training-job-name>/profiler-output', # Optional. Path to an S3 bucket to save profiling outputs
    # Available values for ProfilingIntervalInMilliseconds: 100, 200, 500, 1000 (1 second), 5000 (5 seconds), and 60000 (1 minute) milliseconds.
    'ProfilingIntervalInMilliseconds': 500, 
    'ProfilingParameters': {
        'DataloaderProfilingConfig': '{
            "StartStep": 5, 
            "NumSteps": 3, 
            "MetricsRegex": ".*"
        }',
        'DetailedProfilingConfig': '{
            "StartStep": 5, 
            "NumSteps": 3 
        }',
        'PythonProfilingConfig': '{
            "StartStep": 5, 
            "NumSteps": 3, 
            "ProfilerName": "cprofile",  # Available options: cprofile, pyinstrument
            "cProfileTimer": "total_time"  # Include only when using cprofile. Available options: cpu, off_cpu, total_time
        }',
        'LocalPath': '/opt/ml/output/profiler/' # Optional. Local path for profiling outputs
    }
}
```

------
#### [ Target Time Duration ]

```
ProfilerConfig={ 
    'S3OutputPath': 's3://<default-bucket>/<training-job-name>/profiler-output', # Optional. Path to an S3 bucket to save profiling outputs
    # Available values for ProfilingIntervalInMilliseconds: 100, 200, 500, 1000 (1 second), 5000 (5 seconds), and 60000 (1 minute) milliseconds.
    'ProfilingIntervalInMilliseconds': 500,
    'ProfilingParameters': {
        'DataloaderProfilingConfig': '{
            "StartTimeInSecSinceEpoch": 12345567789, 
            "DurationInSeconds": 10, 
            "MetricsRegex": ".*"
        }',
        'DetailedProfilingConfig': '{
            "StartTimeInSecSinceEpoch": 12345567789, 
            "DurationInSeconds": 10
        }',
        'PythonProfilingConfig': '{
            "StartTimeInSecSinceEpoch": 12345567789, 
            "DurationInSeconds": 10, 
            "ProfilerName": "cprofile",  # Available options: cprofile, pyinstrument
            "cProfileTimer": "total_time"  # Include only when using cprofile. Available options: cpu, off_cpu, total_time
        }',
        'LocalPath': '/opt/ml/output/profiler/' # Optional. Local path for profiling outputs
    }
}
```

------

**启用 Debugger 规则来分析指标**

以下示例代码显示了如何配置 `ProfilerReport` 规则。

```
ProfilerRuleConfigurations=[ 
    {
        'RuleConfigurationName': 'ProfilerReport',
        'RuleEvaluatorImage': '895741380848.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rules:latest',
        'RuleParameters': {
            'rule_to_invoke': 'ProfilerReport',
            'CPUBottleneck_cpu_threshold': '90',
            'IOBottleneck_threshold': '90'
        }
    }
]
```

要查找使用 Debugger 规则时可用的 Docker 映像的完整列表，请参阅[用于 Debugger 规则的 Docker 映像](debugger-reference.md#debugger-docker-images-rules)。要查找 `RuleParameters` 的键值对，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

## 使用 `UpdateTrainingJob` API 操作更新 Debugger 分析配置
<a name="debugger-updatetrainingjob-api.Boto3"></a>

在训练作业运行期间，可以使用 AWS Boto3 SageMaker AI 客户端的[https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.update_training_job](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.update_training_job)功能更新调试器分析配置。配置新的[ProfilerConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerConfig.html)和[ProfilerRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleConfiguration.html)对象，并在`TrainingJobName`参数中指定训练作业名称。

```
ProfilerConfig={ 
    'DisableProfiler': boolean,
    'ProfilingIntervalInMilliseconds': number,
    'ProfilingParameters': { 
        'string' : 'string' 
    }
},
ProfilerRuleConfigurations=[ 
    { 
        'RuleConfigurationName': 'string',
        'RuleEvaluatorImage': 'string',
        'RuleParameters': { 
            'string' : 'string' 
        }
    }
],
TrainingJobName='your-training-job-name-YYYY-MM-DD-HH-MM-SS-SSS'
```

## 在 CreateTrainingJob API 操作中添加调试器自定义规则配置
<a name="debugger-custom-rules-api.Boto3"></a>

可以使用 AWS Boto3 SageMaker AI 客户端的功能使用[ DebugHookConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html)和[ DebugRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html)对象为训练作业配置自定义规则。[https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_training_job](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_training_job)以下代码示例显示了如何使用此 SageMaker API 操作配置使用 *smdebug* 库编写的自定义`ImproperActivation`规则。此示例假定您已在 *custom\$1rules.py* 文件中编写自定义规则，并将其上传到 Amazon S3 存储桶。该示例提供了预构建的 Docker 映像，您可以使用这些映像运行自定义规则。[URIs 适用于自定义规则评估者的 Amazon SageMaker 调试器图片](debugger-reference.md#debuger-custom-rule-registry-ids) 中列出了这些映像。您可以在 `RuleEvaluatorImage` 参数中为预构建的 Docker 映像指定 URL 注册表地址。

```
DebugHookConfig={
    'S3OutputPath': 's3://<default-bucket>/<training-job-name>/debug-output',
    'CollectionConfigurations': [
        {
            'CollectionName': 'relu_activations',
            'CollectionParameters': {
                'include_regex': 'relu',
                'save_interval': '500',
                'end_step': '5000'
            }
        }
    ]
},
DebugRulesConfigurations=[
    {
        'RuleConfigurationName': 'improper_activation_job',
        'RuleEvaluatorImage': '552407032007.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-debugger-rule-evaluator:latest',
        'InstanceType': 'ml.c4.xlarge',
        'VolumeSizeInGB': 400,
        'RuleParameters': {
           'source_s3_uri': 's3://bucket/custom_rules.py',
           'rule_to_invoke': 'ImproperActivation',
           'collection_names': 'relu_activations'
        }
    }
]
```

要查找使用 Debugger 规则时可用的 Docker 映像的完整列表，请参阅[用于 Debugger 规则的 Docker 映像](debugger-reference.md#debugger-docker-images-rules)。要查找 `RuleParameters` 的键值对，请参阅 [Debugger 内置规则列表](debugger-built-in-rules.md)。

# Amazon SageMaker 调试器参考资料
<a name="debugger-reference"></a>

在以下主题中查找有关使用 Amazon SageMaker Debugger 的更多信息和参考资料。

**Topics**
+ [Amazon SageMaker 调试器 APIs](#debugger-apis)
+ [用于 Debugger 规则的 Docker 映像](#debugger-docker-images-rules)
+ [Amazon SageMaker 调试器异常](#debugger-exceptions)
+ [由 Amazon SageMaker 调试器支持的分布式训练](#debugger-considerations)

## Amazon SageMaker 调试器 APIs
<a name="debugger-apis"></a>

Amazon SageMaker Debugger 在多个位置都有用于监控和分析模型训练的 API 操作。

Amazon D SageMaker ebugger 还提供了开源 [`sagemaker-debugger`Python SDK](https://github.com/awslabs/sagemaker-debugger/tree/master/smdebug)，用于配置内置规则、定义自定义规则和注册挂钩以收集训练作业的输出张量数据。

[Amazon SageMaker AI Python S](https://sagemaker.readthedocs.io/en/stable/) DK 是一款专注于机器学习实验的高级软件开发工具包。SDK 可用于部署由 `SMDebug` Python 库定义的内置规则或自定义规则，以便使用 SageMaker AI 估计器监控和分析这些张量。

调试器已向 Amazon SageMaker API 添加了操作和类型，使平台能够在训练模型时使用调试器并管理输入和输出的配置。
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)并[https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateTrainingJob.html)使用以下 Debugger APIs 来配置张量集合、规则、规则图像和分析选项：
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CollectionConfiguration.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CollectionConfiguration.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_TensorBoardOutputConfig.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_TensorBoardOutputConfig.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerConfig.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerConfig.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleConfiguration.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleConfiguration.html)
+ [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html) 提供了训练作业的完整描述，包括以下 Debugger 配置和规则评估状态：
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleEvaluationStatus.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleEvaluationStatus.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerConfig.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerConfig.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleConfiguration.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleConfiguration.html)
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleEvaluationStatus.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleEvaluationStatus.html)

规则配置 API 操作在分析模型训练时使用 SageMaker 处理功能。有关 SageMaker 处理的更多信息，请参阅[带 SageMaker 处理功能的数据转换工作负载](processing-job.md)。

## 用于 Debugger 规则的 Docker 映像
<a name="debugger-docker-images-rules"></a>

Amazon SageMaker AI 为规则提供了两组 Docker 镜像：一组用于评估 SageMaker AI 提供的规则（内置规则），另一组用于评估 Python 源文件中提供的自定义规则。

如果您使用 [Amaz SageMaker on Python SDK](https://sagemaker.readthedocs.io/en/stable)，则只需将 SageMaker AI 高级调试器 API 操作与 SageMaker AI Estimator API 操作一起使用，而不必手动检索调试器 Docker 镜像和配置 API。`ConfigureTrainingJob`

如果您不使用 SageMaker Python SDK，则必须为调试器规则检索相关的预构建容器基础镜像。Amazon D SageMaker ebugger 为内置规则和自定义规则提供预构建的 Docker 镜像，这些镜像存储在亚马逊弹性容器注册表 (Amazon ECR) Container Registry 中。要从 Amazon ECR 存储库中提取图像（或将图像推送到存储库），请使用 `CreateTrainingJob` API 使用该图像的全名注册表 URL。 SageMaker AI 使用以下 URL 模式作为调试器规则容器镜像注册表地址。

```
<account_id>.dkr.ecr.<Region>.amazonaws.com/<ECR repository name>:<tag>
```

有关每个 AWS 地区的账户 ID、Amazon ECR 存储库名称和标签值，请参阅以下主题。

**Topics**
+ [内置规则评估器的 Amazon SageMaker 调试器图片 URIs](#debuger-built-in-registry-ids)
+ [URIs 适用于自定义规则评估者的 Amazon SageMaker 调试器图片](#debuger-custom-rule-registry-ids)

### 内置规则评估器的 Amazon SageMaker 调试器图片 URIs
<a name="debuger-built-in-registry-ids"></a>

使用以下值作为为 Amazon D SageMaker ebugger 提供内置规则的映像的注册表 URLs 组件。有关帐户 IDs，请参阅下表。

**ECR 存储库名称：** sagemaker-debugger-rules

**标签**：最新 

**完整注册表 URL 示例**：

`904829902805.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-debugger-rules:latest`

按 AWS 区域划分 IDs 的内置规则容器镜像的账户


| Region | account\$1id | 
| --- | --- | 
| af-south-1 |  314341159256  | 
| ap-east-1 |  199566480951  | 
| ap-northeast-1 |  430734990657   | 
| ap-northeast-2 |  578805364391  | 
| ap-south-1 |  904829902805  | 
| ap-southeast-1 |  972752614525  | 
| ap-southeast-2 |  184798709955  | 
| ca-central-1 |  519511493484  | 
| cn-north-1 |  618459771430  | 
| cn-northwest-1 |  658757709296  | 
| eu-central-1 |  482524230118  | 
| eu-north-1 |  314864569078  | 
| eu-south-1 |  563282790590  | 
| eu-west-1 |  929884845733  | 
| eu-west-2 |  250201462417  | 
| eu-west-3 |  447278800020  | 
| me-south-1 |  986000313247  | 
| sa-east-1 |  818342061345  | 
| us-east-1 |  503895931360  | 
| us-east-2 |  915447279597  | 
| us-west-1 |  685455198987  | 
| us-west-2 |  895741380848  | 
| us-gov-west-1 |  515509971035  | 

### URIs 适用于自定义规则评估者的 Amazon SageMaker 调试器图片
<a name="debuger-custom-rule-registry-ids"></a>

使用以下值作为为 Amazon D SageMaker ebugger 提供自定义规则评估器的图像的注册表 URL 的组成部分。有关帐户 IDs，请参阅下表。

**ECR 存储库名称：** sagemaker-debugger-rule-evaluator

**标签**：最新 

**完整注册表 URL 示例**：

`552407032007.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-debugger-rule-evaluator:latest`

按 AWS 区域划分 IDs 的自定义规则容器镜像账户


| Region | account\$1id | 
| --- | --- | 
| af-south-1 |  515950693465  | 
| ap-east-1 |  645844755771  | 
| ap-northeast-1 |  670969264625   | 
| ap-northeast-2 |  326368420253  | 
| ap-south-1 |  552407032007  | 
| ap-southeast-1 |  631532610101  | 
| ap-southeast-2 |  445670767460  | 
| ca-central-1 |  105842248657  | 
| cn-north-1 |  617202126805  | 
| cn-northwest-1 |  658559488188  | 
| eu-central-1 |  691764027602  | 
| eu-north-1 |  091235270104  | 
| eu-south-1 |  335033873580  | 
| eu-west-1 |  606966180310  | 
| eu-west-2 |  074613877050  | 
| eu-west-3 |  224335253976  | 
| me-south-1 |  050406412588  | 
| sa-east-1 |  466516958431  | 
| us-east-1 |  864354269164  | 
| us-east-2 |  840043622174  | 
| us-west-1 |  952348334681  | 
| us-west-2 |  759209512951  | 
| us-gov-west-1 |  515361955729  | 

## Amazon SageMaker 调试器异常
<a name="debugger-exceptions"></a>

Amazon SageMaker Debugger 旨在意识到执行规则所需的张量可能并非在每个步骤都可用。因此，它会引发几个异常，以使您能够控制张量缺失时发生的情况。在 [smdebug.exceptions 模块](https://github.com/awslabs/sagemaker-debugger/blob/master/smdebug/exceptions.py)中提供了这些异常。可按如下方式导入它们：

```
from smdebug.exceptions import *
```

提供了以下异常：
+ `TensorUnavailableForStep` – 请求的张量对步骤不可用。这可能意味着此步骤可能不会由挂钩保存，或者此步骤可能已保存一些张量，但请求的张量不在其中。请注意，当您看到该异常时，这意味着此张量将来绝不可用于此步骤。如果张量已为此步骤保存减少量，则它会告知您可以查询这些减少量。
+ `TensorUnavailable` – `smdebug` API 未保存或尚未保存此张量。这意味着，该张量永远对 `smdebug` 中的任何步骤不可见。
+ `StepUnavailable` – 步骤未保存，并且 Debugger 没有获取来自步骤的数据。
+ `StepNotYetAvailable` – 步骤对 `smdebug` 尚不可见。如果训练还在进行中，数据可以在以后可用。Debugger 会在新数据可用时自动加载新数据。
+ `NoMoreData` – 在训练结束时引发。一旦您看到此项，便知道没有其他需要保存的步骤和张量。
+ `IndexReaderException` – 索引读取器无效。
+ `InvalidWorker` – 调用了无效的工作线程。
+ `RuleEvaluationConditionMet` – 在步骤中对规则的评估结果是满足条件。
+ `InsufficientInformationForRuleInvocation` – 提供的信息不足，无法调用规则。

## 由 Amazon SageMaker 调试器支持的分布式训练
<a name="debugger-considerations"></a>

以下列表针对使用深度学习框架和各种分布式训练选项的训练作业，显示了 Debugger 的适用范围和注意事项。
+ **Horovod**

  对采用 Horovod 的训练作业的 Debugger 适用范围    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/debugger-reference.html)
+ **SageMaker AI 分布式数据 parallel**

  使用 Debugger 训练具有 SageMaker AI 分布式数据 parallel 的作业的有效范围    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/debugger-reference.html)

  \$1 调试器不支持 TensorFlow 2.x 的框架分析。

  \$1\$1 SageMaker 人工智能分布式数据 parallel 不支持采用 Keras 实现的 TensorFlow 2.x。
+ **SageMaker AI 分布式模型 paral** lel — Debugger 不支持 SageMaker AI 分布式模型并行训练。
+ **带有 SageMaker AI 检查点的分布式训**练 — 当同时启用分布式训练选项和 SageMaker AI 检查点时，调试器不可用于训练作业。您可能会看到如下所示的错误：

  ```
  SMDebug Does Not Currently Support Distributed Training Jobs With Checkpointing Enabled
  ```

  要使用 Debugger 进行具有分布式训练选项的训练作业，您需要禁用 SageMaker AI 检查点功能，并在训练脚本中添加手动检查点功能。有关在带有检查点的分布式训练选项中使用 Debugger 的详细信息，请参阅[与 Amazon SageMaker 调试器和检查点并行使用 SageMaker 人工智能分布式数据](distributed-troubleshooting-data-parallel.md#distributed-ts-data-parallel-debugger)和[保存检查点](distributed-troubleshooting-model-parallel.md#distributed-ts-model-parallel-checkpoints)。
+ **参数服务器** – Debugger 不支持基于参数服务器的分布式训练。
+ 无法分析分布式训练框架的`AllReduced`操作，例如 SageMaker AI 分布式数据并行操作和 [Horovod 操作](https://horovod.readthedocs.io/en/stable/timeline_include.html)。