

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

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

Aturan bawaan Amazon SageMaker Debugger dapat dikonfigurasi untuk pekerjaan pelatihan menggunakan [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)fungsi klien AI AWS Boto3 SageMaker . Anda perlu menentukan URI gambar yang tepat dalam `RuleEvaluatorImage` parameter, dan contoh berikut memandu Anda melalui cara mengatur badan permintaan untuk [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)fungsi tersebut.

Kode berikut menunjukkan contoh lengkap tentang cara mengkonfigurasi Debugger untuk badan `create_training_job()` permintaan dan memulai pekerjaan pelatihan`us-west-2`, dengan asumsi bahwa skrip pelatihan `entry_point/train.py` disiapkan menggunakan. TensorFlow Untuk menemukan buku catatan contoh ujung ke ujung, lihat [Membuat Profil Job Pelatihan TensorFlow Multi GPU Multi Node dengan Amazon SageMaker Debugger](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node-boto3.html) (Boto3).

**catatan**  
Pastikan Anda menggunakan gambar kontainer Docker yang benar. Untuk menemukan gambar AWS Deep Learning Container yang [tersedia, lihat Gambar Deep Learning Containers](https://github.com/aws/deep-learning-containers/blob/master/available_images.md) yang Tersedia. Untuk menemukan daftar lengkap gambar Docker yang tersedia untuk menggunakan aturan Debugger, lihat. [Gambar Docker untuk aturan Debugger](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'}
        }
    ]
)
```

## Untuk mengonfigurasi aturan Debugger untuk parameter model debugging
<a name="debugger-built-in-rules-api-debug.Boto3"></a>

Contoh kode berikut menunjukkan cara mengonfigurasi `VanishingGradient` aturan bawaan menggunakan SageMaker API ini. 

**Untuk mengaktifkan Debugger mengumpulkan tensor keluaran**

Tentukan konfigurasi kait Debugger sebagai berikut:

```
DebugHookConfig={
    'S3OutputPath': '{{s3://<default-bucket>/<training-job-name>/debug-output}}',
    'CollectionConfigurations': [
        {
            'CollectionName': '{{gradients}}',
            'CollectionParameters' : {
                'train.save_interval': '{{500}}',
                'eval.save_interval': '{{50}}'
            }
        }
    ]
}
```

Ini akan membuat pekerjaan pelatihan menghemat koleksi tensor,`gradients`, setiap `save_interval` 500 langkah. Untuk menemukan `CollectionName` nilai yang tersedia, lihat [ Built-in Koleksi Debugger di dokumentasi pustaka](https://github.com/awslabs/sagemaker-debugger/blob/master/docs/api.md#built-in-collections) klien *SMDebug*. Untuk menemukan kunci dan nilai `CollectionParameters` parameter yang tersedia, lihat [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)kelas dalam dokumentasi *SageMaker Python SDK*.

**Untuk mengaktifkan aturan Debugger untuk men-debug tensor keluaran**

Contoh `DebugRuleConfigurations` API berikut menunjukkan cara menjalankan `VanishingGradient` aturan bawaan pada `gradients` koleksi yang disimpan.

```
DebugRuleConfigurations=[
    {
        'RuleConfigurationName': '{{VanishingGradient}}',
        'RuleEvaluatorImage': '{{895741380848.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rules:latest}}',
        'RuleParameters': {
            'rule_to_invoke': '{{VanishingGradient}}',
            'threshold': '{{20.0}}'
        }
    }
]
```

Dengan konfigurasi seperti yang ada dalam sampel ini, Debugger memulai pekerjaan evaluasi aturan untuk pekerjaan pelatihan Anda menggunakan `VanishingGradient` aturan pada kumpulan tensor. `gradients` Untuk menemukan daftar lengkap gambar Docker yang tersedia untuk menggunakan aturan Debugger, lihat. [Gambar Docker untuk aturan Debugger](debugger-reference.md#debugger-docker-images-rules) Untuk menemukan pasangan kunci-nilai untuk`RuleParameters`, lihat. [Daftar aturan bawaan Debugger](debugger-built-in-rules.md)

## Untuk mengonfigurasi aturan bawaan Debugger untuk sistem profil dan metrik kerangka kerja
<a name="debugger-built-in-rules-api-profile.Boto3"></a>

Contoh kode berikut menunjukkan cara menentukan operasi ProfilerConfig API untuk mengaktifkan metrik sistem dan kerangka kerja pengumpulan.

**Untuk mengaktifkan profiling Debugger untuk mengumpulkan metrik sistem dan kerangka kerja**

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

------

**Untuk mengaktifkan aturan Debugger untuk membuat profil metrik**

Kode contoh berikut menunjukkan cara mengkonfigurasi `ProfilerReport` aturan.

```
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}}'
        }
    }
]
```

Untuk menemukan daftar lengkap gambar Docker yang tersedia untuk menggunakan aturan Debugger, lihat. [Gambar Docker untuk aturan Debugger](debugger-reference.md#debugger-docker-images-rules) Untuk menemukan pasangan kunci-nilai untuk`RuleParameters`, lihat. [Daftar aturan bawaan Debugger](debugger-built-in-rules.md)

## Perbarui Konfigurasi Profil Debugger Menggunakan Operasi API `UpdateTrainingJob`
<a name="debugger-updatetrainingjob-api.Boto3"></a>

Konfigurasi profiling debugger dapat diperbarui saat pekerjaan pelatihan Anda berjalan dengan menggunakan [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)fungsi klien AI AWS SageMaker Boto3. Konfigurasikan baru [ProfilerConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerConfig.html)dan [ProfilerRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ProfilerRuleConfiguration.html)objek, dan tentukan nama pekerjaan pelatihan ke `TrainingJobName` parameter.

```
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}}'
```

## Tambahkan Konfigurasi Aturan Kustom Debugger ke Operasi API CreateTrainingJob
<a name="debugger-custom-rules-api.Boto3"></a>

Aturan khusus dapat dikonfigurasi untuk pekerjaan pelatihan menggunakan [ DebugRuleConfiguration](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugRuleConfiguration.html)objek [ DebugHookConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DebugHookConfig.html)dan menggunakan fungsi klien 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) Contoh kode berikut menunjukkan cara mengonfigurasi `ImproperActivation` aturan kustom yang ditulis dengan pustaka *smdebug* menggunakan operasi SageMaker API ini. Contoh ini mengasumsikan bahwa Anda telah menulis aturan kustom dalam file *custom\_rules.py* dan mengunggahnya ke bucket Amazon S3. Contoh ini menyediakan gambar Docker pra-bangun yang dapat Anda gunakan untuk menjalankan aturan kustom Anda. Ini terdaftar di[URI gambar Amazon SageMaker Debugger untuk evaluator aturan khusus](debugger-reference.md#debuger-custom-rule-registry-ids). Anda menentukan alamat registri URL untuk image Docker yang sudah dibuat sebelumnya dalam parameter. `RuleEvaluatorImage`

```
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}}'
        }
    }
]
```

Untuk menemukan daftar lengkap gambar Docker yang tersedia untuk menggunakan aturan Debugger, lihat. [Gambar Docker untuk aturan Debugger](debugger-reference.md#debugger-docker-images-rules) Untuk menemukan pasangan kunci-nilai untuk`RuleParameters`, lihat. [Daftar aturan bawaan Debugger](debugger-built-in-rules.md)