

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

# 偵錯並改善模型效能
<a name="train-debug-and-improve-model-performance"></a>

訓練機器學習模型、深度學習神經網路、轉換器模型的核心在於實現穩定的模型收斂，因此，最先進的模型具有數百萬、數十億或數兆個模型參數。在每次反覆執行期間，更新龐大數量的模型參數的操作次數很容易變成天文數字。若要識別模型收斂問題，必須能夠存取最佳化程序期間運算的模型參數、啟用和漸層。

Amazon SageMaker AI 提供兩種偵錯工具，可協助識別此類收斂問題，並深入了解您的模型。

**具備 TensorBoard 的 Amazon SageMaker AI**

為了提供與 SageMaker AI Training 平台中開放原始碼社群工具的更大相容性，SageMaker AI 將 TensorBoard 託管為 [SageMaker AI 網域](https://docs.aws.amazon.com/sagemaker/latest/dg/sm-domain.html)中的應用程式。您可以將訓練任務帶到 SageMaker AI，並繼續使用 TensorBoard 摘要寫入器來收集模型輸出張量。由於 TensorBoard 已實作到 [SageMaker AI 網域](https://docs.aws.amazon.com/sagemaker/latest/dg/sm-domain.html)中，因此它還為您提供更多選項來管理 AWS 您帳戶中 SageMaker AI 網域下的使用者設定檔，並透過授予對特定動作和資源的存取權，提供對使用者設定檔的精細控制。如需詳細資訊，請參閱 [Amazon SageMaker AI 中的 TensorBoard](tensorboard-on-sagemaker.md)。

**Amazon SageMaker Debugger**

Amazon SageMaker Debugger 是 SageMaker AI 的功能，提供工具來註冊回呼勾點，以擷取模型輸出張量，並將其儲存在 Amazon Simple Storage Service。它為偵測模型收斂問題提供[內建規則](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-built-in-rules.html)，例如過度擬合、飽和啟動函式、消失梯度等。您也可以使用 Amazon CloudWatch Events 設定內建規則 AWS Lambda ，並針對偵測到的問題採取自動化動作，以及設定 Amazon Simple Notification Service 來接收電子郵件或簡訊通知。如需進一步了解，請參閱[Amazon SageMaker Debugger](train-debugger.md)。

**Topics**
+ [

# Amazon SageMaker AI 中的 TensorBoard
](tensorboard-on-sagemaker.md)
+ [

# Amazon SageMaker Debugger
](train-debugger.md)
+ [

# 透過 存取訓練容器 AWS Systems Manager 以進行遠端偵錯
](train-remote-debugging.md)
+ [

# Amazon SageMaker AI 偵錯功能的版本備註
](debugger-release-notes.md)

# Amazon SageMaker AI 中的 TensorBoard
<a name="tensorboard-on-sagemaker"></a>

使用 TensorBoard 的 Amazon SageMaker AI 是一種 Amazon SageMaker AI 的功能，將 [TensorBoard](https://www.tensorflow.org/tensorboard) 的視覺化工具帶到 SageMaker AI，與 SageMaker 訓練和網域進行整合。它提供選項來透過 [SageMaker AI 網域](https://docs.aws.amazon.com/sagemaker/latest/dg/sm-domain.html)管理 AWS 您的帳戶和屬於該帳戶的使用者，讓網域使用者存取具有 Amazon S3 適當許可的 TensorBoard 資料，並協助網域使用者使用 TensorBoard 視覺化外掛程式執行模型偵錯任務。具有 TensorBoard 的 SageMaker AI 透過 SageMaker AI 資料管理員外掛程式進行擴充，讓網域使用者可以集中在 TensorBoard 應用程式存取許多訓練任務。

**注意**  
此功能適用於使用 PyTorch 或 TensorFlow 來偵錯深度學習模型訓練。

**對於資料科學家**

訓練大型模型可能會遇到科學問題，這些問題需要資料科學家對其進行偵錯和解決，以改善模型收斂並穩定梯度下降程序。

當您遇到模型訓練問題時 (例如遺失值未收斂、權重和梯度消失或爆炸)，您需要存取張量資料，以深入探索並分析模型參數、純量和任何自訂指標。使用 SageMaker AI 搭配 TensorBoard，您可以從訓練任務擷取視覺化模型的輸出張量。當您試圖使用不同的模型、多個訓練執行和建立超參數的模型時，您可以在 TensorBoard 中選取多個訓練任務，並在同一處進行比較。

**針對管理員**

如果您是 AWS 帳戶或 SageMaker AI 網域的管理員，您可以透過 SageMaker AI 主控台或 [SageMaker AI](https://docs.aws.amazon.com/sagemaker/latest/dg/sm-domain.html) SageMaker 網域中的 TensorBoard 登陸頁面來管理 TensorBoard 應用程式使用者。 TensorBoard 每個網域使用者都可以透過授予許可存取自己的 TensorBoard 應用程式。身為 SageMaker AI 網域管理員和網域使用者，您可以根據擁有的權限層級，建立和刪除 TensorBoard 應用程式。

**注意**  
您不能分享 TensorBoard 應用程式進行協作，因為 SageMaker AI 網域不允許使用者間共用應用程式。如果使用者有儲存貯體的存取權限，他們可以共用儲存在 S3 儲存貯體中的輸出張量。

## 支援的架構和 AWS 區域
<a name="debugger-htb-support"></a>

SageMaker AI 中的 TensorBoard 應用程式適用於下列機器學習架構和 AWS 區域。

**架構**
+ PyTorch
+ TensorFlow
+ Hugging Face 轉換器

**AWS 區域**
+ 美國東部 (維吉尼亞北部) (`us-east-1`)
+ 美國東部 (俄亥俄) (`us-east-2`)
+ 美國西部 (奧勒岡) (`us-west-2`)
+ 歐洲 (法蘭克福) (`eu-central-1`)
+ 歐洲 (愛爾蘭) (`eu-west-1`)

**注意**  
具有 TensorBoard 的 Amazon SageMaker AI 會在 `ml.r5.large` 執行個體上執行，並在使用 SageMaker AI 免費方案或該功能的免費試用期後產生費用。如需更多資訊，請參閱 [Amazon SageMaker AI 定價](https://aws.amazon.com/sagemaker/pricing/)。

**Topics**
+ [

## 支援的架構和 AWS 區域
](#debugger-htb-support)
+ [

# 準備訓練任務以收集 TensorBoard 輸出資料
](debugger-htb-prepare-training-job.md)
+ [

# 在 SageMaker AI 上存取 TensorBoard 應用程式
](debugger-htb-access-tb.md)
+ [

# 使用 TensorBoard 應用程式載入和視覺化輸出張量
](debugger-htb-access-tb-data.md)
+ [

# 刪除未使用的 TensorBoard 應用程式
](debugger-htb-delete-app.md)

# 準備訓練任務以收集 TensorBoard 輸出資料
<a name="debugger-htb-prepare-training-job"></a>

SageMaker AI 中，機器學習的典型訓練任務包含兩個主要步驟：準備訓練指令碼和設定 SageMaker AI Python SDK 的 SageMaker AI 估算器物件。在本節中，您將了解所需的變更，以便從 SageMaker 訓練任務中收集與 TensorBoard 相容的資料。

## 先決條件
<a name="debugger-htb-prerequisites"></a>

下列清單顯示開始使用 SageMaker AI 與 TensorBoard 的先決條件。
+  AWS 帳戶中使用 Amazon VPC 設定的 SageMaker AI 網域。

  如需有關設定網域的指示，請參閱[使用快速設定佈設到 Amazon SageMaker AI 網域](https://docs.aws.amazon.com/sagemaker/latest/dg/onboard-quick-start.html)。您還需要為個別使用者新增網域使用者設定檔，才能在 SageMaker AI 上存取 TensorBoard。如需詳細資訊，請參閱[新增使用者設定檔](domain-user-profile-add.md)。
+ 下列清單是在 SageMaker AI 上使用 TensorBoard 時所需的最低許可組合。
  + `sagemaker:CreateApp`
  + `sagemaker:DeleteApp`
  + `sagemaker:DescribeTrainingJob`
  + `sagemaker:Search`
  + `s3:GetObject`
  + `s3:ListBucket`

## 步驟 1：使用開放原始碼 TensorBoard 協助程式工具修改訓練指令碼
<a name="debugger-htb-prepare-training-job-1"></a>

請確定您決定要收集哪些輸出張量和純量，並使用下列任一工具修改訓練指令碼中的程式碼：TensorBoardX、TensorFlow 摘要寫入器、PyTorch 摘要寫入器或 SageMaker Debugger。

此外，請務必將 TensorBoard 資料輸出路徑，指定為訓練容器中回調的日誌目錄 (`log_dir`)。

如需每個架構回調的更多相關資訊，請參閱下列資源。
+ PyTorch 的話，請使用[torch.utils.tensorboard.SummaryWriter](https://pytorch.org/docs/stable/tensorboard.html#module-torch.utils.tensorboard)。另請參閱*PyTorch 教學課程*內的[在 PyTorch 中使用 TensorBoard](https://pytorch.org/tutorials/recipes/recipes/tensorboard_with_pytorch.html#using-tensorboard-in-pytorch) 和[日誌純量](https://pytorch.org/tutorials/recipes/recipes/tensorboard_with_pytorch.html#log-scalars)章節。或者，您也可以使用 [TensorBoardX 摘要寫入器](https://tensorboardx.readthedocs.io/en/latest/tutorial.html)。

  ```
  LOG_DIR="/opt/ml/output/tensorboard"
  tensorboard_callback=torch.utils.tensorboard.writer.SummaryWriter(log_dir=LOG_DIR)
  ```
+ 針對 TensorFlow，請使用 TensorBoard 的原生回調，[tf.keras.callbacks.TensorBoard](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/TensorBoard)。

  ```
  LOG_DIR="/opt/ml/output/tensorboard"
  tensorboard_callback=tf.keras.callbacks.TensorBoard(
      log_dir=LOG_DIR, histogram_freq=1)
  ```
+ 如為 PyTorch 轉換器，您可以使用[transformers.integrations.TensorBoardCallback](https://huggingface.co/docs/transformers/main/en/main_classes/callback#transformers.integrations.TensorBoardCallback)。

  對於 TensorFlow 的轉換器，請使用`tf.keras.tensorboard.callback`，並將其傳遞給轉換器中的 keras 回調。
**提示**  
您也可以使用不同的容器本機輸出路徑。不過在 [步驟 2：使用 TensorBoard 輸出組態建立 SageMaker 訓練估算器物件](#debugger-htb-prepare-training-job-2)，您必須正確對應路徑，SageMaker AI 才能成功搜尋本機路徑，並將 TensorBoard 資料儲存至 S3 輸出儲存貯體。
+ 如需使用 SageMaker Debugger Python 程式庫修改訓練指令碼的指引，請參閱[調整您的訓練指令碼以註冊勾點](debugger-modify-script.md)。

## 步驟 2：使用 TensorBoard 輸出組態建立 SageMaker 訓練估算器物件
<a name="debugger-htb-prepare-training-job-2"></a>

在設定 SageMaker AI 架構估算器時使用 `sagemaker.debugger.TensorBoardOutputConfig`。此組態 API 會將您指定用來儲存 TensorBoard 資料的 S3 儲存貯體，與訓練容器 (`/opt/ml/output/tensorboard`) 中的本機路徑對應。將模組的物件傳遞給估算器類別的`tensorboard_output_config`參數。下列程式碼片段為一則範例，顯示使用 TensorBoard 輸出組態參數準備 TensorFlow 估算器。

**注意**  
此範例假設您使用 SageMaker Python SDK。如果您使用低階 SageMaker API，則應在 [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) API 的請求語法中包含以下內容。  

```
"TensorBoardOutputConfig": { 
  "LocalPath": "/opt/ml/output/tensorboard",
  "S3OutputPath": "s3_output_bucket"
}
```

```
from sagemaker.tensorflow import TensorFlow
from sagemaker.debugger import TensorBoardOutputConfig

# Set variables for training job information, 
# such as s3_out_bucket and other unique tags.
... 

LOG_DIR="/opt/ml/output/tensorboard"

output_path = os.path.join(
    "s3_output_bucket", "sagemaker-output", "date_str", "your-training_job_name"
)

tensorboard_output_config = TensorBoardOutputConfig(
    s3_output_path=os.path.join(output_path, 'tensorboard'),
    container_local_output_path=LOG_DIR
)

estimator = TensorFlow(
    entry_point="train.py",
    source_dir="src",
    role=role,
    image_uri=image_uri,
    instance_count=1,
    instance_type="ml.c5.xlarge",
    base_job_name="your-training_job_name",
    tensorboard_output_config=tensorboard_output_config,
    hyperparameters=hyperparameters
)
```

**注意**  
TensorBoard 應用程式不提供立即可用的 SageMaker AI 超參數調校任務支援，因為 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateHyperParameterTuningJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateHyperParameterTuningJob.html) API 未與映射的 TensorBoard 輸出組態整合。若要將 TensorBoard 應用程式用於超參數調校任務，您需要在訓練指令碼中撰寫將指標上傳至 Amazon S3 的程式碼。將指標上傳至 Amazon S3 儲存貯體後，您就可以將儲存貯體載入 SageMaker AI 上的 TensorBoard 應用程式。

# 在 SageMaker AI 上存取 TensorBoard 應用程式
<a name="debugger-htb-access-tb"></a>

您可以透過兩種方法存取 TensorBoard：透過程式設計方式使用產生未登入或預先登入 URL 的 `sagemaker.interactive_apps.tensorboard` 模組，或使用 SageMaker AI 主控台中的 TensorBoard 登陸頁面。開啟 Tensorboard 之後，SageMaker AI 會執行 TensorBoard 外掛程式，並自動尋找所有訓練任務輸出資料，並以 TensorBoard 相容的檔案格式自動尋找。

**Topics**
+ [

# 使用`sagemaker.interactive_apps.tensorboard`模組開啟 TensorBoard
](debugger-htb-access-tb-url.md)
+ [

# 使用`get_app_url`函式做為`estimator`類方法來開啟 TensorBoard
](debugger-htb-access-tb-get-app-url-estimator-method.md)
+ [

# 透過 SageMaker AI 主控台開啟 TensorBoard
](debugger-htb-access-tb-console.md)

# 使用`sagemaker.interactive_apps.tensorboard`模組開啟 TensorBoard
<a name="debugger-htb-access-tb-url"></a>

`sagemaker.interactive_apps.tensorboard` 模組提供一個名為 `get_app_url` 的函式，可產生未登入或預先登入的 URL，以便在 SageMaker AI 或 Amazon EC2 的任何環境中開啟 TensorBoard 應用程式。這是為了為 Studio Classic 和非 Studio Classic 使用者提供一致的體驗。對於 Studio 環境，您可以透過依原樣執行 `get_app_url()` 函式來開啟 TensorBoard，也可以指定任務名稱，在 TensorBoard 應用程式開啟時開始追蹤。對於非 Studio Classic 環境，您可以將網域和使用者設定檔資訊提供給公用程式功能，以開啟 TensorBoard。使用此功能，無論您在何處或以何種方式執行訓練程式碼及啟動訓練任務，都可以透過在您的 Jupyter 筆記本或終端機中執行 `get_app_url` 函式直接存取 TensorBoard。

**注意**  
此功能可在 SageMaker Python SDK v2.184.0 及更新版本中使用。若要使用此功能，請務必透過`pip install sagemaker --upgrade`執行升級 SDK。

**Topics**
+ [

## 選項 1：適用於 SageMaker AI Studio Classic
](#debugger-htb-access-tb-url-unsigned)
+ [

## 選項 2：適用於非 Studio Classic 環境
](#debugger-htb-access-tb-url-presigned)

## 選項 1：適用於 SageMaker AI Studio Classic
<a name="debugger-htb-access-tb-url-unsigned"></a>

如果您使用的是 SageMaker Studio Classic，您可以按照下列說明執行 `get_app_url` 函式，直接開啟 TensorBoard 應用程式或擷取未登入的 URL。由於您已經在 Studio Classic 環境中以網域使用者身分登入，不需要再次驗證，因此 `get_app_url()` 會產生未登入的 URL。

**開啟 TensorBoard 應用程式** 

下列程式碼會將從`get_app_url()`函式傳回的未登入 URL，以環境預設的網頁瀏覽器自動開啟 TensorBoard 應用程式。

```
from sagemaker.interactive_apps import tensorboard

region = "us-west-2"
app = tensorboard.TensorBoardApp(region)

app.get_app_url(
    training_job_name="your-training_job_name" # Optional. Specify the job name to track a specific training job 
)
```

**擷取未登入的 URL 並手動開啟 TensorBoard 應用程式**

下列程式碼會列印未登入的 URL，您可以複製到網頁瀏覽器並開啟 TensorBoard 應用程式。

```
from sagemaker.interactive_apps import tensorboard

region = "us-west-2"
app = tensorboard.TensorBoardApp(region)
print("Navigate to the following URL:")
print(
    app.get_app_url(
        training_job_name="your-training_job_name", # Optional. Specify the name of the job to track.
        open_in_default_web_browser=False           # Set to False to print the URL to terminal.
    )
)
```

請注意，如果您在 SageMaker AI Studio Classic 環境之外執行前兩個程式碼範例，該函式會將 TensorBoard 登陸頁面的 URL 傳回至 SageMaker AI 主控台，因為這些範例沒有您的網域和使用者設定檔的登入資訊。如需建立預先登入的 URL，請參閱下一節中的選項 2。

## 選項 2：適用於非 Studio Classic 環境
<a name="debugger-htb-access-tb-url-presigned"></a>

如果您使用非 Studio Classic 環境 (例如 SageMaker 筆記本執行個體或 Amazon EC2)，並且想要直接從您所在的環境開啟 TensorBoard，則需要使用網域和使用者設定檔資訊產生預先登入的 URL。*預先登入*的 URL 是已登入 Amazon SageMaker Studio Classic 的 URL，由於您當時正在使用您的網域和使用者設定檔，因此會授予與您網域相關聯的所有網域應用程式和檔案的存取權。若要透過預先登入的網址開啟 TensorBoard，請依照下列方式使用您的網域和使用者設定檔名稱的 `get_app_url` 功能。

請注意，此選項需要網域使用者擁有 `sagemaker:CreatePresignedDomainUrl` 許可權限。如果沒有許可權限，網域使用者將會收到例外狀況錯誤。

**重要**  
請勿與他人分享任何預先登入的 URL。此 `get_app_url` 功能會建立預先登入的 URL，該 URL 會自動使用您的網域和使用者設定檔進行驗證，並可存取與您網域相關聯的任何應用程式和檔案。

```
print(
    app.get_app_url(
        training_job_name="your-training_job_name", # Optional. Specify the name of the job to track.
        create_presigned_domain_url=True,           # Reguired to be set to True for creating a presigned URL.
        domain_id="your-domain-id",                 # Required if creating a presigned URL (create_presigned_domain_url=True).
        user_profile_name="your-user-profile-name", # Required if creating a presigned URL (create_presigned_domain_url=True).
        open_in_default_web_browser=False,          # Optional. Set to False to print the URL to terminal.
        optional_create_presigned_url_kwargs={}     # Optional. Add any additional args for Boto3 create_presigned_domain_url
    )
)
```

**提示**  
`get_app_url` 函數會在後端的 適用於 Python (Boto3) 的 AWS SDK 中執行 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_presigned_domain_url.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_presigned_domain_url.html) API。由於 Boto3 `create_presigned_domain_url` API 建立預先登入的網域網址，預設會在 300 秒內到期，因此預先登入的 TensorBoard 應用程式 URL 也會在 300 秒後到期。如果要延長到期時間，請將`ExpiresInSeconds`引數發送至`get_app_url`功能的`optional_create_presigned_url_kwargs`參數，如下所示。  

```
optional_create_presigned_url_kwargs={"ExpiresInSeconds": 1500}
```

**注意**  
如果您傳遞給`get_app_url`引數的輸入有任何無效值，函式會將 URL 輸出到 TensorBoard 登陸頁面，而不會開啟 TensorBoard 應用程式。輸出訊息可能類似以下內容。  

```
Navigate to the following URL:
https://us-west-2.console.aws.amazon.com/sagemaker/home?region=us-west-2#/tensor-board-landing
```

# 使用`get_app_url`函式做為`estimator`類方法來開啟 TensorBoard
<a name="debugger-htb-access-tb-get-app-url-estimator-method"></a>

如果您正在使用 SageMaker Python SDK 的`estimator`類別執行訓練任務，並且具有`estimator`類別的使用中物件，您也可以將[`get_app_url`函式當做`estimator`類的類別方法](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.EstimatorBase.get_app_url)存取。開啟 TensorBoard 應用程式，或透過執行`get_app_url`方法擷取未登入的 URL，如下所示。`get_app_url`類方法會從估算器擷取訓練任務名稱，並開啟具有指定任務的 TensorBoard 應用程式。

**注意**  
此功能可在 SageMaker Python SDK v2.184.0 及更新版本中使用。若要使用此功能，請務必透過`pip install sagemaker --upgrade`執行升級 SDK。

**Topics**
+ [

## 選項 1：適用於 SageMaker Studio Classic
](#debugger-htb-access-tb-get-app-url-estimator-method-studio)
+ [

## 選項 2：適用於非 Studio Classic 環境
](#debugger-htb-access-tb-get-app-url-estimator-method-non-studio)

## 選項 1：適用於 SageMaker Studio Classic
<a name="debugger-htb-access-tb-get-app-url-estimator-method-studio"></a>

**開啟 TensorBoard 應用程式** 

下列程式碼會將從`get_app_url()`方法傳回的未登入 URL，以環境預設的網頁瀏覽器自動開啟 TensorBoard 應用程式。

```
estimator.get_app_url(
    app_type=SupportedInteractiveAppTypes.TENSORBOARD # Required.
)
```

**擷取未登入的 URL 並手動開啟 TensorBoard 應用程式**

下列程式碼會列印未登入的 URL，您可以複製到網頁瀏覽器並開啟 TensorBoard 應用程式。

```
print(
    estimator.get_app_url(
        app_type=SupportedInteractiveAppTypes.TENSORBOARD, # Required.
        open_in_default_web_browser=False, # Optional. Set to False to print the URL to terminal.
    )
)
```

請注意，如果您在 SageMaker AI Studio Classic 環境之外執行前兩個程式碼範例，該函式會將 TensorBoard 登陸頁面的 URL 傳回至 SageMaker AI 主控台，因為這些範例沒有您的網域和使用者設定檔的登入資訊。如需建立預先登入的 URL，請參閱下一節中的選項 2。

## 選項 2：適用於非 Studio Classic 環境
<a name="debugger-htb-access-tb-get-app-url-estimator-method-non-studio"></a>

如果您使用非 Studio Classic 環境 (例如 SageMaker 筆記本執行個體或 Amazon EC2)，並且想要產生預先登入 URL 以開啟 TensorBoard，您需要使用 `get_app_url` 方法，透過您的網域和使用者設定檔資訊進行，如下所示。

請注意，此選項需要網域使用者擁有 `sagemaker:CreatePresignedDomainUrl` 許可權限。如果沒有許可權限，網域使用者將會收到例外狀況錯誤。

**重要**  
請勿與他人分享任何預先登入的 URL。此 `get_app_url` 功能會建立預先登入的 URL，該 URL 會自動使用您的網域和使用者設定檔進行驗證，並可存取與您網域相關聯的任何應用程式和檔案。

```
print(
    estimator.get_app_url(
        app_type=SupportedInteractiveAppTypes.TENSORBOARD, # Required
        create_presigned_domain_url=True,           # Reguired to be set to True for creating a presigned URL.
        domain_id="your-domain-id",                 # Required if creating a presigned URL (create_presigned_domain_url=True).
        user_profile_name="your-user-profile-name", # Required if creating a presigned URL (create_presigned_domain_url=True).
        open_in_default_web_browser=False,            # Optional. Set to False to print the URL to terminal.
        optional_create_presigned_url_kwargs={}       # Optional. Add any additional args for Boto3 create_presigned_domain_url
    )
)
```

# 透過 SageMaker AI 主控台開啟 TensorBoard
<a name="debugger-htb-access-tb-console"></a>

您也可以使用 SageMaker AI 主控台使用者介面來開啟 TensorBoard 應用程式。有兩個選項可透過 SageMaker AI 主控台開啟 TensorBoard 應用程式。

**Topics**
+ [

## 選項 1：從網域詳細資訊頁面啟動 TensorBoard
](#debugger-htb-access-tb-console-domain-detail)
+ [

## 選項 2：從 TensorBoard 登陸頁面啟動 TensorBoard
](#debugger-htb-access-tb-console-landing-pg)

## 選項 1：從網域詳細資訊頁面啟動 TensorBoard
<a name="debugger-htb-access-tb-console-domain-detail"></a>

**導覽至網域詳細資訊頁面**

 下列程序會說明如何導覽至網域詳細資訊頁面。

1. 開啟 Amazon SageMaker AI 主控台，網址為 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/)。

1. 在左側導覽窗格中，選擇**管理員組態**。

1. 在**管理員組態**下，選擇**網域**。

1. 從網域清單中選取您要啟動 TensorBoard 應用程式的網域。

**啟動使用者設定檔應用程式**

下列程序顯示如何啟動範圍為使用者設定檔的 Studio Classic 應用程式。

1. 在網域詳細資訊頁面，選取**使用者設定檔**索引標籤。

1. 識別您要啟動 Studio Classic 應用程式的使用者設定檔。

1. 以選定的使用者設定檔選擇**啟動**，然後選擇 **TensorBoard**。

## 選項 2：從 TensorBoard 登陸頁面啟動 TensorBoard
<a name="debugger-htb-access-tb-console-landing-pg"></a>

下列程序說明如何從 TensorBoard 登陸頁面啟動 TensorBoard 應用程式。

1. 開啟位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 Amazon SageMaker AI 主控台。

1. 在左側導覽面板上，選擇 **TensorBoard**。

1. 在**立即開始**下方，選取您要啟動 Studio Classic 應用程式的網域。如果您的使用者設定檔只屬於一個網域，您將看不到選取網域的選項。

1. 選取您要用來啟動 Studio Classic 應用程式的使用者設定檔。如果網域中沒有使用者設定檔，請選取**建立使用者設定檔**。如需更多資訊，請參閱[新增和移除使用者設定檔](https://docs.aws.amazon.com/sagemaker/latest/dg/domain-user-profile-add.html)。

1. 選擇**開啟 TensorBoard**。

下列螢幕擷取畫面示範 TensorBoard 在 SageMaker AI 主控台的左側導覽面板中的位置，以及主面板中具有 TensorBoard 登陸頁面的 SageMaker AI。

![\[TensorBoard 登陸頁面\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/htb-landing-page.png)


# 使用 TensorBoard 應用程式載入和視覺化輸出張量
<a name="debugger-htb-access-tb-data"></a>

在訓練期間或訓練後，您可以載入從 S3 儲存貯體收集到的輸出張量及對應的訓練任務，以進行線上或離線分析。

當您開啟 TensorBoard 應用程式時，會以 **SageMaker AI 資料管理員**索引標籤開啟 TensorBoard。下列螢幕擷取畫面顯示 TensorBoard 應用程式中 SageMaker AI 資料管理員索引標籤的完整檢視。

**注意**  
當您初次啟動 TensorBoard 應用程式時，視覺化外掛程式可能不會出現。在 SageMaker AI 資料管理員外掛程式中選取訓練任務之後，TensorBoard 應用程式會載入 TensorBoard 資料並生成視覺化外掛程式。

**注意**  
TensorBoard 應用程式會在閒置 1 小時後自動關閉。如果您想要在使用完應用程式後關閉應用程式，請務必手動關閉 TensorBoard，以避免因執行個體託管而產生費用。如需刪除應用程式的指示，請參閱[刪除未使用的 TensorBoard 應用程式](debugger-htb-delete-app.md)。

![\[SageMaker AI 資料管理員索引標籤檢視。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/htb-sagemaker-manager-tab.png)


在 **SageMaker AI 資料管理員**索引標籤中，您可以選取任何訓練任務，並從 Amazon S3 載入與 Tensorboard 相容的訓練輸出資料。

1. 在**搜尋訓練任務**區段中，使用篩選器縮小您要尋找、載入和視覺化的訓練任務清單。

1. 在**訓練任務清單**區段中，使用核取方塊來選擇您要從中擷取資料，並進行視覺化以偵錯的訓練任務。

1. 選擇**新增選取任務**。選取任務應顯示在**追蹤的訓練任務**區段中，如下列螢幕擷取畫面所示。  
![\[追蹤的訓練任務區段。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/htb-sagemaker-manager-tab-tracked-jobs.png)

**注意**  
**SageMaker AI 資料管理員**索引標籤僅顯示使用 `TensorBoardOutputConfig` 參數配置的訓練任務。請確定您已使用此參數設定 SageMaker AI 估算器。如需詳細資訊，請參閱[步驟 2：使用 TensorBoard 輸出組態建立 SageMaker 訓練估算器物件](debugger-htb-prepare-training-job.md#debugger-htb-prepare-training-job-2)。

**注意**  
如果您是第一次將 SageMaker AI 與 TensorBoard 搭配使用，或者沒有載入先前使用的資料，可能不會出現視覺化索引標籤。新增訓練任務並等待幾秒鐘後，請選擇右上角的順時針圓形箭頭來重新整理檢視器。成功載入任務資料後，視覺化索引標籤應該會出現。您也可以使用右上角重新整理按鈕旁的**設定**按鈕，設定為自動重新整理。

## TensorBoard 中的輸出張量視覺化
<a name="debugger-htb-explore"></a>

在圖形索引標籤中，您可以在左面板中看到已載入的訓練任務清單。您也可以使用訓練任務核取方塊來顯示或隱藏視覺化。TensorBoard 的動態外掛程式是根據您設定訓練腳本的方式，納入摘要寫入器和張量與純量收集的回調函式，藉此來動態啟動的，所以那些圖形索引標籤也會隨之動態地出現。下列螢幕擷取畫面顯示每個索引標籤的檢視範例，其中包含兩個訓練任務的視覺化方式，這些任務收集了時間序列、純量、圖形、分佈和長條圖外掛程式

**時間序列索引標籤檢視**

![\[時間序列索引標籤檢視。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/htb-time-series.png)


**純量索引標籤檢視**

![\[純量標籤檢視\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/htb-scalars.png)


**圖表索引標籤檢視**

![\[圖表索引標籤檢視。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/htb-graphs.png)


**分佈索引標籤檢視**

![\[分佈索引標籤檢視。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/htb-distribution.png)


**長條圖索引標籤檢視**

![\[長條圖索引標籤檢視。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/debugger/htb-histogram.png)


# 刪除未使用的 TensorBoard 應用程式
<a name="debugger-htb-delete-app"></a>

在 TensorBoard 中完成監控和試驗任務之後，請關閉 TensorBoard 應用程式。

1. 開啟 SageMaker AI 主控台。

1. 在左側導覽窗格中，選擇**管理員組態**。

1. 在**管理員組態**下，選擇**網域**。

1. 選擇您的網域。

1. 選擇您的使用者設定檔。

1. 在**應用程式**下，選擇**刪除應用程式**做為 TensorBoard 資料列

1. 選擇**是，刪除應用程式**。

1. 在文字方塊中輸入**delete**，然後選擇**刪除**。

1. 畫面頂端應會出現藍色訊息：**預設值正在刪除**。

# 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)。

# 透過 存取訓練容器 AWS Systems Manager 以進行遠端偵錯
<a name="train-remote-debugging"></a>

您可以透過 AWS Systems Manager (SSM) 安全地連線至 SageMaker 訓練容器。如此一來，您就可以存取 Shell 層級，以偵錯在容器內執行的訓練任務。您也可以記錄串流到 Amazon CloudWatch 的命令和回應。如果您使用自己的 Amazon Virtual Private Cloud (VPC) 來訓練模型，您可以使用 AWS PrivateLink 來設定 SSM 的 VPC 端點，並透過 SSM 私下連線至容器。

您可以連線至 [SageMaker AI 架構容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only)或連線至透過 SageMaker 訓練環境設定的自有訓練容器。

## 設定 IAM 許可
<a name="train-remote-debugging-iam"></a>

若要在 SageMaker 訓練容器中啟用 SSM，您需要為容器設定 IAM 角色。若要讓您或 AWS 帳戶中的使用者透過 SSM 存取訓練容器，您需要設定具有使用 SSM 許可的 IAM 使用者。

### IAM 角色
<a name="train-remote-debugging-iam-role"></a>

若要以 SSM 代理程式啟動 SageMaker 訓練容器，請提供具 SSM 許可的 IAM 角色。

若要為您的訓練任務啟用遠端偵錯，SageMaker AI 需要在訓練任務啟動時，於訓練容器中啟動 [SSM 代理程式](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html)。若要允許 SSM 代理程式與 SSM 服務溝通，請將下列政策新增至您用來執行訓練任務的 IAM 角色。

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

****  

```
{
    "Version":"2012-10-17",		 	 	             
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssmmessages:CreateControlChannel",
                "ssmmessages:CreateDataChannel",
                "ssmmessages:OpenControlChannel",
                "ssmmessages:OpenDataChannel"
            ],
            "Resource": "*"    
        }
    ]
 }
```

------

### IAM 使用者
<a name="train-remote-debugging-iam-user"></a>

新增下列政策以授予 IAM 使用者 SSM 工作階段連線至 SSM 目標的許可。在此情況下，SSM 目標為 SageMaker 訓練容器。

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

****  

```
{
    "Version":"2012-10-17",		 	 	             
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:StartSession",
                "ssm:TerminateSession"
            ],
            "Resource": "*"    
        }
    ]
}
```

------

 您可以新增 `Condition` 索引鍵來限制 IAM 使用者僅連線到特定訓練任務的容器，如下列政策範例所示。

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

****  

```
{
    "Version":"2012-10-17",		 	 	             
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:StartSession",
                "ssm:TerminateSession"
            ],
            "Resource": [
                "*"
            ],
            "Condition": {
                "StringLike": {
                    "ssm:resourceTag/aws:ssmmessages:target-id": [
                        "sagemaker-training-job:*"
                    ]
                }
            } 
        }
    ]
}
```

------

您也可以明確使用 `sagemaker:EnableRemoteDebug` 條件索引鍵來限制遠端偵錯。以下是 IAM 使用者限制遠端偵錯的範例政策。

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "DenyRemoteDebugInTrainingJob",
            "Effect": "Allow",
            "Action": [
                "sagemaker:CreateTrainingJob",
                "sagemaker:UpdateTrainingJob"
            ],
            "Resource": "*",
            "Condition": {
                "BoolIfExists": {
                    "sagemaker:EnableRemoteDebug": false
                }
            }
        }
    ]
}
```

------

如需更多資訊，請參閱 *AWS 服務授權參考*內的 [Amazon SageMaker AI 的條件索引鍵](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonsagemaker.html#amazonsagemaker-policy-keys)。

## 如何啟用 SageMaker 訓練任務的遠端偵錯
<a name="train-remote-debugging-how-to-use"></a>

在本節中了解如何在 Amazon SageMaker AI 中啟動或更新訓練任務時啟用遠端偵錯。

------
#### [ SageMaker Python SDK ]

您可以使用 SageMaker Python SDK 中的估算器類別，使用 `enable_remote_debug` 參數或 `enable_remote_debug()` 和 `disable_remote_debug()` 方法開啟或關閉遠端偵錯。

**建立訓練任務時啟用遠端偵錯**

若要在建立訓練任務時啟用遠端偵錯，請將 `enable_remote_debug` 參數設為 `True`。預設值為 `False`，因此，如果您完全未設定此參數或明確將其設為 `False`，則會停用遠端偵錯功能。

```
import sagemaker

session = sagemaker.Session()

estimator = sagemaker.estimator.Estimator(
    ...,
    sagemaker_session=session,
    image_uri="<your_image_uri>", #must be owned by your organization or Amazon DLCs 
    role=role,
    instance_type="ml.m5.xlarge",
    instance_count=1,
    output_path=output_path,
    max_run=1800,
    enable_remote_debug=True
)
```

**更新訓練任務以啟用遠端偵錯**

您可以使用下列估算器類別方法，在任務的 `SecondaryStatus` 為 `Downloading` 或 `Training` 時，於訓練任務執行時啟用或停用遠端偵錯。

```
# Enable RemoteDebug
estimator.enable_remote_debug()

# Disable RemoteDebug
estimator.disable_remote_debug()
```

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

**建立訓練任務時啟用遠端偵錯**

若要在建立訓練任務時啟用遠端偵錯，請在 `RemoteDebugConfig` 參數中將 `EnableRemoteDebug` 索引鍵的值設為 `True`。

```
import boto3

sm = boto3.Session(region_name=region).client("sagemaker")

# Start a training job
sm.create_training_job(
    ...,
    TrainingJobName=job_name,
    AlgorithmSpecification={
        // Specify a training Docker container image URI 
        // (Deep Learning Container or your own training container) to TrainingImage.
        "TrainingImage": "<your_image_uri>",
        "TrainingInputMode": "File"
    },
    RoleArn=iam_role_arn,
    OutputDataConfig=output_path,
    ResourceConfig={
        "InstanceType": "ml.m5.xlarge",
        "InstanceCount": 1,
        "VolumeSizeInGB": 30
    },
    StoppingCondition={
        "MaxRuntimeInSeconds": 86400
    },
    RemoteDebugConfig={
        "EnableRemoteDebug": True
    }
)
```

**更新訓練任務以啟用遠端偵錯**

您可以使用 `update_traing_job` API，在任務的 `SecondaryStatus` 為 `Downloading` 或 `Training` 時，於訓練任務執行時啟用或停用遠端偵錯。

```
# Update a training job
sm.update_training_job(
    TrainingJobName=job_name,
    RemoteDebugConfig={
        "EnableRemoteDebug": True     # True | False
    }
)
```

------
#### [ AWS Command Line Interface (CLI) ]

**建立訓練任務時啟用遠端偵錯**

準備 JSON 格式的 `CreateTrainingJob` 請求檔案，如下所示。

```
// train-with-remote-debug.json
{
    "TrainingJobName": job_name,
    "RoleArn": iam_role_arn,
    "AlgorithmSpecification": {
        // Specify a training Docker container image URI (Deep Learning Container or your own training container) to TrainingImage.
        "TrainingImage": "<your_image_uri>",
        "TrainingInputMode": "File"
    },
    "OutputDataConfig": {
        "S3OutputPath": output_path
    },
    "ResourceConfig": {
        "InstanceType": "ml.m5.xlarge",
        "InstanceCount": 1,
        "VolumeSizeInGB": 30
    },
    "StoppingCondition": {
        "MaxRuntimeInSeconds": 86400
    },
    "RemoteDebugConfig": {
        "EnableRemoteDebug": True
    }
}
```

儲存 JSON 檔案後，請在您提交訓練任務的終端機中執行下列命令。下列範例命令假設 JSON 檔案名為 `train-with-remote-debug.json`。如果您從 Jupyter 筆記本執行該命令，請將驚嘆號 (`!`) 新增至命令列的開頭。

```
aws sagemaker create-training-job \
    --cli-input-json file://train-with-remote-debug.json
```

**更新訓練任務以啟用遠端偵錯**

準備 JSON 格式的 `UpdateTrainingJob` 請求檔案，如下所示。

```
// update-training-job-with-remote-debug-config.json
{
    "TrainingJobName": job_name,
    "RemoteDebugConfig": {
        "EnableRemoteDebug": True
    }
}
```

儲存 JSON 檔案後，請在您提交訓練任務的終端機中執行下列命令。下列範例命令假設 JSON 檔案名為 `train-with-remote-debug.json`。如果您從 Jupyter 筆記本執行該命令，請將驚嘆號 (`!`) 新增至命令列的開頭。

```
aws sagemaker update-training-job \
    --cli-input-json file://update-training-job-with-remote-debug-config.json
```

------

## 存取您的訓練容器
<a name="train-remote-debugging-access-container"></a>

當相應訓練任務的 `SecondaryStatus` 為 `Training` 時，您就可以存取訓練容器。下列程式碼範例示範如何使用 `DescribeTrainingJob` API 檢查訓練任務的狀態、如何在 CloudWatch 中檢查訓練任務日誌，以及如何登入訓練容器。

**檢查訓練任務的狀態**

------
#### [ SageMaker Python SDK ]

若要檢查訓練任務的 `SecondaryStatus`，請執行下列 SageMaker Python SDK 程式碼。

```
import sagemaker

session = sagemaker.Session()

# Describe the job status
training_job_info = session.describe_training_job(job_name)
print(training_job_info)
```

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

若要檢查訓練任務的 `SecondaryStatus`，請執行下列 SDK for Python (Boto3) 程式碼。

```
import boto3

session = boto3.session.Session()
region = session.region_name
sm = boto3.Session(region_name=region).client("sagemaker")

# Describe the job status
sm.describe_training_job(TrainingJobName=job_name)
```

------
#### [ AWS Command Line Interface (CLI) ]

若要檢查訓練任務`SecondaryStatus`的 ，請針對 SageMaker AI 執行下列 AWS CLI 命令。

```
aws sagemaker describe-training-job \
    --training-job-name job_name
```

------

**尋找訓練容器的主機名稱**

若要透過 SSM 連線至訓練容器，請針對目標 ID 使用此格式：`sagemaker-training-job:<training-job-name>_algo-<n>`，其中 `algo-<n>` 是容器主機的名稱。如果您的任務在單一執行個體上執行，主機一律為 `algo-1`。如果您在多個執行個體上執行分散式訓練任務，SageMaker AI 會建立相同數量的主機和日誌串流。例如，如果您使用 4 個執行個體，SageMaker AI 會建立 `algo-1`、`algo-2`、`algo-3` 和 `algo-4`。您必須決定要偵錯哪個日誌串流及其主機號碼。若要存取與訓練任務相關的日誌串流，請執行下列動作。

1. 開啟位在 [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/) 的 Amazon SageMaker AI 主控台。

1. 在左側導覽窗格中，選擇**訓練**，然後選擇**訓練任務**。

1. 在**訓練任務**清單下，選擇您要偵錯的訓練任務。畫面即會顯示訓練任務詳細資訊頁面。

1. 在**監控**區段中，選擇**檢視日誌**。相關的訓練任務日誌串流清單會在 CloudWatch 主控台中開啟。

1. 日誌串流名稱會以 `<training-job-name>/algo-<n>-<time-stamp>` 格式顯示，其中 `algo-<n>` 代表主機名稱。

若要進一步了解 SageMaker AI 如何管理多執行個體分散式訓練的組態資訊，請參閱[分散式訓練組態](https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo-running-container.html#your-algorithms-training-algo-running-container-dist-training)。

**存取訓練容器**

請在終端機中使用下列命令來啟動 SSM 工作階段 (`[aws ssm start-session](https://docs.aws.amazon.com/cli/latest/reference/ssm/start-session.html)`) 並連線至訓練容器。

```
aws ssm start-session --target sagemaker-training-job:<training-job-name>_algo-<n>
```

例如，如果訓練任務名稱為 `training-job-test-remote-debug` 且主機名稱為 `algo-1`，則目標 ID 會變成 `sagemaker-training-job:training-job-test-remote-debug_algo-1`。如果此命令的輸出類似於 `Starting session with SessionId:xxxxx`，即表示連線成功。

### 使用 存取 SSM AWS PrivateLink
<a name="train-remote-debugging-access-container-vpc"></a>

如果您的訓練容器在未連線至公有網際網路的 Amazon Virtual Private Cloud 中執行，您可以使用 AWS PrivateLink 來啟用 SSM。 會將端點執行個體、SSM 和 Amazon EC2 之間的所有網路流量 AWS PrivateLink 限制在 Amazon 網路。如需如何使用 設定 SSM 存取的詳細資訊 AWS PrivateLink，請參閱[設定 Session Manager 的 Amazon VPC 端點](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-privatelink.html)。

## 記錄 SSM 工作階段命令和結果
<a name="train-remote-debugging-log-ssm"></a>

遵循[建立工作階段管理員偏好設定文件 (命令列)](https://docs.aws.amazon.com/systems-manager/latest/userguide/getting-started-create-preferences-cli.html) 的指示之後，您可以建立 SSM 文件來定義 SSM 工作階段的偏好設定。您可以使用 SSM 文件來設定工作階段選項，包括資料加密、工作階段持續時間和日誌記錄。例如，您可以指定在 Amazon Simple Storage Service (Amazon S3) 儲存貯體或 Amazon CloudWatch Logs 日誌群組中存放工作階段日誌資料的選項。您可以建立定義 AWS 帳戶所有工作階段一般偏好設定的文件 AWS 區域，以及定義個別工作階段偏好設定的文件。

## 從 SSM 檢查錯誤日誌，以對問題進行故障診斷
<a name="train-remote-debugging-checking-ssm-agent-logs"></a>

Amazon SageMaker AI 會從 SSM 代理程式將錯誤上傳至 `/aws/sagemaker/TrainingJobs` 日誌群組中的 CloudWatch Logs。SSM 代理程式日誌串流以下列格式命名：`<job-name>/algo-<n>-<timestamp>/ssm`。例如，如果您建立名為 `training-job-test-remote-debug` 的雙節點訓練任務，訓練任務日誌 `training-job-test-remote-debug/algo-<n>-<timestamp>` 和多個 SSM 代理程式錯誤日誌 `training-job-test-remote-debug/algo-<n>-<timestamp>/ssm` 會上傳至您的 CloudWatch Logs。在此範例中，您可以檢閱 `*/ssm` 日誌串流，以對 SSM 問題進行故障診斷。

```
training-job-test-remote-debug/algo-1-1680535238
training-job-test-remote-debug/algo-2-1680535238
training-job-test-remote-debug/algo-1-1680535238/ssm
training-job-test-remote-debug/algo-2-1680535238/ssm
```

## 考量事項
<a name="train-remote-debugging-considerations"></a>

使用 SageMaker AI 遠端偵錯時，請考慮下列事項。
+ [SageMaker AI 演算法容器](https://docs.aws.amazon.com/sagemaker/latest/dg/algorithms-choose.html)或 SageMaker AI 上的容器不支援遠端偵錯 AWS Marketplace。
+ 您無法為已啟用網路隔離的容器啟動 SSM 工作階段，因為隔離會防止傳出網路呼叫。

# Amazon SageMaker AI 偵錯功能的版本備註
<a name="debugger-release-notes"></a>

請參閱以下版本備註，以追蹤 Amazon SageMaker AI 偵錯功能的最新更新。

## 2023 年 12 月 21 日
<a name="debugger-release-notes-20231221"></a>

**新功能**

發佈遠端偵錯功能，這是 SageMaker AI 的新偵錯功能，可讓您擁有訓練容器的 Shell 存取權。在此版本中，您可以透過登入在 SageMaker AI ML 執行個體上執行的任務容器來偵錯訓練任務。如需詳細資訊，請參閱 [透過 存取訓練容器 AWS Systems Manager 以進行遠端偵錯](train-remote-debugging.md)。

## 2023 年 9 月 7 日
<a name="debugger-release-notes-20230907"></a>

**新功能**

新增了一個新的公用程式模組 `sagemaker.interactive_apps.tensorboard.TensorBoardApp`，它提供了稱為 `get_app_url()` 的函式。該 `get_app_url()` 函式會產生未簽署或預先簽章的 URL，以在 SageMaker AI 或 Amazon EC2 的任何環境中開啟 TensorBoard 應用程式。這是為了為 Studio Classic 和非 Studio Classic 使用者提供一致的體驗。對於 Studio Classic 環境，您可以透過依原樣執行 `get_app_url()` 函式來開啟 TensorBoard，也可以指定任務名稱，在 TensorBoard 應用程式開啟時開始追蹤。對於非 Studio Classic 環境，您可以透過將網域資訊提供給公用程式函式來開啟 TensorBoard。使用此功能，無論您在何處或以何種方式執行訓練程式碼及啟動訓練任務，都可以透過在您的 Jupyter 筆記本或終端機中執行 `get_app_url` 函式直接存取 TensorBoard。此功能可在 SageMaker Python SDK 2.184.0 及更新版本中使用。如需更多詳細資訊，請參閱 [在 SageMaker AI 上存取 TensorBoard 應用程式](debugger-htb-access-tb.md)。

## 2023 年 4 月 4 日
<a name="debugger-release-notes-20230404"></a>

**新功能**

現已發行具有 TensorBoard 的 SageMaker AI，此功能可在 SageMaker AI 上託管 TensorBoard。TensorBoard 可透過 SageMaker AI 網域作為應用程式，SageMaker AI 訓練平台則支援將 TensorBoard 資料集合輸出至 S3，並將其自動載入到 SageMaker AI 上託管 TensorBoard。透過此功能，您可以在 SageMaker AI 中執行使用 TensorBoard 摘要寫入器設定的訓練任務、將 TensorBoard 輸出檔案儲存於 Amazon S3、直接從 SageMaker AI 主控台開啟 TensorBoard 應用程式，並利用在託管 TensorBoard 介面上實施 SageMaker AI 資料管理員外掛程式載入輸出檔案。您不需要手動安裝 TensorBoard 並本機託管於 SageMaker AI IDE 或本機機器。如需詳細資訊，請參閱 [Amazon SageMaker AI 中的 TensorBoard](tensorboard-on-sagemaker.md)。

## 2023 年 3 月 16 日
<a name="debugger-release-notes-20230315"></a>

**棄用備註**

SageMaker Debugger 自 TensorFlow 2.11 和 PyTorch 2.0 起開始棄用架構分析功能。您仍可在舊版的架構和 SDK 中使用該功能，如下所示。
+ SageMaker Python SDK <= v2.130.0
+ PyTorch >= v1.6.0, < v2.0
+ TensorFlow >= 2.3.1 版，< 2.11 版

棄用的情況下，SageMaker Debugger 同樣會停止對下列三個用於架構分析的 `ProfilerRules` 的支援。
+ [MaxInitializationTime](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-built-in-rules.html#max-initialization-time)
+ [OverallFrameworkMetrics](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-built-in-rules.html#overall-framework-metrics)
+ [StepOutlier](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-built-in-rules.html#step-outlier)

## 2023 年 2 月 21 日
<a name="debugger-release-notes-20230221"></a>

**其他變更**
+ XgBoost 報告索引標籤已從 SageMaker Debugger 剖析工具儀表板中移除。您仍可以透過將其下載為 Jupyter 筆記本或 HTML 檔案來存取 XGBoost 報告。如需詳細資訊，請參閱 [SageMaker Debugger XGBoost 訓練報告](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-report-xgboost.html)。
+ 從此版本開始，預設為不會啟用內建剖析工具規則。若要使用 SageMaker Debugger 剖析工具規則來偵測特定運算問題，您需要在設定 SageMaker 訓練任務啟動器時新增規則。

## 2020 年 12 月 1 日
<a name="debugger-release-notes-20201201"></a>

Amazon SageMaker Debugger 於 re:Invent 2020 推出深度分析功能。

## 2019 年 12 月 3 日
<a name="debugger-release-notes-20191203"></a>

Amazon SageMaker Debugger 最初於 re:Invent 2019 推出。