

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

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