

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

# 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\_rules.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)。