

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

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