

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

# 使用 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)