

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# SageMaker 훈련 컴파일러를 이용한 PyTorch 훈련 작업 실행
<a name="training-compiler-enable-pytorch"></a>

SageMaker AI 인터페이스를 사용하여 Amazon SageMaker Studio Classic AWS SDK for Python (Boto3), Amazon SageMaker 노트북 인스턴스 및 Amazon SageMaker 훈련 컴파일러로 훈련 작업을 실행할 수 있습니다 AWS Command Line Interface.

**Topics**
+ [

## SageMaker Python SDK 사용하기
](#training-compiler-enable-pytorch-pysdk)
+ [

## SageMaker AI `CreateTrainingJob` API 연산 사용
](#training-compiler-enable-pytorch-api)

## SageMaker Python SDK 사용하기
<a name="training-compiler-enable-pytorch-pysdk"></a>

PyTorch용 SageMaker Training Compiler는 SageMaker AI [https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html) 및 [https://sagemaker.readthedocs.io/en/stable/frameworks/huggingface/sagemaker.huggingface.html#hugging-face-estimator](https://sagemaker.readthedocs.io/en/stable/frameworks/huggingface/sagemaker.huggingface.html#hugging-face-estimator) 프레임워크 예측기 클래스로 사용할 수 있습니다. SageMaker Training Compiler를 켜려면 SageMaker AI 예측기에 `compiler_config` 파라미터를 추가하세요. `TrainingCompilerConfig` 클래스를 가져와서 이 클래스의 인스턴스를 `compiler_config` 매개변수에 전달합니다. 아래의 코드 예시는 SageMaker Training Compiler가 켜진 상태에서 SageMaker AI 예측기 클래스의 구조를 보여줍니다.

**작은 정보**  
PyTorch 또는 변환기에서 제공하는 사전 빌드 모델을 시작하려면 [테스트 완료 모델](training-compiler-support.md#training-compiler-tested-models)의 참조 표에 제시된 배치 크기를 사용해 보세요.

**참고**  
네이티브 PyTorch 지원은 SageMaker Python SDK v2.121.0 이상에서 이용 가능합니다. 이에 따라 SageMaker Python SDK를 업데이트해야 합니다.

**참고**  
PyTorch용 SageMaker Training Compiler 컨테이너는 PyTorch v1.12.0부터 사용 가능합니다. PyTorch용 SageMaker Training Compiler 컨테이너는 Hugging Face 변환기와 함께 사전 패키징되지 않습니다. 이 컨테이너에 라이브러리를 설치해야 하는 경우, 훈련 작업을 제출할 때 소스 디렉터리 하위에 `requirements.txt` 파일을 추가해야 합니다.  
PyTorch v1.11.0 이하 버전에서는 이전 버전의 Hugging Face 전용 및 PyTorch 전용 SageMaker Training Compiler 컨테이너를 사용하세요.  
프레임워크 버전의 전체 목록과 해당 컨테이너의 정보는 [지원되는 프레임워크](training-compiler-support.md#training-compiler-supported-frameworks)을(를) 참조하세요.

사용 사례에 맞는 내용은 다음 옵션 중 하나를 참조하세요.

### 단일 GPU 훈련용
<a name="training-compiler-estimator-pytorch-single"></a>

------
#### [ PyTorch v1.12.0 and later ]

PyTorch 모델을 컴파일하고 훈련시키려면 다음 코드 예시와 같이 SageMaker Training Compiler로 SageMaker AI PyTorch 예측기를 구성하세요.

**참고**  
이 네이티브 PyTorch 지원은 SageMaker AI Python SDK v2.120.0 이상에서 사용 가능합니다. SageMaker AI Python SDK를 업데이트해야 합니다.

```
from sagemaker.pytorch import PyTorch, TrainingCompilerConfig

# the original max batch size that can fit into GPU memory without compiler
batch_size_native=12
learning_rate_native=float('5e-5')

# an updated max batch size that can fit into GPU memory with compiler
batch_size=64

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size

hyperparameters={
    "n_gpus": 1,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

pytorch_estimator=PyTorch(
    entry_point='train.py',
    source_dir='path-to-requirements-file', # Optional. Add this if need to install additional packages.
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    framework_version='1.13.1',
    py_version='py3',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_estimator.fit()
```

------
#### [ Hugging Face Transformers with PyTorch v1.11.0 and before ]

PyTorch로 트랜스포머 모델을 컴파일하고 훈련시키려면 다음 코드 예시와 같이 SageMaker Training Compiler로 SageMaker AI Hugging Face 예측기를 구성하세요.

```
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig

# the original max batch size that can fit into GPU memory without compiler
batch_size_native=12
learning_rate_native=float('5e-5')

# an updated max batch size that can fit into GPU memory with compiler
batch_size=64

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size

hyperparameters={
    "n_gpus": 1,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

pytorch_huggingface_estimator=HuggingFace(
    entry_point='train.py',
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    transformers_version='4.21.1',
    pytorch_version='1.11.0',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_huggingface_estimator.fit()
```

훈련 스크립트를 준비하려면 다음 페이지를 참조하세요.
+ Hugging Face Transformers의 [트레이너 API](https://huggingface.co/docs/transformers/main_classes/trainer)를 이용한 PyTorch 모델의 [단일 GPU 훈련의 경우](training-compiler-pytorch-models.md#training-compiler-pytorch-models-transformers-trainer-single-gpu)
+ Hugging Face Transformers의 [트레이너 API](https://huggingface.co/transformers/main_classes/trainer.html)가 없는 PyTorch 모델의 [단일 GPU 훈련의 경우](training-compiler-pytorch-models.md#training-compiler-pytorch-models-non-trainer-single-gpu)

예제 전체를 확인하려면 다음 노트북을 참조하세요.
+ [SQuAD 데이터세트를 이용한 질문 및 답변용 Hugging Face Transformers 트레이너 모델 컴파일 및 훈련 ](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_single_gpu_single_node/albert-base-v2/albert-base-v2.html) 
+ [SageMaker Training Compiler를 사용하는 SST 데이터세트를 이용한 Hugging Face Transformer `BERT` 모델 컴파일 및 훈련](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_single_gpu_single_node/bert-base-cased/bert-base-cased-single-node-single-gpu.html) 
+ [단일 노드 단일 GPU 훈련용 SST2 데이터세트를 이용한 바이너리 분류 트레이너 모델 컴파일 및 훈련 ](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_single_gpu_single_node/roberta-base/roberta-base.html)

------

### 분산형 훈련용
<a name="training-compiler-estimator-pytorch-distributed"></a>

------
#### [ PyTorch v1.12 ]

PyTorch v1.12에서는 SageMaker AI PyTorch 예측기 클래스의 `distribution` 파라미터에 지정된 `pytorch_xla` 옵션을 추가하여 SageMaker Training Compiler로 분산 훈련을 실행할 수 있습니다.

**참고**  
이 네이티브 PyTorch 지원은 SageMaker AI Python SDK v2.121.0 이상에서 사용 가능합니다. SageMaker AI Python SDK를 업데이트해야 합니다.

```
from sagemaker.pytorch import PyTorch, TrainingCompilerConfig

# choose an instance type, specify the number of instances you want to use,
# and set the num_gpus variable the number of GPUs per instance.
instance_count=1
instance_type='ml.p3.8xlarge'
num_gpus=4

# the original max batch size that can fit to GPU memory without compiler
batch_size_native=16
learning_rate_native=float('5e-5')

# an updated max batch size that can fit to GPU memory with compiler
batch_size=26

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size*num_gpus*instance_count

hyperparameters={
    "n_gpus": num_gpus,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

pytorch_estimator=PyTorch(
    entry_point='your_training_script.py',
    source_dir='path-to-requirements-file', # Optional. Add this if need to install additional packages.
    instance_count=instance_count,
    instance_type=instance_type,
    framework_version='1.13.1',
    py_version='py3',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    distribution ={'pytorchxla' : { 'enabled': True }},
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_estimator.fit()
```

**작은 정보**  
훈련 스크립트를 준비하려면 [PyTorch](training-compiler-pytorch-models.md)을(를) 참조하세요.

------
#### [ Transformers v4.21 with PyTorch v1.11 ]

PyTorch v1.11 이상에서는 `distribution` 파라미터에 지정된 `pytorch_xla` 옵션으로 SageMaker Training Compiler를 분산 훈련에 사용할 수 있습니다.

```
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig

# choose an instance type, specify the number of instances you want to use,
# and set the num_gpus variable the number of GPUs per instance.
instance_count=1
instance_type='ml.p3.8xlarge'
num_gpus=4

# the original max batch size that can fit to GPU memory without compiler
batch_size_native=16
learning_rate_native=float('5e-5')

# an updated max batch size that can fit to GPU memory with compiler
batch_size=26

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size*num_gpus*instance_count

hyperparameters={
    "n_gpus": num_gpus,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

pytorch_huggingface_estimator=HuggingFace(
    entry_point='your_training_script.py',
    instance_count=instance_count,
    instance_type=instance_type,
    transformers_version='4.21.1',
    pytorch_version='1.11.0',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    distribution ={'pytorchxla' : { 'enabled': True }},
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_huggingface_estimator.fit()
```

**작은 정보**  
훈련 스크립트를 준비하려면 다음 페이지를 참조하세요.  
Hugging Face Transformers의 [트레이너 API](https://huggingface.co/transformers/main_classes/trainer.html)를 이용한 PyTorch 모델의 [분산 훈련의 경우](training-compiler-pytorch-models.md#training-compiler-pytorch-models-transformers-trainer-distributed)
Hugging Face Transformers의 [트레이너 API](https://huggingface.co/transformers/main_classes/trainer.html)가 없는 PyTorch 모델의 [분산 훈련의 경우](training-compiler-pytorch-models.md#training-compiler-pytorch-models-non-trainer-distributed)

------
#### [ Transformers v4.17 with PyTorch v1.10.2 and before ]

지원되는 PyTorch v1.10.2 이하 버전의 경우, SageMaker Training Compiler에는 분산 훈련 작업을 시작하기 위한 대체 메커니즘이 필요합니다. 분산 훈련을 실행하려면 SageMaker Training Compiler로 SageMaker AI 분산 훈련 런처 스크립트를 `entry_point` 인수에 전달하고, 훈련 스크립트를 `hyperparameters` 인수에 전달해야 합니다. 다음 코드 예시는 필수 변경 사항을 적용하여 SageMaker AI Hugging Face 예측기를 구성하는 방법을 보여줍니다.

```
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig

# choose an instance type, specify the number of instances you want to use,
# and set the num_gpus variable the number of GPUs per instance.
instance_count=1
instance_type='ml.p3.8xlarge'
num_gpus=4

# the original max batch size that can fit to GPU memory without compiler
batch_size_native=16
learning_rate_native=float('5e-5')

# an updated max batch size that can fit to GPU memory with compiler
batch_size=26

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size*num_gpus*instance_count

training_script="your_training_script.py"

hyperparameters={
    "n_gpus": num_gpus,
    "batch_size": batch_size,
    "learning_rate": learning_rate,
    "training_script": training_script     # Specify the file name of your training script.
}

pytorch_huggingface_estimator=HuggingFace(
    entry_point='distributed_training_launcher.py',    # Specify the distributed training launcher script.
    instance_count=instance_count,
    instance_type=instance_type,
    transformers_version='4.17.0',
    pytorch_version='1.10.2',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_huggingface_estimator.fit()
```

런처 스크립트는 다음과 같아야 합니다. 이 스크립트에서는 훈련 스크립트를 래핑하고, 선택된 훈련 인스턴스의 크기에 따라 분산 훈련 환경을 구성합니다.

```
# distributed_training_launcher.py

#!/bin/python

import subprocess
import sys

if __name__ == "__main__":
    arguments_command = " ".join([arg for arg in sys.argv[1:]])
    """
    The following line takes care of setting up an inter-node communication
    as well as managing intra-node workers for each GPU.
    """
    subprocess.check_call("python -m torch_xla.distributed.sm_dist " + arguments_command, shell=True)
```

**작은 정보**  
훈련 스크립트를 준비하려면 다음 페이지를 참조하세요.  
Hugging Face Transformers의 [트레이너 API](https://huggingface.co/transformers/main_classes/trainer.html)를 이용한 PyTorch 모델의 [분산 훈련의 경우](training-compiler-pytorch-models.md#training-compiler-pytorch-models-transformers-trainer-distributed)
Hugging Face Transformers의 [트레이너 API](https://huggingface.co/transformers/main_classes/trainer.html)가 없는 PyTorch 모델의 [분산 훈련의 경우](training-compiler-pytorch-models.md#training-compiler-pytorch-models-non-trainer-distributed)

**작은 정보**  
예제 전체를 확인하려면 다음 노트북을 참조하세요.  
[단일 노드 다중 GPU 훈련용 SST2 데이터 세트로 Transformers 트레이너 API를 이용한 GPT2 모델 컴파일 및 훈련](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling-multi-gpu-single-node.html)
[다중 노드 다중 GPU 훈련용 SST2 데이터 세트로 Transformers 트레이너 API를 이용한 GPT2 모델 컴파일 및 훈련](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_multiple_node/language-modeling-multi-gpu-multi-node.html)

------

다음 목록은 컴파일러로 SageMaker 훈련 작업을 실행하는 데 필요한 파라미터의 최소 세트입니다.

**참고**  
SageMaker AI Hugging Face 예측기를 사용할 때는 `transformers_version`, `pytorch_version`, `hyperparameters` 및 `compiler_config` 파라미터를 지정하여 SageMaker Training Compiler를 활성화해야 합니다. `image_uri`은(는) [지원되는 프레임워크](training-compiler-support.md#training-compiler-supported-frameworks)에 나열된 Training Compiler 통합 딥 러닝 컨테이너를 수동으로 지정하는 데 사용할 수 없습니다.
+ `entry_point`(str) - 필수 사항. 훈련 스크립트의 파일 이름을 지정하세요.
**참고**  
SageMaker Training Compiler와 PyTorch v1.10.2 이하 버전을 사용하여 분산 훈련을 실행하려면 런처 스크립트의 파일 이름을 이 파라미터에 지정하세요. 훈련 스크립트를 래핑하고 분산 훈련 환경을 구성할 수 있도록 런처 스크립트를 준비해야 합니다. 자세한 내용은 다음 예제 노트북을 참조하세요.  
[단일 노드 다중 GPU 훈련용 SST2 데이터세트로 Transformers 트레이너 API를 이용한 GPT2 모델 컴파일 및 훈련](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling-multi-gpu-single-node.html)
[다중 노드 다중 GPU 훈련용 SST2 데이터세트로 Transformers 트레이너 API를 이용한 GPT2 모델 컴파일 및 훈련](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_multiple_node/language-modeling-multi-gpu-multi-node.html)
+ `source_dir`(str) - 선택 사항. 추가 패키지를 설치해야 하는 경우에 추가하세요. 패키지를 설치하려면 이 디렉터리 하위에 `requirements.txt` 파일을 준비해야 합니다.
+ `instance_count`(int) - 필수 사항. 인스턴스 수를 지정하세요.
+ `instance_type`(str) - 필수 사항. 인스턴스 유형을 지정하세요.
+ `transformers_version`(str) - SageMaker AI Hugging Face 예측기를 사용할 때만 필요합니다. SageMaker Training Compiler가 지원하는 Hugging Face Transformers 라이브러리 버전을 지정하세요. 사용 가능한 버전을 확인하려면 [지원되는 프레임워크](training-compiler-support.md#training-compiler-supported-frameworks)을(를) 참조하세요.
+ `framework_version` 또는 `pytorch_version`(str) - 필수 사항. SageMaker Training Compiler가 지원하는 PyTorch 버전을 지정하세요. 사용 가능한 버전을 확인하려면 [지원되는 프레임워크](training-compiler-support.md#training-compiler-supported-frameworks)을(를) 참조하세요.
**참고**  
SageMaker AI Hugging Face 예측기를 사용할 때는 `transformers_version` 및 `pytorch_version`을 둘 다 지정해야 합니다.
+ `hyperparameters`(dict) - 선택 사항. 훈련 작업에 사용할 하이퍼파라미터(예: `n_gpus`, `batch_size`, `learning_rate`)를 지정하세요. SageMaker Training Compiler를 활성화할 경우, 배치 크기를 늘려 보고 그에 따라 학습률을 조정하세요. 컴파일러를 사용하고 배치 크기를 조정하여 훈련 속도를 향상시킨 사례 연구를 확인하려면 [테스트 완료 모델](training-compiler-support.md#training-compiler-tested-models) 및 [SageMaker 훈련 컴파일러 예제 노트북 및 블로그](training-compiler-examples-and-blogs.md)을(를) 참조하세요.
**참고**  
SageMaker Training Compiler와 PyTorch v1.10.2 이하 버전을 사용하여 분산 훈련을 실행하려면 이전 코드 예제와 같이 추가 파라미터인 `"training_script"`을(를) 추가하여 훈련 스크립트를 지정해야 합니다.
+ `compiler_config`(TrainingCompilerConfig 객체) - SageMaker Training Compiler를 활성화하는 데 필요합니다. SageMaker Training Compiler를 켜려면 이 파라미터를 포함시키세요. 다음은 `TrainingCompilerConfig` 클래스의 파라미터입니다.
  + `enabled`(bool) - 선택 사항. SageMaker Training Compiler를 켜거나 끄려면 `True` 또는 `False`을(를) 지정하세요. 기본값은 `True`입니다.
  + `debug`(bool) - 선택 사항. 컴파일러 가속 훈련 작업의 자세한 훈련 로그를 수신하려면 이 파라미터를 `True`(으)로 변경하세요. 다만 추가 로깅으로 인해 오버헤드가 추가되어 컴파일된 훈련 작업이 느려질 수 있습니다. 기본값은 `False`입니다.
+ `distribution`(dict) - 선택 사항. SageMaker Training Compiler로 분산 훈련 작업을 실행하려면 `distribution = { 'pytorchxla' : { 'enabled': True }}`을(를) 추가하세요.

**주의**  
SageMaker Debugger를 켜면 SageMaker Training Compiler의 성능에 영향을 미칠 수 있습니다. SageMaker Training Compiler를 실행할 때는 그 성능에 영향을 미치지 않도록 Debugger를 끄는 것이 좋습니다. 자세한 내용은 [고려 사항](training-compiler-tips-pitfalls.md#training-compiler-tips-pitfalls-considerations)을 참조하세요. Debugger 기능을 끄려면 다음 2가지 인수를 예측기에 추가하세요.  

```
disable_profiler=True,
debugger_hook_config=False
```

컴파일러를 이용한 훈련 작업이 시작되면 작업 초기화 단계에서 다음과 같은 로그를 받게 됩니다.
+ `TrainingCompilerConfig(debug=False)` 포함

  ```
  Found configuration for Training Compiler
  Configuring SM Training Compiler...
  ```
+ `TrainingCompilerConfig(debug=True)` 포함

  ```
  Found configuration for Training Compiler
  Configuring SM Training Compiler...
  Training Compiler set to debug mode
  ```

## SageMaker AI `CreateTrainingJob` API 연산 사용
<a name="training-compiler-enable-pytorch-api"></a>

SageMaker 훈련 컴파일러 구성 옵션은 [`CreateTrainingJob` API 작업](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)에 대해 요청 구문의 `AlgorithmSpecification` 및 `HyperParameters` 필드를 통해 지정해야 합니다.

```
"AlgorithmSpecification": {
    "TrainingImage": "<sagemaker-training-compiler-enabled-dlc-image>"
},

"HyperParameters": {
    "sagemaker_training_compiler_enabled": "true",
    "sagemaker_training_compiler_debug_mode": "false",
    "sagemaker_pytorch_xla_multi_worker_enabled": "false"    // set to "true" for distributed training
}
```

SageMaker Training Compiler가 구현된 딥 러닝 컨테이너 이미지 URI의 전체 목록을 확인하려면 [지원되는 프레임워크](training-compiler-support.md#training-compiler-supported-frameworks)을(를) 참조하세요.