

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

# Amazon SageMaker Debugger
<a name="train-debugger"></a>

即時偵錯機器學習訓練任務的模型輸出張量，並使用 Amazon SageMaker Debugger 偵測非收斂問題。

## Amazon SageMaker Debugger 功能
<a name="debugger-features"></a>

機器學習 (ML) 訓練任務可能會遇到諸如過度擬合、飽和啟動函式和梯度消失等問題，這可能會洩露模型效能。

SageMaker Debugger 提供可偵錯訓練任務並解決此類問題的工具，改善模型的效能。發現訓練異常狀況時，Debugger 也提供傳送提醒的工具，針對問題採取行動，並透過視覺化收集的指標和張量來識別其根本原因。

SageMaker Debugger 支援 Apache MXNet、PyTorch、TensorFlow 和 XGBoost 架構。如需 SageMaker Debugger 所支援之可用架構和版本的詳細資訊，請參閱[支援的架構和演算法](debugger-supported-frameworks.md)。

![\[Amazon SageMaker Debugger 的運作方式概觀。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-main.png)


高階 Debugger 工作流程如下所示：

1. 如有需要，請使用 `sagemaker-debugger` Python SDK 修改您的訓練指令碼。

1. 使用 SageMaker Debugger 設定 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 設定[自訂訓練容器](debugger-bring-your-own-container.md)。

1. 開啟訓練任務並即時監控訓練問題。
   + [偵錯工具內建規則清單](debugger-built-in-rules.md).

1. 收到提醒並針對訓練問題立即採取行動。
   + 使用 [使用偵錯工具內建動作來執行規則](debugger-built-in-actions.md) 發現訓練問題時，收到文字和電子郵件，並停止訓練任務。
   + 使用 [Amazon CloudWatch Events 和 AWS Lambda](debugger-cloudwatch-lambda.md) 設定設定自己的動作。

1. 探索訓練問題的深度分析。
   + 如需偵錯模型輸出張量，請參閱[在 TensorBoard 中視覺化偵錯工具輸出張量](debugger-enable-tensorboard-summaries.md)。

1. 修正問題、考慮 Debugger 所提供的建議，然後重複步驟 1-5，直到您最佳化模型並達到目標準確度為止。

SageMaker Debugger 開發人員指南會逐步引導您完成下列主題。

**Topics**
+ [Amazon SageMaker Debugger 功能](#debugger-features)
+ [支援的架構和演算法](debugger-supported-frameworks.md)
+ [Amazon SageMaker Debugger 架構](debugger-how-it-works.md)
+ [Debugger 教學課程](debugger-tutorial.md)
+ [使用 Amazon SageMaker Debugger 為訓練任務除錯](debugger-debug-training-jobs.md)
+ [偵錯工具內建規則清單](debugger-built-in-rules.md)
+ [使用偵錯工具用戶端程式庫建立自訂規則](debugger-custom-rules.md)
+ [Debugger 和自訂訓練容器搭配使用](debugger-bring-your-own-container.md)
+ [使用 SageMaker API 設定 Debugger](debugger-createtrainingjob-api.md)
+ [Amazon SageMaker Debugger 參考](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 棄用使用 TensorFlow 2.6 及更新版本 `tf.keras` 模組所建立之偵錯模型的零程式碼變更支援。這是因為 [TensorFlow 2.6.0 版本註釋](https://github.com/tensorflow/tensorflow/releases/tag/v2.6.0)中公告有突破性變更。如需如何更新訓練指令碼的指示，請參閱[調整您的 TensorFlow 訓練指令碼](debugger-modify-script-tensorflow.md)。
**重要**  
從 PyTorch 1.12.0 版及更新版本開始，SageMaker Debugger 棄用偵錯模型的零程式碼變更支援。  
這是因為突破性變更導致 SageMaker Debugger 干擾 `torch.jit` 功能。如需如何更新訓練指令碼的指示，請參閱[調整 PyTorch 訓練指令碼](debugger-modify-script-pytorch.md)。

如果表中未列出您要訓練和偵錯的架構或演算法，請前往[AWS 討論論壇](https://forums.aws.amazon.com/)，並在 SageMaker Debugger 上留下意見回饋。

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

Amazon SageMaker Debugger 適用於服務中 Amazon SageMaker AI 所在的所有地區，但下列區域除外。
+ 亞太區域 (雅加達)：`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 使用您的訓練容器，並使用 Debugger 取得訓練任務的深入分析。使用監控和偵錯功能，在 Amazon EC2 執行個體上最佳化模型，將您的工作效率最大化。

有關如何使用 `sagemaker-debugger` 用戶端程式庫，將其推送到 Amazon Elastic Container Registry (Amazon ECR)，並監視和偵錯，請參閱[Debugger 和自訂訓練容器搭配使用](debugger-bring-your-own-container.md)。

## Debugger 開放原始碼 GitHub 儲存庫
<a name="debugger-opensource"></a>

透過 SageMaker Python SDK 提供 Debugger API，而且該 API 專門設計用來建構 SageMaker AI [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) 和[ DescribeTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html) API 作業的 Debugger 勾點和規則組態。`sagemaker-debugger` 用戶端程式庫提供工具來註冊*勾點*，並透過其*試用*功能存取訓練資料，全部都透過具有彈性且功能強大的 API 作業進行。在 Python 3.6 及更新版本中，此功能支援機器學習架構 TensorFlow、PyTorch、MXNet 和 XGBoost。

有關 Debugger 和`sagemaker-debugger`API 作業，請參閱以下連結：
+ [Amazon SageMaker Python SDK 文件](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_debugger.html)
+ [Amazon SageMaker Python SDK - Debugger API](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html)
+ [Amazon SageMaker Debugger 開放原始碼用戶端程式庫](https://github.com/awslabs/sagemaker-debugger#amazon-sagemaker-debugger)的 [`sagemaker-debugger` Python SDK 文件](https://sagemaker-debugger.readthedocs.io/en/website/index.html)
+ [`sagemaker-debugger` PyPI](https://pypi.org/project/smdebug/)

如果您使用適用 SDK for Java 的軟體開發工具包執行 SageMaker 訓練作業並且想要配置 Debugger API，請參閱以下參考文獻：
+ [Amazon SageMaker Debugger API](debugger-reference.md#debugger-apis)
+ [使用 SageMaker API 設定 Debugger](debugger-createtrainingjob-api.md)

# Amazon SageMaker Debugger 架構
<a name="debugger-how-it-works"></a>

這個主題會逐步引導您了解 Amazon SageMaker Debugger 工作流程的高階概觀。

Debugger 支援*效能最佳化*的分析功能，識別諸如系統瓶頸和使用量過低等運算問題，並協助大規模最佳化硬體資源使用率。

Debugger *模型最佳化*的偵錯功能涉及分析可能出現的非收斂訓練問題，同時使用諸如梯度下降及其變化等最佳化演算法，以最小化損耗函式。

下圖顯示 SageMaker Debugger 的架構。具有粗邊界的區塊即為 Debugger 管理來分析訓練任務的區塊。

![\[Amazon SageMaker Debugger 的運作方式概觀。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger_new_diagram.png)


Debugger 會將訓練任務的下列資料存放在安全的 Amazon S3 儲存貯體中：
+ **輸出張量** — 訓練機器學習 (ML) 模型時，在向前和向後傳遞期間持續更新純量和模型參數的集合。輸出張量包含純量值 (準確度和損失) 和矩陣 (權重、梯度、輸入層和輸出層)。
**注意**  
根據預設，Debugger 監控並偵錯 SageMaker 訓練任務，不會使用 SageMaker AI 估算器中所設定的任何 Debugger 特定參數。Debugger 每 500 毫秒收集一次系統指標，並且每 500 個步驟收集一次基本輸出張量 (諸如損失和準確度等純量輸出)。它也執行 `ProfilerReport` 規則來分析系統指標，並彙總 Studio Debugger 深入分析儀表板和分析報告。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-notebooks.md)
+ [偵錯工具進階示範和視覺化](debugger-visualization.md)

# Debugger 教學課程影片
<a name="debugger-videos"></a>

下列影片提供使用 SageMaker Studio 和 SageMaker AI 筆記本執行個體的 Amazon SageMaker Debugger 功能之導覽。

**Topics**
+ [在 Studio Classic 使用 Amazon SageMaker Debugger 為模型除錯](#debugger-video-get-started)
+ [深入探索 Amazon SageMaker Debugger 和 SageMaker AI Model Monitor](#debugger-video-dive-deep)

## 在 Studio Classic 使用 Amazon SageMaker Debugger 為模型除錯
<a name="debugger-video-get-started"></a>

*Julien Simon， AWS 技術發展者 \$1 長度：14 分鐘 17 秒*

本教學影片示範如何使用 Amazon SageMaker Debugger，從訓練模型中擷取和檢查偵錯資訊。此影片中使用的訓練模型範例，是以 Keras 為基礎，搭配 TensorFlow 後端的簡單卷積神經網路 (CNN)。Tensorflow 架構和 Debugger 中的 SageMaker 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 Model Monitor
<a name="debugger-video-dive-deep"></a>

*Julien Simon， AWS 技術發展者 \$1 長度：44 分鐘 34 秒*

這一集影片探討 Debugger 和 SageMaker Model Monitor 的進階功能，有助於提升模型的生產力和品質。首先，此影片示範如何偵測和修正訓練問題、視覺化張量，以及使用偵錯工具來改善模型。接下來，在 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)提供的影片中，找到此範例筆記本。

# 偵錯工具範例筆記本
<a name="debugger-notebooks"></a>

[aws/amazon-sagemaker-examples](https://github.com/aws/amazon-sagemaker-examples) 儲存庫提供 [SageMaker Debugger 範例筆記本](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/)。偵錯工具範例筆記本將逐步引導您完成偵錯和分析訓練任務的基礎到進階使用案例。

我們建議您在 SageMaker Studio 或 SageMaker 筆記本執行個體中執行範例筆記本，因為大多數範例都是專門設計用於 SageMaker AI 生態系統中的訓練任務，包括 Amazon EC2、Amazon S3 和 Amazon SageMaker Python SDK。

若要將範例儲存庫複製到 SageMaker Studio，請遵循 [Amazon SageMaker Studio 導覽](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-studio-end-to-end.html)中的指示進行操作。

**重要**  
若要使用新的偵錯工具功能，您需要升級 SageMaker SDK 和 `SMDebug` 用戶端程式庫。在您的 iPython 核心、Jupyter 筆記本或 JupyterLab 環境中，執行以下程式碼以安裝最新版本的程式庫，並重新啟動核心。  

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

## 分析訓練任務的偵錯工具範例筆記本
<a name="debugger-notebooks-profiling"></a>

下列清單列出偵錯工具範例筆記本，說明偵錯工具針對不同機器學習模型、資料集和架構監控及分析訓練任務的適應性。


| 筆記本標題 | 架構 | 模型 | 資料集 | Description | 
| --- | --- | --- | --- | --- | 
|  [Amazon SageMaker Debugger 分析資料分析](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/debugger_interactive_analysis_profiling/interactive_analysis_profiling_data.html)  |  TensorFlow  |  Keras ResNet50  | Cifar-10 |  本筆記本提供 SageMaker Debugger 擷取的分析資料之互動式分析的簡介。探索 `SMDebug` 互動式分析工具的完整功能。  | 
|  [使用 Amazon SageMaker Debugger 對機器學習訓練進行分析](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_nlp_sentiment_analysis/sentiment-analysis-tf-distributed-training-bringyourownscript.html)  |  TensorFlow  |  一維卷積神經網路  |  IMDB 資料集  |  分析 TensorFlow 1-D CNN，以便對 IMDB 資料進行情緒分析，其中包含標籤為具備正面或負面情緒的電影評論。瀏覽 Studio 偵錯工具深入分析和偵錯工具分析報告。  | 
|  [使用各種分散式訓練設定對 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 訓練任務、監控系統資源使用率，並使用偵錯工具分析模型效能。  | 

## 分析模型參數的偵錯工具範例筆記本
<a name="debugger-notebooks-debugging"></a>

下列清單列出偵錯工具範例筆記本，說明偵錯工具針對不同機器學習模型、資料集和架構對訓練任務進行偵錯的適應性。


| 筆記本標題 | 架構 | 模型 | 資料集 | Description | 
| --- | --- | --- | --- | --- | 
|  [Amazon SageMaker Debugger - 使用內建規則](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/tensorflow_builtin_rule)  |  TensorFlow  |  卷積神經網路  | MNIST |  使用 Amazon SageMaker Debugger 內建規則進行 TensorFlow 模型偵錯。  | 
|  [Amazon SageMaker Debugger - 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 Debugger 啟用 Spot 訓練](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mxnet_spot_training)   | MXNet |  Gluon 卷積神經網路  | Fashion MNIST |  了解偵錯工具如何從 Spot 執行個體上的訓練任務收集張量資料，以及如何搭配受管 Spot 訓練使用偵錯工具內建規則。  | 
| [解釋使用 Amazon SageMaker Debugger 預測個人收入的 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-visualization.md)。

# 偵錯工具進階示範和視覺化
<a name="debugger-visualization"></a>

下列示範將逐步引導您使用偵錯工具完成進階使用案例和視覺化指令碼。

**Topics**
+ [使用 Amazon SageMaker Experiments 和 Debugger 訓練和刪減模型](#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 Debugger 監控 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 Debugger 在卷積神經網路 (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 Experiments 和 Debugger 訓練和刪減模型
<a name="debugger-visualization-video-model-pruning"></a>

*Nathalie Rauschmayr 醫生， AWS 應用科學家 \$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 Experiments 和偵錯工具如何簡化訓練任務的管理。Amazon SageMaker Debugger 提供有關訓練任務的透明可見度，並將訓練指標儲存到 Amazon S3 儲存貯體中。SageMaker 實驗可讓您透過 SageMaker Studio 呼叫訓練資訊做為*試驗*，並支援訓練任務視覺化。這可協助您維持模型的高品質，同時根據重要性排名減少較不重要的參數。

這部影片示範了*模型刪減*技術，讓預先訓練的 ResNet50 和 AlexNet 模型更輕量化且經濟實惠，同時保留模型準確度的高標準。

SageMaker AI 估算器會在具有 PyTorch 架構的 AWS 深度學習容器中訓練 PyTorch 模型庫所提供的演算法，而偵錯工具會從訓練程序中擷取訓練指標。

影片也會示範如何設定偵錯工具自訂規則來監看已剔除模型的準確度、在準確度達到閾值時觸發 Amazon CloudWatch 事件和 AWS Lambda 函數，以及自動停止剔除程序以避免備援反覆運算。

學習目標如下：
+  了解如何使用 SageMaker AI 加速 ML 模型訓練並改善模型品質。
+  了解如何自動擷取輸入參數、組態和結果，以使用 SageMaker Experiments 管理訓練反覆運算。
+  探索偵錯工具如何從加權、批度和卷積神經網路的啟用輸出等指標自動擷取即時張量資料，以讓訓練程序透明化。
+ 當 Debugger 擷取問題時，使用 CloudWatch 觸發 Lambda。
+  使用 SageMaker Experiments 和偵錯工具精通 SageMaker 訓練程序。

若要尋找這部影片所使用的筆記本和訓練指令碼，請參閱 [SageMaker Debugger PyTorch 反覆運算模型刪減](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/pytorch_iterative_model_pruning)。

下列影像顯示反覆運算模型刪減程序如何根據啟用輸出和坡度所評估的重要性排名，刪去 100 個最不重要的篩選條件，以縮減 AlexNet 的大小。

刪減程序已將最初的 5000 萬個參數縮減為 1800 萬個參數。它也已將預估模型大小從 201 MB 縮減為 73 MB。

![\[包含模型刪減結果輸出視覺效果的影像\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-model-pruning-results-alexnet.gif)


您也需要追蹤模型準確度，而下列影像顯示您可如何繪製模型刪減程序，以根據 SageMaker Studio 中的參數數量視覺化模型準確度的變更。

![\[在 SageMaker Studio 中使用偵錯工具的張量視覺效果影像\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-model-pruning-studio.png)


在 SageMaker Studio 中，選擇**實驗**索引標籤，從刪減程序中選取由偵錯程式儲存的張量清單，然後構成**試驗元件清單**面板。將十個反覆運算全選，然後選擇**新增圖表**，以建立**試驗元件圖表**。決定要部署的模型之後，請選擇試驗元件和要執行動作的功能表，或選擇**部署模型**。

**注意**  
若要使用下列筆記本範例透過 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 平均數、k-NN 和 t-Distributed Stochastic Neighbor Embedding (t-SNE) 等叢集演算法的效能。

此筆記本範例示範如何使用偵錯工具視覺化隱含變數，如下列動畫所示。它也示範 t-SNE 演算法如何將隱含變數分類為十個叢集，並將它們投影到 2D 空間中。影像右側的散佈圖色彩結構呈現真正的值，說明 BERT 模型和 t-SNE 演算法將隱含變數整理為叢集的情況是否良好。

![\[卷積自動編碼器的概念圖\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-cnn-autoencoder-plot.gif)


## [使用 SageMaker Debugger 監控 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 億個英文文字的單字 (權杖)，來源為 Wikipedia 和電子書等。若為簡單範例，BERT 模型可將高*注意力*提供給來自主詞權杖的適當動詞權杖或代名詞權杖。

預先訓練的 BERT 模型可使用額外的輸出層進行微調，在問題回應自動化、文字分類等 NLP 任務中達到最先進的模型訓練成果。

偵錯工具從微調程序收集張量。在 NLP 的內容中，神經元的權重稱為*注意力*。

此筆記本示範如何在 Stanford 問題和回答資料集上使用[來自 GluonNLP 模型庫的預先訓練 BERT 模型](https://gluon-nlp.mxnet.io/model_zoo/bert/index.html)，以及如何設定 SageMaker Debugger 來監控訓練任務。

在查詢和關鍵向量中繪製*注意力分數* 和個別神經元，可協助您識別不正確模型預測的原因。透過 SageMaker AI Debugger，您可以在訓練進行並了解模型學習內容的同時，擷取張量並即時繪製*注意力頭檢視畫面*。

下列動畫顯示筆記本範例提供的訓練任務中，十個反覆運算的前 20 個輸入權杖的注意力分數。

![\[注意力分數的動畫\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-attention_scores.gif)


## [使用 SageMaker Debugger 在卷積神經網路 (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 來繪製類別啟用地圖，以供卷積神經網路 (CNN) 內的影像偵測和分類使用。在深度學習中，*卷積神經網路 (CNN 或 ConVNet)* 屬於深度神經網路類別，最常用於分析視覺影像。自動駕駛車輛是採用分類啟用地圖的其中一個應用程式，這需要影像的立即偵測和分類，例如交通號誌、道路和障礙物。

在此筆記本中，PyTorch ResNet 模型是在[德國交通號誌資料集](http://benchmark.ini.rub.de/)上進行訓練，該資料集包含超過 40 種類別的交通相關物件，以及總共超過 50,000 個影像。

![\[CNN 類別啟用地圖的動畫\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-cnn-class-activation-maps.gif)


在訓練程序期間，SageMaker Debugger 會收集張量，以即時繪製類別啟用地圖。如此動畫影像所示，類別啟用地圖 (也稱為*顯著性地圖*) 會以紅色突顯高度啟用的區域。

您可以使用偵錯工具擷取的張量，視覺化啟用地圖如何在模型訓練期間進化。首先，模型會在訓練任務開始時偵測左下角的邊緣。在訓練繼續進行的同時，焦點會移動到中央並偵測速度限制號誌，而模型成功地將輸入影像預測為類別 3，這是速度限制 60km/h 號誌的類別，具有 97% 的信賴度。

# 使用 Amazon SageMaker Debugger 為訓練任務除錯
<a name="debugger-debug-training-jobs"></a>

若要使用 SageMaker Debugger 準備訓練指令碼並執行訓練工作，為模型訓練流程除錯，請遵循典型的兩步驟程序：使用 `sagemaker-debugger` Python SDK 修改訓練指令碼，並使用 SageMaker Python SDK 建構 SageMaker AI 估算器。請瀏覽下列主題，以瞭解如何使用 SageMaker Debugger 的除錯功能。

**Topics**
+ [調整您的訓練指令碼以註冊勾點](debugger-modify-script.md)
+ [使用 SageMaker Python SDK 搭配 Debugger 啟動訓練任務](debugger-configuration-for-debugging.md)
+ [SageMaker Debugger 針對 XGBoost 的互動式報告](debugger-report-xgboost.md)
+ [Amazon SageMaker Debugger 規則的動作](debugger-action-on-rules.md)
+ [在 TensorBoard 中視覺化 Amazon SageMaker Debugger 輸出張量](debugger-enable-tensorboard-summaries.md)

# 調整您的訓練指令碼以註冊勾點
<a name="debugger-modify-script"></a>

Amazon SageMaker Debugger 隨附一個名為 [`sagemaker-debugger`Python SDK ](https://sagemaker-debugger.readthedocs.io/en/website)的用戶端程式庫。`sagemaker-debugger` Python SDK 提供工具，可在訓練前調整您的訓練指令碼，並在訓練後調整分析工具。在此頁面中，您將了解如何使用用戶端程式庫調整訓練指令碼。

`sagemaker-debugger` Python SDK 提供包裝函式，可協助註冊勾點以擷取模型張量，而不必變更訓練指令碼。若要開始收集模型輸出張量並對其進行偵錯以尋找訓練問題，請在訓練指令碼中進行下列修改。

**提示**  
依照此頁面操作時，請使用 [`sagemaker-debugger` 開放原始碼軟體開發套件文件](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 Debugger 無法從 [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` 用戶端程式庫中的[勾點 API](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 啟動訓練任務](debugger-configuration-for-debugging.md) 中啟動訓練任務時，在估算器中使用任何 DebuggerHookConfig、TensorBoardConfig 或 Rules，SageMaker AI 會將 JSON 組態檔案新增至您的訓練執行個體，並由 `get_hook` 函式選取。請注意，如果您沒有在估算器中包含任何組態 API，就不會有要尋找勾點的組態檔案，且函式會傳回 `None`。

   **(選用) 適用於 SageMaker AI 以外的訓練工作**

   如果您以本機模式執行訓練任務，請直接在 SageMaker 筆記本執行個體、Amazon EC2 執行個體或您自己的本機裝置上執行訓練任務，並使用 `smd.Hook` 類別建立勾點。不過，這種方法只能儲存張量集合，且僅可用於 TensorBoard 視覺化。SageMaker Debugger 的內建規則不適用於本機模式，因為規則會要求 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 啟動訓練任務](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 啟動訓練任務](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 啟動訓練任務](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 啟動訓練任務](debugger-configuration-for-debugging.md) 於您的估算器中使用任何一個 `DebuggerHookConfig`、`TensorBoardConfig` 或 `Rules` 啟動訓練任務時，SageMaker AI 會將 JSON 組態檔案新增至您的訓練執行個體，該檔案將由 `smd.get_hook` 方法選取。請注意，如果您沒有在估算器中包含任何組態 API，就不會有要尋找勾點的組態檔案，且函式會傳回 `None`。

**(選用) 為 SageMaker AI 以外的訓練工作建立勾點**

如果您以本機模式執行訓練任務，請直接在 SageMaker 筆記本執行個體、Amazon EC2 執行個體或您自己的本機裝置上執行訓練任務，並使用 `smd.Hook` 類別建立勾點。不過，這種方法只能儲存張量集合，且僅可用於 TensorBoard 視覺化。SageMaker Debugger 的內建規則不適用於本機模式。在這種情況下，`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 Debugger 目前僅支援 TensorFlow Keras。

## 在您的 TensorFlow Keras 訓練指令碼中註冊勾點
<a name="debugger-modify-script-tensorflow-keras"></a>

以下程序將逐步引導您使用勾點及其方法，從模型和最佳化工具收集輸出純量與張量。

1. 利用勾點的類別方法包裝您的 Keras 模型和最佳化工具。

   `hook.register_model()` 方法採用您的模型並逐一查看每一層，尋找與您透過 [使用 SageMaker Python SDK 搭配 Debugger 啟動訓練任務](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 Debugger 將無法收集張量。不過，系統可以收集其他張量，例如模型加權、誤差和損失，而無須在嚴格模式中明確執行。

   ```
   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()` 方法 (例如 `push_tape()`、`pop_tape()`、`gradient()`) 將設定 SageMaker Debugger 的寫入器，並儲存提供做為輸入 `gradient()` (可訓練的變數及損失) 和 `gradient()` (漸層) 輸出的張量。
**注意**  
如要透過自訂訓練循環進行收集，請務必使用嚴格模式。否則，SageMaker Debugger 無法收集任何張量。

如需 `sagemaker-debugger` 勾點 API 提供用來建構勾點和儲存張量的完整動作清單，請參閱 *`sagemaker-debugger`Python SDK 文件*中的[勾點方法](https://sagemaker-debugger.readthedocs.io/en/website/hook-methods.html)。

完成訓練指令碼的調整後，請繼續前往[使用 SageMaker Python SDK 搭配 Debugger 啟動訓練任務](debugger-configuration-for-debugging.md)。

# 使用 SageMaker Python SDK 搭配 Debugger 啟動訓練任務
<a name="debugger-configuration-for-debugging"></a>

若要使用 SageMaker Debugger 設定 SageMaker AI 估算器，請使用 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 並指定特定 Debugger 的參數。若要充分利用除錯功能，您需要設定三個參數：`debugger_hook_config`、`tensorboard_output_config` 和 `rules`。

**重要**  
建構並執行估計器擬合方法以啟動訓練任務之前，請確定您已依照[調整您的訓練指令碼以註冊勾點](debugger-modify-script.md)中的指示調整訓練指令碼。

## 使用特定 Debugger 參數建構 SageMaker AI 估算器
<a name="debugger-configuration-structure"></a>

本節中的程式碼範例說明如何使用特定 Debugger 參數建構 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：
+ `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 以儲存張量](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`，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。若要尋找偵錯輸出張量之內建規則的完整清單，請參閱[偵錯工具規則](debugger-built-in-rules.md#debugger-built-in-rules-Rule)。如果您想要建立自己的邏輯偵測任何訓練問題，請參閱[使用偵錯工具用戶端程式庫建立自訂規則](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 相容格式收集輸出張量，並儲存至 `TensorBoardOutputConfig` 物件中指定的 S3 輸出路徑。如需詳細資訊，請參閱 [在 TensorBoard 中視覺化 Amazon SageMaker Debugger 輸出張量](debugger-enable-tensorboard-summaries.md)。
**注意**  
`tensorboard_output_config` 必須使用 `debugger_hook_config` 參數進行設定，過程中您必須新增 `sagemaker-debugger` 勾點，調整訓練指令碼。

**注意**  
SageMaker Debugger 將輸出張量安全儲存於 S3 儲存貯體的子資料夾。例如，帳戶中預設 S3 儲存貯體 URI 的格式為 `s3://amzn-s3-demo-bucket-sagemaker-<region>-<12digit_account_id>/<base-job-name>/<debugger-subfolders>/`。SageMaker Debugger 建立的子資料夾有兩個：`debug-output` 和 `rule-output`。如果新增 `tensorboard_output_config` 參數，您也會找到 `tensorboard-output` 資料夾。

請參閱下列主題，尋找關於如何設定特定 Debugger 參數的更多詳細範例。

**Topics**
+ [使用特定 Debugger 參數建構 SageMaker AI 估算器](#debugger-configuration-structure)
+ [設定 SageMaker Debugger 以儲存張量](debugger-configure-hook.md)
+ [如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)
+ [關閉偵錯工具](debugger-turn-off.md)
+ [Debugger 的實用 SageMaker AI 估算器類別方法](debugger-estimator-classmethods.md)

# 設定 SageMaker Debugger 以儲存張量
<a name="debugger-configure-hook"></a>

*張量*是從每個訓練迭代的向後和向前傳遞更新參數的資料集合。SageMaker Debugger 收集輸出張量，分析訓練任務的狀態。SageMaker Debugger 的 [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 勾點來儲存、存取和視覺化輸出張量的範例。

建構 SageMaker AI 估計器時請指定 `debugger_hook_config` 參數，啟動 SageMaker Debugger。下列主題包含如何使用 `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"
        }
    )
]
```

如需可用參數索引鍵的更多相關資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 中的 [CollectionConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig)。例如，下列程式碼範例會示範如何在不同訓練階段調整 “遺失” 張量集合的儲存間隔：在訓練階段每 100 個步驟儲存一次遺失，並在驗證階段每 10 個步驟儲存一次驗證遺失。

```
from sagemaker.debugger import CollectionConfig

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

**提示**  
此張量集合組態物件可同時用於 [DebuggerHookConfig](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-configure-hook.html#debugger-configure-tensor-hook) 和 [Rule](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
)
```

如需更多資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 中的 [DebuggerHookConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.DebuggerHookConfig)。

# 設定 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 提供訓練深度學習模型的透明檢視。
+ [使用 MXNet 在 SageMaker Studio 筆記本進行互動張量分析](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mnist_tensor_analysis)

  此筆記本範例示範如何使用 Amazon SageMaker Debugger 視覺化已儲存的張量。透過將張量視覺化，訓練深度學習演算法的同時，您可以查看張量值的變化方式。此筆記本包含訓練任務和設定不良的神經網路，並使用 Amazon SageMaker 偵錯器來彙總和分析張量，包括梯度、啟用輸出和權重。例如，下圖顯示了受消失坡度問題影響之卷積圖層的坡度分佈。  
![\[繪製梯度分佈的圖形。\]](http://docs.aws.amazon.com/zh_tw/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 SageMaker Debugger，從 MXNet Gluon 模型訓練任務儲存和視覺化張量。其中說明 Debugger 設為將所有張量儲存到 Amazon S3 儲存貯體，並擷取 ReLu 啟用輸出來進行視覺化。下圖顯示 ReLu 啟用輸出的三維視覺化。色彩方案設為藍色表示接近 0 的值，設為黃色表示接近 1 的值。  
![\[ReLU 啟用輸出的視覺化\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/tensorplot.gif)

  在此筆記本中，從 `tensor_plot.py` 匯入的 `TensorPlot` 類別，旨在繪製以二維影像作為輸入的卷積神經網路 (CNN)。筆記本隨附的 `tensor_plot.py` 指令碼使用 Debugger 擷取張量，並將卷積神經網路視覺化。您可以在 SageMaker Studio 上執行此筆記本，重現張量視覺化，並實作您自己的卷積神經網路模型。
+ [使用 MXNet 在 SageMaker 筆記本中進行即時張量分析](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mxnet_realtime_analysis)

  本範例逐步引導您安裝必要的元件，在 Amazon SageMaker 訓練任務中發出張量，以及在訓練執行期間，使用 Debugger API 作業存取這些張量。gluon CNN 模型在 Fashion MNIST 資料集訓練。任務執行時，您會看到 Debugger 如何從每 100 個批次的第一個卷積層擷取啟用輸出，並將它們視覺化。此外，這將向您顯示如何在任務完成後視覺化權重。

## 使用 Debugger 內建集合儲存張量
<a name="debugger-save-built-in-collections"></a>

使用 `CollectionConfig` API 即可使用內建張量集合，使用 `DebuggerHookConfig` API 即可儲存它們。下列範例示範如何使用 Debugger 勾點組態的預設設定，建構 SageMaker AI 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` 集合，以及如何建構 SageMaker AI 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` 參數完整清單，請參閱 [Debugger 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` 參數的完整清單，請參閱 [ Debugger CollectionConfig](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#configuring-collection-using-sagemaker-python-sdk)。

# 如何設定偵錯工具內建規則
<a name="use-debugger-built-in-rules"></a>

在下列主題中，您將了解如何使用 SageMaker Debugger 內建規則。Amazon SageMaker Debugger 的內建規則會分析在模型訓練期間發出的張量。SageMaker AI Debugger 提供 `Rule` API 作業，可監控訓練任務進度和錯誤，以便成功訓練模型。例如，規則可以偵測漸層是否變得太大或太小、模型是過度擬合還是過度訓練，以及訓練任務是否不會降低損耗功能並改善。要查看可用內建規則的完整清單，請參閱[偵錯工具內建規則清單](debugger-built-in-rules.md)。

**Topics**
+ [搭配預設參數設定使用偵錯工具內建規則](debugger-built-in-rules-configuration.md)
+ [搭配自訂參數值使用偵錯工具內建規則](debugger-built-in-rules-configuration-param-change.md)
+ [範例筆記本和程式碼範例，以設定偵錯工具規則](debugger-built-in-rules-example.md)

# 搭配預設參數設定使用偵錯工具內建規則
<a name="debugger-built-in-rules-configuration"></a>

若要在估算器中指定偵錯工具內建規則，您需要設定清單物件。下列範例程式碼顯示列出偵錯工具內建規則的基本結構。

```
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-built-in-rules.md)。

若要尋找 SageMaker Debugger 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())
]
```

當您開始訓練任務時，偵錯工具會每 500 毫秒收集一次系統資源使用率資料，並依預設每 500 個步驟收集一次遺失和準確度值。偵錯工具會分析資源使用率，來識別您的模型是否有瓶頸問題。`loss_not_decreasing`、`overfit`、`overtraining` 和 `stalled_training_rule` 會監控您的模型是否在沒有這些訓練問題的情況下，最佳化損耗功能。如果規則偵測到訓練有異常狀況，則規則評估狀態會變更為 `IssueFound`。您可以設定自動化動作，例如使用 Amazon CloudWatch Events 和 AWS Lambda來通知訓練問題和停止訓練任務。如需詳細資訊，請參閱[Amazon SageMaker Debugger 規則的動作](debugger-action-on-rules.md)。



# 搭配自訂參數值使用偵錯工具內建規則
<a name="debugger-built-in-rules-configuration-param-change"></a>

如果您想要調整內建規則參數值並自訂張量集合 Regex，請設定 `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-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` 完整清單，請參閱[Debugger 集合組態 API](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#configuring-collection-using-sagemaker-python-sdk)。

有關 Debugger 規則類別、方法和參數的詳細資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 中的 [SageMaker AI Debugger 規則類別](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-built-in-rules.md) 中的每個規則提供參數描述和參數值自訂範例。

# 範例筆記本和程式碼範例，以設定偵錯工具規則
<a name="debugger-built-in-rules-example"></a>

在下列各節中，提供如何使用偵錯工具規則監控 SageMaker 訓練任務的筆記本和程式碼範例。

**Topics**
+ [偵錯工具內建規則範例筆記本](#debugger-built-in-rules-notebook-example)
+ [偵錯工具內建規則範例程式碼](#debugger-deploy-built-in-rules)
+ [使用偵錯工具內建規則與參數修改](#debugger-deploy-modified-built-in-rules)

## 偵錯工具內建規則範例筆記本
<a name="debugger-built-in-rules-notebook-example"></a>

下列範例筆記本示範如何在使用 Amazon SageMaker AI 執行訓練任務時，使用偵錯工具內建規則：
+ [搭配 TensorFlow 使用 SageMaker Debugger 內建規則](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/tensorflow_builtin_rule)
+ [搭配受管 Spot 訓練和 MXNet 使用 SageMaker Debugger 內建規則](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/mxnet_spot_training)
+ [使用具有參數修改功能的 SageMaker Debugger 內建規則，以利用 XGBoost 即時訓練任務分析](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/xgboost_realtime_analysis)

在 SageMaker Studio 中執行範例筆記本時，您可以找到在 **Studio 實驗清單**索引標籤上建立的訓練任務試驗。例如，如下列螢幕擷取畫面所示，您可以尋找並開啟目前訓練任務的**描述試驗元件**視窗。在偵錯工具索引標籤上，您可以檢查偵錯程式規則 (`vanishing_gradient()` 和 `loss_not_decreasing()`) 是否平行監控訓練任務工作階段。有關如何在 Studio 使用者介面中查找訓練工作試用組件的完整說明，請參閱[SageMaker Studio - 查看實驗、試驗和試用組件](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-tasks.html#studio-tasks-experiments)。

![\[使用 SageMaker Studio 中啟動的偵錯工具內建規則來執行訓練任務的映像\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-built-in-rule-studio.png)


在 SageMaker AI 環境中有兩種使用偵錯工具內建規則的方法：在準備時部署內建規則，或根據需要調整其參數。下列主題示範如何搭配範例程式碼使用內建規則。

## 偵錯工具內建規則範例程式碼
<a name="debugger-deploy-built-in-rules"></a>

下列程式碼範例示範如何使用 `Rule.sagemaker` 方法設定偵錯工具內建規則。若要指定要執行的內建規則，請使用 `rules_configs` API 作業呼叫內建規則。要查找 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()
```

**注意**  
偵錯工具內建規則會與您的訓練任務平行執行。訓練任務的內建規則容器數量上限為 20。

有關 Debugger 規則類別、方法和參數的詳細資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 中的 [SageMaker Debugger 規則類別](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html) 

要查找有關如何調整 Debugger 規則參數的範例，請參閱以下 [使用偵錯工具內建規則與參數修改](#debugger-deploy-modified-built-in-rules) 部分。

## 使用偵錯工具內建規則與參數修改
<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](debugger-createtrainingjob-api.md)。

# 關閉偵錯工具
<a name="debugger-turn-off"></a>

如果您想完全關閉 Debugger，請執行下列其中一項操作：
+ 開始訓練任務之前，請執行下列操作：

  若要同時停止監控和效能分析，請將 `disable_profiler` 參數包含在估算器中，並將其設定為 `True`。
**警告**  
如果停用它，您將無法檢視全方位的 Studio Debugger 深入分析儀表板和自動產生的分析報告。

  若要停止偵錯，請將 `debugger_hook_config` 參數設定為 `False`。
**警告**  
如果停用它，就無法收集輸出張量，也無法偵錯模型參數。

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

  有關偵錯工具特定參數的更多相關資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 中的 [SageMaker AI 估算器](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator)。
+ 當訓練工作正在執行時，請執行下列操作：

  若要在訓練工作執行時停用監控和分析，請使用下列估算器分類方法：

  ```
  estimator.disable_profiling()
  ```

  只禁用架構分析並保持系統監控，請使用 `update_profiler` 方法：

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

  有關估算器擴展方法的更多相關資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 文件內的 [estimator.disable\$1profiling](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator.disable_profiling) 和 [estimator.update\$1profiler](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator.update_profiler) 類別方法。

# Debugger 的實用 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 訓練任務執行時檢查 Debugger 規則的完整清單：

  ```
  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 訓練任務執行時檢查 Debugger 的偵錯規則清單：

  ```
  estimator.debugger_rules
  ```
+ 若要檢查 Debugger 的監控和分析系統規則組態與架構指標：

  ```
  estimator.profiler_rule_configs
  ```
+ 若要在 SageMaker 訓練任務執行時檢查 Debugger 的監控和分析規則清單：

  ```
  estimator.profiler_rules
  ```

如需 SageMaker AI 估算器類別及其方法的更多相關資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 的 [估算器 API](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator)。

# SageMaker Debugger 針對 XGBoost 的互動式報告
<a name="debugger-report-xgboost"></a>

獲得由 Debugger 自動產生的訓練報告。Debugger 報告可提供訓練任務的深入解析，並提供改善模型效能的建議。對於 SageMaker AI XGBoost 訓練任務，請使用 Debugger [CreateXgboostReport](debugger-built-in-rules.md#create-xgboost-report) 規則來獲得訓練進度和結果的完整訓練報告。依照本指南，指定建構 XGBoost 估算器時的 [CreateXgboostReport](debugger-built-in-rules.md#create-xgboost-report) 規則、使用 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 或 Amazon S3 主控台下載報告，並深入了解訓練結果。

**注意**  
您可以在訓練工作執行時或工作完成時，下載 Debugger 報告。在訓練期間，Debugger 會同時更新報告，反映目前規則的評估狀態。只有在訓練工作完成後，您才能下載完整的 Debugger 報告。

**重要**  
報告中的圖表和建議僅用於提供資訊，並非絕對。由您負責對資訊進行您自己獨立的評估。

**Topics**
+ [使用 Debugger XGBoost 報告規則建構 SageMaker AI XGBoost 估算器](debugger-training-xgboost-report-estimator.md)
+ [下載 Debugger XGBoost 訓練報告](debugger-training-xgboost-report-download.md)
+ [Debugger XGBoost 訓練報告演練](debugger-training-xgboost-report-walkthrough.md)

# 使用 Debugger XGBoost 報告規則建構 SageMaker AI XGBoost 估算器
<a name="debugger-training-xgboost-report-estimator"></a>

[CreateXgboostReport](debugger-built-in-rules.md#create-xgboost-report) 規則會從訓練任務收集下列輸出張量：
+ `hyperparameters` – 在第一個步驟進行儲存。
+ `metrics` – 每 5 個步驟儲存損失和準確性。
+ `feature_importance` – 每 5 個步驟進行儲存。
+ `predictions` – 每 5 個步驟進行儲存。
+ `labels` – 每 5 個步驟進行儲存。

輸出張量會儲存在預設的 S3 儲存貯體。例如 `s3://sagemaker-<region>-<12digit_account_id>/<base-job-name>/debug-output/`。

當您為 XGBoost 訓練任務建構 SageMaker AI 估算器時，請指定如下列範例程式碼所示的規則。

------
#### [ 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)
```

------

# 下載 Debugger XGBoost 訓練報告
<a name="debugger-training-xgboost-report-download"></a>

在訓練任務執行期間或使用 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 和 AWS Command Line Interface (CLI) 完成任務後，下載 Debugger XGBoost 訓練報告。

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

1. 檢查目前任務的預設 S3 輸出基礎 URI。

   ```
   estimator.output_path
   ```

1. 檢查目前的任務名稱。

   ```
   estimator.latest_training_job.job_name
   ```

1. Debugger 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. 如要檢查報告是否已產生，請在使用 `aws s3 ls` 和搭配 `--recursive` 選項在 `rule_output_path` 下遞迴列出目錄和檔案。

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

   這應該會在名為 `CreateXgboostReport` 和 `ProfilerReport-1234567890` 的自動產生之資料夾下傳回完整的檔案清單。XGBoost 訓練報告會儲存在 `CreateXgboostReport` 中，而分析報告則儲存在 `ProfilerReport-1234567890` 資料夾中。要瞭解有關 xGBoost 訓練工作預設產生的性能分析報告的詳細資訊，請參閱[SageMaker Debugger 互動報告](debugger-profiling-report.md)。  
![\[規則輸出的範例。\]](http://docs.aws.amazon.com/zh_tw/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，請選擇**信任 HTML** 以查看自動產生的 Debugger 訓練報告。  
![\[規則輸出的範例。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-xgboost-report-open-trust.png)

1. 開啟 `xgboost_report.ipynb` 檔案以探索產生報告的方式。您可以使用 Jupyter 筆記本檔案來自訂及擴充訓練報告。

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

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)：// 開啟 Amazon S3 主控台。

1. 搜尋基礎 S3 儲存貯體。例如，如果您尚未指定任何基本作業名稱，則基礎 S3 儲存貯體名稱應採用下列格式：`sagemaker-<region>-111122223333`。透過**依名稱尋找儲存貯體**欄位查詢基礎 S3 儲存貯體。  
![\[Amazon S3 主控台中的依名稱尋找儲存貯體欄位。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-report-download-s3console-0.png)

1. 在基礎 S3 儲存貯體中，在**依字首尋找物件**中輸入工作名稱字首，然後選擇訓練工作名稱，以查詢訓練工作名稱。  
![\[Amazon S3 主控台中的依字首尋找物件欄位。\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/sagemaker/latest/dg/images/debugger/debugger-xgboost-report-s3-download.png)

1. 在網頁瀏覽器中開啟下載的 **xbgoost\$1report.html** 檔案。

------

# Debugger XGBoost 訓練報告演練
<a name="debugger-training-xgboost-report-walkthrough"></a>

本節將逐步引導您完成 Debugger XGBoost 訓練報告。報告會根據輸出張量 regex 自動彙總，以識別二進制分類、多類別分類和迴歸中的訓練任務類型。

**重要**  
在報告中，系統會提供資訊圖表和相關建議，其中的內容並非絕對。您有責任對當中的資訊進行自己的獨立評估。

**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_tw/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_tw/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_tw/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_tw/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_tw/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_tw/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 軸為相符率 (TPF)，X 軸為假陽性率 (FPR)。該圖也會顯示曲線下面積 (AUC) 的值。AUC 值越高，您的分類器就越具預測性。您也可以使用 ROC 曲線來了解 TPR 和 FPR 之間的取捨，並識別適合您使用案例的最佳分類閾值。可以調整分類閾值以微調模型的行為，以減少一種或另一種類型的錯誤 (FP/FN)。

![\[接收器操作特性曲線圖表的範例。\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/sagemaker/latest/dg/images/debugger/debugger-training-xgboost-report-walkthrough-val-error-per-label-bin.png)


# Amazon SageMaker Debugger 規則的動作
<a name="debugger-action-on-rules"></a>

基於 Debugger 規則評估狀態，您可以設定自動化動作，例如停止訓練工作及使用 Amazon Simple Notification Service (Amazon SNS) 來傳送通知。您也可以使用 Amazon CloudWatch Events 和 建立自己的動作 AWS Lambda。若要了解如何基於偵錯工具規則評估狀態設定自動化動作，請參閱下列主題。

**Topics**
+ [使用偵錯工具內建動作來執行規則](debugger-built-in-actions.md)
+ [使用 Amazon CloudWatch 和 對規則執行的動作 AWS Lambda](debugger-cloudwatch-lambda.md)

# 使用偵錯工具內建動作來執行規則
<a name="debugger-built-in-actions"></a>

使用偵錯工具內建動作來回應 [偵錯工具規則](debugger-built-in-rules.md#debugger-built-in-rules-Rule) 找到的問題。偵錯工具 `rule_configs` 類別提供設定動作清單的工具，包含在偵錯工具規則發現訓練問題時，自動停止訓練任務及使用 Amazon Simple Notification Service (Amazon SNS) 傳送通知。下列主題會逐步引導您完成這些任務。

**Topics**
+ [設定 Amazon SNS，建立 `SMDebugRules` 主題，並訂閱該主題](#debugger-built-in-actions-sns)
+ [設定 IAM 角色以附加必要政策](#debugger-built-in-actions-iam)
+ [使用內建動作設定偵錯工具規則](#debugger-built-in-actions-on-rule)
+ [使用偵錯工具內建動作的考量事項](#debugger-built-in-actions-considerations)

## 設定 Amazon SNS，建立 `SMDebugRules` 主題，並訂閱該主題
<a name="debugger-built-in-actions-sns"></a>

本節將逐步引導您如何設定 Amazon SNS **SMDebugRules** 主題、訂閱並確認訂閱以獲得來自偵錯工具規則的通知。

**注意**  
關於 Amazon SNS 的計費，如需更多相關資訊，請參閱 [Amazon SNS 定價](https://aws.amazon.com/sns/pricing/)和 [Amazon SNS 常見問答集](https://aws.amazon.com/sns/faqs/)。

**建立一個 SMDebugEvents 主題**

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home)：// 開啟 Amazon SNS 主控台。

1. 在左側導覽窗格中，選擇**主題**。

1. 在**主題**頁面上，選擇**建立主題**。

1. 在**建立主題**頁面上，於**詳細資訊**區段中，執行以下作業：

   1. 在**類型**中，選擇**標準**做為主題類型。

   1. 在**名稱**中，輸入 **SMDebugRules**。

1. 略過所有其他選項設定，然後選擇**建立主題**。如果您想進一步了解可選設定，請參閱[建立一個 Amazon SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)。

**訂閱 SMDebugRules 主題**

1. 在 [https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home) 開啟 Amazon SNS 主控台。

1. 在左導覽窗格中，選擇**訂閱**。

1. 在**訂閱**頁面，選擇**建立訂閱**。

1. 在**建立訂閱**頁面上，於**詳細資訊**區段中，執行以下作業：

   1. 在**主題 ARN**，請選擇 **SMDebugRules** 主題 ARN。ARN 應為 `arn:aws:sns:<region-id>:111122223333:SMDebugRules` 格式。

   1. 針對**通訊協定**，選擇**電子郵件** 或**簡訊**。

   1. 在**端點**中，輸入您要接收通知的端點值，例如電子郵件地址或電話號碼。
**注意**  
請務必輸入正確的電子郵件地址和電話號碼。電話號碼必須包含 `+`、國家/地區代碼和電話號碼，不含特殊字元或空格。例如，電話號碼 \$11 (222) 333-4444 被格式化為 **\$112223334444**。

1. 略過所有其他選項設定，然後選擇**建立訂閱**。如果您想進一步了解可選設定，請參閱[訂閱 Amazon SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-create-subscribe-endpoint-to-topic.html)。

訂閱 **SMDebugRules** 主題後，您會在電子郵件或電話中收到下列確認訊息：

![\[Amazon SNS SMDebugRules 主題的訂閱確認電子郵件訊息。\]](http://docs.aws.amazon.com/zh_tw/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 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在導覽窗格中，選擇**政策**，並選擇**建立政策**。

1. 在**建立政策**頁面上，執行下列動作以建立新的 sns-access 存取政策：

   1. 選擇 **JSON** 標籤。

   1. 將以下程式碼中以粗體格式的 JSON 字串貼入 `"Statement"`，以您的帳戶 ID 取代 12 位數 AWS 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. 查詢您用於 SageMaker AI 模型訓練的 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)。

## 使用內建動作設定偵錯工具規則
<a name="debugger-built-in-actions-on-rule"></a>

在前面的步驟中成功完成必要設定之後，您可以為偵錯規則設定偵錯工具內建動作，如下列範例指令碼所示。您可以選擇建置 `actions` 清單物件時要使用的內建動作。`rule_configs` 是一個輔助模組，提供進階工具來配置偵錯工具的內建規則和動作。偵錯工具可使用下列內建動作：
+ `rule_configs.StopTraining()` — 當偵錯工具規則發現問題時，停止訓練工作。
+ `rule_configs.Email("abc@abc.com")` — 當偵錯工具規則發現問題時，透過電子郵件傳送通知。使用您在設定 SNS 主題訂閱時使用的電子郵件地址。
+ `rule_configs.SMS("+1234567890")` — 當偵錯工具規則發現問題時，透過簡訊傳送通知。使用您在設定 SNS 主題訂閱時使用的電話號碼。
**注意**  
請務必輸入正確的電子郵件地址和電話號碼。電話號碼必須包含 `+`、國家/地區代碼和電話號碼，不含特殊字元或空格。例如，電話號碼 \$11 (222) 333-4444 被格式化為 **\$112223334444**。

您可以總結使用 `rule_configs.ActionList()` 方法以使用所有內建動作或動作子集，該方法會採取內建動作並設定動作清單。

**將三個內建動作全部新增至單一項規則**

如果您想要將三個內建動作全部指派給單一項規則，請在建構估算器時設定偵錯工具內建動作清單。使用下列範本建構估算器，偵錯工具會以您用來監控訓練工作進度的一切規則，停止訓練工作並透過電子郵件和簡訊傳送通知。

```
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)
```

訓練工作正在執行時，當規則發現訓練工作的問題時，偵錯工具內建動作就會隨時傳送通知電子郵件和簡訊。下列螢幕擷取畫面顯示，當訓練工作出現停頓訓練工作問題時，電子郵件通知的範例。

![\[當偵錯工具偵測到 StalledTraining 問題時，傳送的電子郵件通知範例。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-built-in-action-email.png)


下列螢幕擷取畫面顯示當規則發現 StalledTraining 問題時，偵錯工具會傳送的簡訊通知範例。

![\[當偵錯工具偵測到 StalledTraining 問題時，所傳送的簡訊通知範例。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-built-in-action-text.png)


## 使用偵錯工具內建動作的考量事項
<a name="debugger-built-in-actions-considerations"></a>
+ 若要使用偵錯工具內建動作，網際網路連接為必要項目。Amazon SageMaker AI 或 Amazon VPC 提供的網路隔離模式不支援此功能。
+ 內建動作無法用於 [剖析工具規則](debugger-built-in-profiler-rules.md#debugger-built-in-profiler-rules-ProfilerRule)。
+ 內建動作無法用於具有 Spot 訓練中斷的訓練工作。
+ 在電子郵件或簡訊通知中，`None` 會出現在訊息結尾。這沒有任何意義，所以您可以忽略文字 `None`。

# 使用 Amazon CloudWatch 和 對規則執行的動作 AWS Lambda
<a name="debugger-cloudwatch-lambda"></a>

Amazon CloudWatch 收集 Amazon SageMaker AI 模型訓練任務日誌和 Amazon SageMaker Debugger 規則處理任務日誌。使用 Amazon CloudWatch Events 設定偵錯工具 AWS Lambda ，並根據偵錯工具規則評估狀態採取動作。

## 範例筆記本
<a name="debugger-test-stop-training"></a>

您可以執行下列範例筆記本，這些筆記本是為了使用 Amazon CloudWatch 和 AWS Lambda對 Debugger 的內建規則執行動作來停止訓練任務而預備的。
+ [Amazon SageMaker Debugger - 對 CloudWatch 活動做出反應](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_action_on_rule/tf-mnist-stop-training-job.html)

  這個範例筆記本執行的訓練工作有梯度消失的問題。建構 SageMaker AI TensorFlow 估算器時，會使用 Debugger [VanishingGradient](debugger-built-in-rules.md#vanishing-gradient) 內建規則。Debugger 規則偵測到問題時，就會終止訓練工作。
+ [使用 SageMaker Debugger 規則偵測停止的訓練並調用動作](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 記錄內的訓練和 Debugger 規則任務狀態，在發生訓練問題時採取進一步的動作。下列程序說明如何存取相關的 CloudWatch 日誌。對於使用 CloudWatch 監控訓練任務，如需更多相關資訊，請參閱[監控 Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/latest/dg/monitoring-overview.html)。

**若要存取訓練任務日誌和偵錯工具規則任務日誌**

1. 透過 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 開啟 CloudWatch 主控台。

1. 在左側導覽窗格中的**日誌**節點下，選擇**日誌群組**。

1. 在日誌群組清單中，執行下列動作：
   + 在訓練工作日誌選擇 **/aws/sagemaker/TrainingJobs**。
   + 在 Debugger 規則工作日誌選擇 **/aws/sagemaker/ProcessingJobs**。

# 使用 CloudWatch 和 Lambda 設定偵錯工具，讓自動化訓練工作終止
<a name="debugger-stop-training"></a>

偵錯工具規則會監控訓練工作狀態，而 CloudWatch 事件規則會監看偵錯工具規則訓練工作評估狀態。下列各節概述使用 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. 在 https：//[https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) 開啟 AWS Lambda 主控台。

1. 在導覽面板上，選擇**函式**，然後選擇**建立函式**。

1. 在**建立函式**頁面上，選擇**從頭開始撰寫**。

1. 在**基本資訊**區段中，輸入**函式名稱** (例如 **debugger-rule-stop-training-job**)。

1. 針對**執行期**，選擇 **Python 3.7**。

1. 針對**許可**，請展開下拉式清單選項，然後選擇**變更預設執行角色**。

1. 針對**執行角色**，請選擇**使用現有的角色**，然後選擇您在 SageMaker AI 上用於訓練工作的 IAM 角色。
**注意**  
確保您使用的執行角色連接 `AmazonSageMakerFullAccess` 和 `AWSLambdaBasicExecutionRole`。否則，Lambda 函式將無法正確回應訓練工作的 Debugger 規則狀態變更。如果您不確定正在使用哪個執行角色，請在 Jupyter 筆記本儲存格中執行下列程式碼，以擷取執行角色輸出：  

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

1. 請在頁面底部，選擇**建立函式**。

下圖顯示**建立函式**頁面的範例，其輸入欄位和選取已完成。

![\[建立函式頁面。\]](http://docs.aws.amazon.com/zh_tw/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 作業。`client` for 適用於 Python (Boto3) 的 AWS SDK SageMaker 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 程式碼編輯器界面的詳細資訊，請參閱[使用 AWS Lambda 主控台編輯器建立函數](https://docs.aws.amazon.com/lambda/latest/dg/code-editor.html)。

1. 略過所有其他設定，然後選擇組態頁面頂端的**儲存**。

## 步驟 3：建立 CloudWatch 事件規則，並連結至偵錯工具的 Lambda 函式
<a name="debugger-cloudwatch-events"></a>

**建立 CloudWatch 事件規則並連結至偵錯工具的 Lambda 函式**

1. 透過 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 開啟 CloudWatch 主控台。

1. 在左側導覽窗格內的**事件**下，選擇**規則**。

1. 選擇**建立規則**。

1. 在**步驟 1：建立規則**頁面中的**事件來源**區段中，在**服務名稱**選擇 **SageMaker AI**，並在**事件類型**選擇 **SageMaker AI 訓練工作狀態變更**。事件模式預覽看起來應該如下列範例的 JSON 字串所示：

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

1. 在**目標**區段, 選擇**新增目標\$1**，然後選擇您建立的 Lambda 函式 **debugger-rule-stop-training-job**。此步驟會將 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_tw/sagemaker/latest/dg/images/debugger/debugger-lambda-designer.png)

# 停用 CloudWatch 事件規則以停止使用讓自動化訓練任務終止
<a name="debugger-disable-cw"></a>

如果要停用讓自動化訓練工作終止，則需要停用 CloudWatch 事件規則。在 Lambda **設計工具**面板中，選擇連結至 Lambda 函式的 **EventBridge (CloudWatch Events)** 區塊。這會在**設計工具**面板下方顯示 **EventBridge** 面板 (如需範例，請參閱先前的螢幕擷取畫面)。選取 **EventBridge (CloudWatch Events): debugger-cw-event-rule** 旁邊的核取方塊，然後選擇**停用**。如果稍後想使用自動化終止功能，您可以再次啟用 CloudWatch 事件規則。

# 在 TensorBoard 中視覺化 Amazon SageMaker Debugger 輸出張量
<a name="debugger-enable-tensorboard-summaries"></a>

**重要**  
此頁面已棄用，以便使用 Amazon SageMaker AI 和 TensoBoard，其中提供與 SageMaker 訓練和 SageMaker AI 網域的存取控制功能整合的全方位 TensorBoard 體驗。如需詳細資訊，請參閱 [Amazon SageMaker AI 中的 TensorBoard](tensorboard-on-sagemaker.md)。

使用 SageMaker Debugger，建立與 TensorBoard 相容的輸出張量檔案。載入要在 TensorBoard 中視覺化的檔案，並分析您的 SageMaker 訓練任務。偵錯工具會自動產生與 TensorBoard 相容的輸出張量檔案。對於您為儲存輸出張量自訂的任何勾點組態，偵錯工具可以彈性建立純量摘要、分佈和長條圖，供您匯入至 TensorBoard。

![\[偵錯工具輸出張量儲存機制的架構圖。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-tensorboard-concept.png)


您可以透過傳遞 `DebuggerHookConfig` 和 `TensorBoardOutputConfig` 物件給 `estimator` 來啟用。

下列程序說明如何將純量、權重和偏差儲存為可透過 TensorBoard 視覺化的完整張量、長條圖和分佈。Debugger 會將它們儲存到訓練容器的本機路徑 (預設路徑為 `/opt/ml/output/tensors`)，並同步至透過偵錯程式輸出組態物件傳遞的 Amazon S3 位置。

**若要使用偵錯工具儲存 TensorBoard 相容的輸出張量檔案**

1. 使用偵錯工具 `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)
   )
   ```

   有關其他資訊，請參閱 Debugger `[TensorBoardOutputConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.TensorBoardOutputConfig)` API 中的 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable)。

1. 設定偵錯工具勾點，並自訂勾點參數值。例如，下列程式碼會設定偵錯工具勾點，以在訓練階段每 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"
               }
           ),
       ]
   )
   ```

   有關 Debugger 組態 API 的詳細資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 中的 Debugger `[CollectionConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.CollectionConfig)` 和 `[DebuggerHookConfig](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.DebuggerHookConfig)` API。

1. 使用偵錯工具參數傳遞組態物件，以建構 SageMaker AI 估算器。以下範例範本示範如何建立一般 SageMaker AI 估算器。您也可以將 `estimator` 和 `Estimator` 取代為其他 SageMaker AI 架構的估算器父系類別和估算器類別。此功能的可用 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()` 方法會啟動訓練任務，偵錯工具會即時將輸出張量檔案寫入偵錯工具 S3 輸出路徑和 TensorBoard S3 輸出路徑。若要擷取輸出路徑，請使用下列估算方法：
   + 對於偵錯工具 S3 輸出路徑，請使用 `estimator.latest_job_debugger_artifacts_path()`。
   + 對於 TensorBoard S3 輸出路徑，請使用 `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 Jupyter 筆記本伺服器、開啟新筆記本，然後執行 TensorBoard 應用程式。

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

下列動畫螢幕擷取畫面示範步驟 5 到 8。將示範如何下載偵錯工具 TensorBoard TAR 檔案，並將檔案載入本機裝置上的 Jupyter 筆記本中。

![\[有關如何在本機下載和載入 Debugger TensorBoard 檔案的動畫。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/debugger-tensorboard.gif)


# 偵錯工具內建規則清單
<a name="debugger-built-in-rules"></a>

您可以使用 Amazon SageMaker Debugger 提供的偵錯工具內建規則，來分析訓練模型時收集的指標和張量。以下列出偵錯工具規則，包括如何設定和部署每個內建規則的資訊和範例。

偵錯工具內建規則監控對成功的訓練任務至關重要的各種常見條件。您可以使用 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 或低階 SageMaker API 作業來呼叫內建規則。

使用內建規則無需額外付費。如需帳單的更多相關資訊，請參閱 [Amazon SageMaker 定價](https://aws.amazon.com/sagemaker/pricing/)頁面。

**注意**  
您可以連接到訓練任務的內建規則數量上限為 20。SageMaker 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)
```

## 偵錯工具規則
<a name="debugger-built-in-rules-Rule"></a>

下列規則是可使用 `Rule.sagemaker` 類別方法呼叫的 Debugger 內建規則。

適用於產生訓練報告的偵錯工具內建規則


| 有效性範圍 | 內建規則 | 
| --- | --- | 
| SageMaker AI XGBoost 訓練任務的訓練報告 |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/debugger-built-in-rules.html)  | 

適用於偵錯模型訓練資料 (輸出張量) 的偵錯工具內建規則


| 有效性範圍 | 內建規則 | 
| --- | --- | 
| 深度學習架構 (TensorFlow、MXNet 和 PyTorch) |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/sagemaker/latest/dg/debugger-built-in-rules.html)  | 
| 深度學習應用程式 |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/debugger-built-in-rules.html)  | 
| XGBoost 演算法 |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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-built-in-rules-example.md#debugger-deploy-built-in-rules)。
+ 如需關於將內建規則與低階 SageMaker API 作業搭配使用的完整指示，請參閱[使用 SageMaker API 設定 Debugger](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 |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串清單或逗號分隔的字串  預設值：`".*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"
                } 
            )
        ]
    )
]
```

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](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 |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串  預設值：`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"
                }
            )
        ]
    )
]
```

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

**注意**  
此規則不適用於 XGBoost 演算法。

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

 此規則偵測您的模型參數初始化是否不佳。

良好的初始化會打破神經網路中的權重和梯度的對稱性，並保持各層之間相稱的啟動變異。否則，神經網路無法有效地學習。像 Xavier 這樣的初始器旨在保持啟動之間的變異固定，這對於訓練非常深的神經網路尤其重要。初始化過小可能導致梯度消失。初始化過大可能導致梯度爆炸。此規則檢查各層之間啟動輸入的變異、梯度分佈，以及初始步驟的損失收斂，以判斷神經網路的初始化是否不佳。

PoorWeightInitialization 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| activation\$1inputs\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串 預設值：`".*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"
                } 
            )
        ]
    )
]
```

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

**注意**  
此規則不適用於 XGBoost 演算法。

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

此規則偵測雙曲正切和 S 形啟動層是否變得飽和。當某層的輸入接近啟動函式的最大值或最小值時，啟動層即飽和。雙曲正切和 S 形啟動函式的最小值和最大值由各自的 `min_threshold` 和 `max_thresholds` 值定義。如果節點的活動低於 `threshold_inactivity` 百分比，則視為飽和。如果超過 `threshold_layer` 百分比的節點飽和，此規則會傳回 `True`。

SaturatedActivation 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| collection\$1names |  由規則檢查張量的集合名稱清單。 **選用** 有效值：字串清單或逗號分隔的字串 預設值：NONE  | 
| tensor\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串  預設值：`".*tanh_input\|.*sigmoid_input".`  | 
| threshold\$1tanh\$1min |  最小與最大臨界值，定義雙曲正切啟動函式的輸入極端值，定義如下：`(min_threshold, max_threshold)`。預設值是根據 0.0000001 的梯度消失臨界值決定。 **選用** 有效值：浮點數 預設值：`-9.4999`  | 
| threshold\$1tanh\$1max |  最小與最大臨界值，定義雙曲正切啟動函式的輸入極端值，定義如下：`(min_threshold, max_threshold)`。預設值是根據 0.0000001 的梯度消失臨界值決定。 **選用** 有效值：浮點數 預設值：`9.4999`  | 
| threshold\$1sigmoid\$1min |  最小與最大臨界值，定義 S 形啟動函式的輸入極端值，定義如下：`(min_threshold, max_threshold)`。預設值是根據 0.0000001 的梯度消失臨界值決定。 **選用** 有效值：浮點數 預設值：`-23`  | 
| threshold\$1sigmoid\$1max |  最小與最大臨界值，定義 S 形啟動函式的輸入極端值，定義如下：`(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"
                } 
            )
        ]
    )
]
```

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](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"
                } 
            )
        ]
    )
]
```

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](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 |  小常數，用於確保運算權重更新比例時，偵錯工具不會除以零。 **選用** 有效值：浮點數 預設值：`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"
                } 
            )
        ]
    )
]
```

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

**注意**  
此規則不適用於 XGBoost 演算法。

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

此規則偵測張量值的全部或已指定百分比是否為零。

此規則可以套用至其中一個支援的深度學習框架 (TensorFlow、MXNet 和 PyTorch) 或 XGBoost 演算法。您必須指定 `collection_names` 或 `tensor_regex` 參數。如果兩個參數都指定，此規則會檢查兩組的張量聯集。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

AllZero 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| collection\$1names |  由規則檢查張量的集合名稱清單。 **選用** 有效值：字串清單或逗號分隔的字串 預設值：`None`  | 
| tensor\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串清單或逗號分隔的字串 預設值：`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 演算法。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](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` 參數。如果兩個參數都指定，此規則會檢查兩組的張量聯集。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

LossNotDecreasing 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| collection\$1names |  由規則檢查張量的集合名稱清單。 **選用** 有效值：字串清單或逗號分隔的字串 預設值：`None`  | 
| tensor\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串清單或逗號分隔的字串  預設值：`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 |  規則檢查時用於查詢張量值的偵錯工具模式名稱。如果未通過，規則預設會依序檢查 `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 演算法。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

**注意**  
防止過度擬合的標準方法是將模型規範化。

Overfit 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| tensor\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串清單或逗號分隔的字串  預設值：NONE  | 
| 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 演算法。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

**注意**  
可提早停止以避免訓練過度。如需提早停止的相關資訊，請參閱[提前停止訓練任務](automatic-model-tuning-early-stopping.md)。如需示範如何將 Spot 訓練與偵錯工具搭配使用的範例，請參閱[以 Amazon SageMaker Debugger 啟用 Spot 訓練](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 演算法。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

SimilarAcrossRuns 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| other\$1trials |  已完成的訓練任務名稱，您想要將其張量與從目前 `base_trial` 收集的張量進行比較。 **必要** 有效值：字串  | 
| collection\$1names |  由規則檢查張量的集合名稱清單。 **選用** 有效值：字串清單或逗號分隔的字串 預設值：NONE  | 
| tensor\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串清單或逗號分隔的字串  預設值：NONE  | 

```
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` 為是，則規則會在相同帳戶中搜尋具有此字首的 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` 參數。如果兩個參數都指定，此規則會檢查兩組的張量聯集。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

TensorVariance 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| collection\$1names |  由規則檢查張量的集合名稱清單。 **選用** 有效值：字串清單或逗號分隔的字串 預設值：NONE  | 
| tensor\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串清單或逗號分隔的字串  預設值：NONE  | 
| max\$1threshold |  張量變異上限的臨界值。 **選用** 有效值：浮點數 預設值：NONE  | 
| min\$1threshold |  張量變異下限的臨界值。 **選用** 有效值：浮點數 預設值：NONE  | 

```
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` 參數。如果兩個參數都指定，此規則會檢查兩組的張量聯集。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

UnchangedTensor 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| collection\$1names |  由規則檢查張量的集合名稱清單。 **選用** 有效值：字串清單或逗號分隔的字串 預設值：NONE  | 
| tensor\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串清單或逗號分隔的字串  預設值：NONE  | 
| 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>

此規則檢查輸入影像是否已正確標準化。具體來說，此規則會偵測樣本資料的平均值與零相差是否大於一個臨界值。許多電腦視覺模型要求輸入資料具有零平均值和單位變異。

此規則適用於深度學習應用程式。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](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 符記數量過高，則應該執行替代的分桶策略。您還可以計算輸入序列中未知符記的百分比。如果未知單字的數量過高，可以使用替代字彙。

此規則適用於深度學習應用程式。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

NLPSequenceRatio 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| tensor\$1regex |  Regex 模式清單，用於將這項比較限定於特定的純量值張量。此規則只檢查與清單中指定的 Regex 模式相符的張量。如果未傳遞模式，此規則依預設會比較試驗中收集的所有張量。只能比對純量值張量。 **選用** 有效值：字串清單或逗號分隔的字串  預設值：`".*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 演算法。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](use-debugger-built-in-rules.md)。

Confusion 規則的參數描述


| 參數名稱 | 描述 | 
| --- | --- | 
| base\$1trial |  基礎試驗訓練任務名稱。此參數會由 Amazon SageMaker Debugger 自動設定為目前的訓練任務。 **必要** 有效值：字串  | 
| category\$1no |  類別的數目。 **選用** 有效值：整數 ≥2 預設值：`"None"`  | 
| labels |  `labels` 張量集合或真實標籤的 1-d 向量。 **選用** 有效值：字串 預設值：`"labels"`  | 
| predictions |  `predictions` 張量集合或預估標籤的 1-d 向量。 **選用** 有效值：字串 預設值：`"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 演算法。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](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 演算法。

如需如何設定和部署內建規則的範例，請參閱[如何設定偵錯工具內建規則](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"
                } 
            )
        ]
    )
]
```

# 使用偵錯工具用戶端程式庫建立自訂規則
<a name="debugger-custom-rules"></a>

您可以使用偵錯器規則 API 和開放原始碼 [`smdebug` Python 程式庫](https://github.com/awslabs/sagemaker-debugger/)，均提供工具供您建置自己的規則容器，建立自訂規則以監控訓練任務。

## 建立自訂規則的先決條件
<a name="debugger-custom-rules-prerequisite"></a>

若要建立偵錯器自訂規則，您需要下列先決條件。
+ [SageMaker 偵錯器 Rule.custom API](https://sagemaker.readthedocs.io/en/stable/api/training/debugger.html#sagemaker.debugger.Rule.custom)
+ [開放原始碼 smdebug Python 程式庫](https://github.com/awslabs/sagemaker-debugger/)
+ 您自己的自訂規則 python 指令碼
+ [自訂規則評估工具的 Amazon SageMaker Debugger 映像 URL](debugger-reference.md#debuger-custom-rule-registry-ids)

**Topics**
+ [建立自訂規則的先決條件](#debugger-custom-rules-prerequisite)
+ [使用 `smdebug` 用戶端程式庫來建立自訂規則作為 Python 指令碼](debugger-custom-rules-python-script.md)
+ [使用 Debugger API 執行您自己的自訂規則](debugger-custom-rules-python-sdk.md)

# 使用 `smdebug` 用戶端程式庫來建立自訂規則作為 Python 指令碼
<a name="debugger-custom-rules-python-script"></a>

`smdebug` 規則 API 提供一個介面，可設定您自己的自訂規則。下列 python 指令碼範例示範如何自建構自訂規則，`CustomGradientRule`。本教學課程自訂規則會監控梯度是否變得太大，並將預設閾值設為 10。自訂規則會在啟動訓練任務時執行由 SageMaker AI 估算器建立的基礎試驗。

```
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 指令碼中新增任意多個自訂規則類別，並透過在以下區段建置自訂規則物件，將其部署至任何訓練任務試驗。

# 使用 Debugger API 執行您自己的自訂規則
<a name="debugger-custom-rules-python-sdk"></a>

下列程式碼範例示範如何使用 [Amazon SageMaker Python SDK](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"}
)
```

以下清單說明偵錯器 `Rule.custom` API 引數。
+ `name` (str)：根據需要指定自訂規則名稱。
+ `image_uri` (str)：這是容器映像，具備理解您的自訂規則的邏輯。它會取得並評估您在訓練任務中儲存的指定張量集合。您可以從 [自訂規則評估工具的 Amazon SageMaker Debugger 映像 URL](debugger-reference.md#debuger-custom-rule-registry-ids) 找到開放原始碼 SageMaker AI 規則評估器的清單。
+ `instance_type` (str)：您需要指定執行個體來建置規則 Docker 容器。這會與訓練容器同時加速運轉執行個體。
+ `source` (str)：這是您自訂規則指令碼的本機路徑或 Amazon S3 URI。
+ `rule_to_invoke` (str)：這將指定您自訂規則指令碼的特定 Rule 類別實作。SageMaker AI 僅支援在規則任務中一次評估一個規則。
+ `collections_to_save` (str)：這會指定要儲存哪些張量集合來執行規則。
+ `rule_parameters` (字典)：這會接受採字典格式的參數輸入。您可以調整自訂規則指令碼中設定的參數。

設定 `custom_rule` 物件後，您可以將其用於建置任何訓練任務的 SageMaker AI 估算器。請指定 `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()
```

有關使用偵錯器自訂規則的更多變化和進階範例，請參閱下列範例筆記本。
+ [使用 Amazon SageMaker Debugger 自訂規則監控您的訓練任務](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_keras_custom_rule/tf-keras-custom-rule.html)
+ [ResNet 和 AlexNet 的 PyTorch 反覆運算模型刪減](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/pytorch_iterative_model_pruning)
+ [使用偵錯器規則觸發 Amazon CloudWatch Events，以根據 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 SageMaker AI 的任何深度學習模型。 AWS CLI、SageMaker AI `Estimator` API 和 Debugger APIs 可讓您使用任何 Docker 基礎映像來建置和自訂容器來訓練模型。若要 Debugger 和自訂容器搭配使用，您需要對訓練指令碼進行最小的變更，才能實施 Debugger 勾點回呼，並從訓練任務擷取張量。以下各節將逐步引導您如何使用 Debugger 搭配自訂訓練容器。

您需要下列資源，才能使用 Debugger 建置自訂容器。
+ [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable)
+ [SMDebug 開放原始碼用戶端程式庫](https://github.com/awslabs/sagemaker-debugger)
+ 您選擇的 Docker 基礎映像
+ 已註冊 Debugger 勾點的訓練指令碼——如需將 Debugger 勾點註冊至訓練指令碼的詳細資訊，請參閱[將 Debugger 勾點註冊到您的訓練指令碼](#debugger-script-mode)。

如需 Debugger 和自訂訓練容器搭配使用的端對端範例，請參閱下列範例筆記本。
+ [使用 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 ResNet50 模型示範訓練指令碼的結構，並示範如何傳遞 Debugger 勾點做為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()
```

如需註冊支援架構和演算法之 SageMaker Debugger 勾點的詳細資訊，請參閱 SMDebug 用戶端程式庫中的下列連結：
+ [SMDebug TensorFlow 勾點](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/tensorflow.md)
+ [SMDebug PyTorch 勾點](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/pytorch.md)
+ [SMDebug MXNet 勾點](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/mxnet.md)
+ [SMDebug XGBoost 勾點](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/xgboost.md)

在下列範例筆記本的訓練指令碼中，您可以找到更多有關如何將 Debugger 勾點新增至訓練指令碼，並收集詳細輸出張量的範例：
+ [具有 TensorFlow 2.1 架構的指令碼模式下的 Debugger](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow2/tensorflow2_keras_custom_container/tf2-keras-custom-container.html)

  若要了解在深度學習容器和指令碼模式中使用 Debugger 之間的差異，請開啟此筆記本，然後將它和[在深度學習容器 TensorFlow v2.1 筆記本範例中先前的 Debugger](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow2/tensorflow2_zero_code_change/tf2-keras-default-container.html) 並排放置。

   在指令碼模式下，勾點組態部分會從您設定估算器的指令碼中移除。相反地，Debugger 勾點功能會合併到訓練指令碼 [(指令碼模式下的 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)。訓練指令碼會在所需的 TensorFlow Keras 環境中匯入 `smdebug` 程式庫，以便與 TensorFlow ResNet50 演算法進行通訊。它還透過在 `train` 函式 (在第 49 行) 內新增 `callbacks=[hook]` 引數，以及新增透過 SageMaker Python SDK 提供的手動勾點組態 (在第 89 行)，來手動實作 `smdebug` 勾點功能。

  此指令碼模式範例在 TF 2.1 架構中執行訓練任務，可直接與 TF 2.1 範例中完全不變更指令碼做比較。在指令碼模式中設定 Debugger 的好處是彈性選擇 AWS 深度學習容器未涵蓋的架構版本。
+ [在指令碼模式下的 PyTorch 容器中使用 Amazon SageMaker Debugger](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/pytorch_custom_container)

  此筆記本可支援在 PyTorch v1.3.1 架構中透過指令碼模式使用 Debugger。SageMaker AI 容器可支援 PyTorch v1.3.1，而此範例提供如何修改訓練指令碼的詳細資訊。

  根據預設，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`。下列程式碼範例是一個包含基本 Docker 建置命令的 `Dockerfile`。將下列程式碼貼入 `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 之後，請使用訓練指令碼和特定的 Debugger 參數來設定 SageMaker AI 估算器。在執行 `estimator.fit()` 之後，Debugger 會收集並監控輸出張量，然後偵測訓練問題。使用儲存的張量，您可以使用 `smdebug` 核心功能和工具，進一步分析訓練任務。使用 Amazon CloudWatch Events 設定偵錯工具規則監控程序的工作流程 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 設定 Debugger
<a name="debugger-createtrainingjob-api"></a>

 上述主題著重於透過 Amazon SageMaker Python SDK 使用 Debugger，這是圍繞 適用於 Python (Boto3) 的 AWS SDK 和 SageMaker API 操作的包裝函式。這提供存取 Amazon SageMaker API 作業的高階體驗。如果您需要為其他 SDKs 使用 AWS Boto3 或 AWS Command Line Interface (CLI) 手動設定 SageMaker API 操作，例如 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>

透過 SageMaker AI [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)、[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 SageMaker Debugger 內建規則。您需要在 `RuleEvaluatorImage` 參數中指定正確的映像 URI，下列範例會逐步引導您如何設定 JSON 字串以請求 [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html).。

下列程式碼會顯示完整的 JSON 範本，使用必要設定和 Debugger 組態執行訓練任務。將範本儲存為工作目錄中的 JSON 檔案，並使用 CLI AWS 執行訓練任務。例如，將以下程式碼儲存為 `debugger-training-job-cli.json`。

**注意**  
請確定您使用正確的 Docker 容器映像。若要尋找 AWS 深度學習容器映像，請參閱[可用的深度學習容器映像](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"
            }
        }
    ]
}
```

這將讓訓練任務儲存張量集合(`gradients`、每 500 個步驟就 `save_interval` 一次)。若要找到可用的 `CollectionName` 值，請參閱 *SMDebug 用戶端程式庫文件*中的 [Debugger 內建集合](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 會使用 `gradients` 張量集合上的 `VanishingGradient` 規則，對訓練任務啟動規則評估任務。要查找使用 Debugger 規則的可用 Docker 映像的完整清單，請參閱[Debugger 規則的 Docker 映像檔](debugger-reference.md#debugger-docker-images-rules)。若要查找 `RuleParameters` 的鍵值對，請參閱[偵錯工具內建規則清單](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-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 作業來執行訓練任務時，可以更新 Debugger 分析組態。設定新的 [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.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 映像，可用來執行您的自訂規則。這些都列在 [自訂規則評估工具的 Amazon SageMaker Debugger 映像 URL](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-built-in-rules.md)。

# 適用於 Python 的 SDK (Boto3)
<a name="debugger-built-in-rules-api.Boto3"></a>

您可以使用 AWS Boto3 SageMaker AI 用戶端的 函數，為訓練任務設定 Amazon SageMaker Debugger 內建規則。 [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)您需要在 `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) 功能的請求內文。

下列程式碼假設使用 TensorFlow 準備訓練指令碼 `entry_point/train.py`，完整示範如何設定 `create_training_job()` 請求內文的 Debugger，並啟動位於 `us-west-2` 的訓練任務。若要找到端對端範例筆記本，請參閱[使用 Amazon SageMaker Debugger (Boto3) 分析 TensorFlow 多重 GPU 多節點訓練任務](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node-boto3.html)。

**注意**  
請確定您使用正確的 Docker 容器映像。若要尋找可用的 AWS 深度學習容器映像，請參閱[可用的深度學習容器映像](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'
            }
        }
    ]
}
```

這將讓訓練任務儲存一個張量集合(`gradients`、每 500 個步驟就 `save_interval` 一次)。若要找到可用的 `CollectionName` 值，請參閱 *SMDebug 用戶端程式庫文件*中的 [Debugger 內建集合](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 會使用 `gradients` 張量集合上的 `VanishingGradient` 規則，對訓練任務啟動規則評估任務。要查找使用 Debugger 規則的可用 Docker 映像的完整清單，請參閱[Debugger 規則的 Docker 映像檔](debugger-reference.md#debugger-docker-images-rules)。若要查找 `RuleParameters` 的鍵值對，請參閱[偵錯工具內建規則清單](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-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)函數來更新偵錯工具分析組態。 SageMaker 設定新的 [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'
```

## 將 Debugger 自訂規則組態新增至 CreateTrainingJob API 作業
<a name="debugger-custom-rules-api.Boto3"></a>

您可以使用 [ DebugHookConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html) 為訓練任務設定自訂規則，並使用 AWS Boto3 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)函數為 [ DebugRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html) 物件設定自訂規則。下列程式碼範例示範如何使用此 SageMaker API 作業來設定以 *smdebug* 程式庫撰寫的自訂 `ImproperActivation` 規則。此範例假設您已在 *custom\$1rules.py* 檔案中撰寫自訂規則，並上傳到 Amazon S3 儲存貯體。下列範例提供預先建置的 Docker 映像，可用來執行您的自訂規則。這些都列在 [自訂規則評估工具的 Amazon SageMaker Debugger 映像 URL](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-built-in-rules.md)。

# Amazon SageMaker Debugger 參考
<a name="debugger-reference"></a>

在下列主題中，尋找有關使用 Amazon SageMaker Debugger 的詳細資訊和參考。

**Topics**
+ [Amazon SageMaker Debugger API](#debugger-apis)
+ [Debugger 規則的 Docker 映像檔](#debugger-docker-images-rules)
+ [Amazon SageMaker Debugger 例外狀況](#debugger-exceptions)
+ [Amazon SageMaker Debugger 支援的分散式訓練](#debugger-considerations)

## Amazon SageMaker Debugger API
<a name="debugger-apis"></a>

Amazon SageMaker Debugger 在很多位置都有 API 作業，用於實作模型訓練的監控和分析。

Amazon SageMaker Debugger 也提供開放原始碼 [`sagemaker-debugger` Python SDK](https://github.com/awslabs/sagemaker-debugger/tree/master/smdebug)，可用來設定內建規則、定義自訂規則以及註冊勾點，從訓練任務收集輸出張量資料。

[Amazon SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/) 是一套以機器學習實驗為主的高階軟體開發套件。此軟體開發套件可用於部署以 `SMDebug` Python 程式庫定義的內建或自訂規則，以使用 SageMaker AI 估算器監控和分析這些張量。

Debugger 在 Amazon SageMaker API 中新增操作和類型，可讓平台在訓練模型時使用 Debugger，以及管理輸入和輸出的組態。
+ [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 API 設定張量集合、規則、規則映像和分析選項：
  + [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 Processing 功能。如需 SageMaker Processing 的詳細資訊，請參閱[使用 SageMaker Processing 的資料轉換工作負載](processing-job.md)。

## Debugger 規則的 Docker 映像檔
<a name="debugger-docker-images-rules"></a>

Amazon SageMaker AI 為規則提供兩組 Docker 映像：一組用於評估 SageMaker AI 提供的規則 (內建規則)，另一組用於評估 Python 來源檔案中提供的自訂規則。

如果您使用 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable)，您可以僅使用 SageMaker AI 高階偵錯器 API 作業搭配 SageMaker AI 估算器 API 作業，無需手動擷取偵錯器 Docker 映像並設定 `ConfigureTrainingJob` API。

如果您未使用 SageMaker Python SDK，則必須為偵錯器規則擷取相關的預先建置容器基礎映像。Amazon SageMaker Debugger 為內建和自訂規則提供預先建置的 Docker 映像，而該映像儲存在 Amazon Elastic Container Registry (Amazon ECR) 中。若要從 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 Debugger 映像 URL](#debuger-built-in-registry-ids)
+ [自訂規則評估工具的 Amazon SageMaker Debugger 映像 URL](#debuger-custom-rule-registry-ids)

### 內建規則評估工具的 Amazon SageMaker Debugger 映像 URL
<a name="debuger-built-in-registry-ids"></a>

對於為 Amazon SageMaker Debugger 提供內建規則的映像，請對映像的登錄 URL 元件使用以下的值。如需帳戶 ID，請參閱下表。

**ECR 儲存庫名稱**：sagemaker-debugger-rules 

**標籤**：latest 

**完整的登錄 URL 範例**：

`904829902805.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-debugger-rules:latest`

依 AWS 區域分類的內建規則容器映像的帳戶 IDs 


| 區域 | 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  | 

### 自訂規則評估工具的 Amazon SageMaker Debugger 映像 URL
<a name="debuger-custom-rule-registry-ids"></a>

對於為 Amazon SageMaker Debugger 提供自訂規則評估工具的映像，請對映像的登錄 URL 元件使用以下的值。如需帳戶 ID，請參閱下表。

**ECR 儲存庫名稱**：sagemaker-debugger-rule-evaluator 

**標籤**：latest 

**完整的登錄 URL 範例**：

`552407032007.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-debugger-rule-evaluator:latest`

依 AWS 區域自訂規則容器映像的帳戶 IDs 


| 區域 | 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 Debugger 例外狀況
<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 Debugger 支援的分散式訓練
<a name="debugger-considerations"></a>

下列清單顯示在具有深度學習架構和各種分散式訓練選項的訓練任務上使用 Debugger 的有效性範圍和考量事項。
+ **Horovod**

  使用 Debugger 進行 Horovod 訓練任務的有效性範圍    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/debugger-reference.html)
+ **SageMaker AI 分散式資料平行**

  使用 Debugger 與 SageMaker AI 分散式資料平行進行訓練任務的有效性範圍    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/debugger-reference.html)

  \$1 Debugger 不支援 TensorFlow 2.x 的架構分析。

  \$1\$1 SageMaker AI 分散式資料平行不支援具有 Keras 實作的 TensorFlow 2.x。
+ **SageMaker AI 分散式模型平行**——Debugger 不支援 SageMaker AI 分散式模型平行訓練。
+ **具有 SageMaker AI 檢查點的分散式訓練**——啟用分散式訓練選項和 SageMaker AI 檢查點時，Debugger 不可用於訓練任務。您可能會看到類似以下的錯誤：

  ```
  SMDebug Does Not Currently Support Distributed Training Jobs With Checkpointing Enabled
  ```

  若要使用 Debugger 進行具有分散式訓練選項的訓練任務，您需要停用 SageMaker AI 檢查點，並將手動檢查點功能新增至訓練指令碼。有關 Debugger 搭配分散式訓練選項和檢查點使用的詳細資訊，請參閱[將 SageMaker AI 分散式資料平行與 Amazon SageMaker Debugger 和檢查點搭配使用](distributed-troubleshooting-data-parallel.md#distributed-ts-data-parallel-debugger)和[儲存檢查點](distributed-troubleshooting-model-parallel.md#distributed-ts-model-parallel-checkpoints)。
+ **參數伺服器**——Debugger不支援以參數伺服器為基礎的分散式訓練。
+ 沒有可用的分析分散式訓練架構作業，例如 SageMaker AI 分散式資料平行的 `AllReduced` 作業和 [Horovod 作業](https://horovod.readthedocs.io/en/stable/timeline_include.html)。