

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

# Neo를 사용한 모델 컴파일
<a name="neo-job-compilation"></a>

이 섹션에서는 컴파일 작업을 생성, 설명 및 중지하고 목록을 생성하는 방법을 보여줍니다. 기계 학습 모델의 컴파일 작업을 관리하기 위해 Amazon SageMaker Neo에서 사용할 수 있는 옵션은 AWS Command Line Interface, Amazon SageMaker AI 콘솔 또는 Amazon SageMaker SDK입니다.

**Topics**
+ [컴파일용 ML 모델 준비](neo-compilation-preparing-model.md)
+ [모델 컴파일(AWS Command Line Interface)](neo-job-compilation-cli.md)
+ [모델 컴파일(Amazon SageMaker AI 콘솔)](neo-job-compilation-console.md)
+ [모델 컴파일(Amazon SageMaker AI SDK)](neo-job-compilation-sagemaker-sdk.md)

# 컴파일용 ML 모델 준비
<a name="neo-compilation-preparing-model"></a>

SageMaker Neo에는 특정 입력 데이터 형태를 충족하는 기계 학습 모델이 필요합니다. 컴파일에 필요한 입력 형태는 사용하는 딥러닝 프레임워크에 따라 달라집니다. 모델 입력 형태의 형식이 올바르게 지정되면 아래 요구 사항에 따라 모델을 저장합니다. 모델을 저장한 후에는 모델 아티팩트를 압축하세요.

**Topics**
+ [SageMaker Neo에 필요한 입력 데이터 형태는 무엇입니까?](#neo-job-compilation-expected-inputs)
+ [SageMaker Neo에 대한 모델 저장](#neo-job-compilation-how-to-save-model)

## SageMaker Neo에 필요한 입력 데이터 형태는 무엇입니까?
<a name="neo-job-compilation-expected-inputs"></a>

모델을 컴파일하기 전에 모델 형식이 올바른지 확인하세요. Neo에는 훈련된 모델에 필요한 데이터 입력의 이름 및 형태가 JSON 형식 또는 목록 형식으로 필요합니다. 필요한 입력은 프레임워크에 따라 다릅니다.

SageMaker Neo에 필요한 입력 형태는 다음과 같습니다.

### Keras
<a name="collapsible-section-1"></a>

훈련된 모델의 딕셔너리 형식을 사용하여 필요한 데이터 입력의 이름 및 형태(NCHW 형식)를 지정해야 합니다. Keras 모델 아티팩트는 NHWC(채널-마지막) 형식으로 업로드해야 하지만 DataInputConfig는 NCHW(채널-우선) 형식으로 지정해야 합니다. 필요한 딕셔너리 형식은 다음과 같습니다.
+ 하나의 입력인 경우: `{'input_1':[1,3,224,224]}`
+ 두개의 입력인 경우: `{'input_1': [1,3,224,224], 'input_2':[1,3,224,224]}`

### MXNet/ONNX
<a name="collapsible-section-2"></a>

훈련된 모델의 딕셔너리 형식을 사용하여 필요한 데이터 입력의 이름 및 형태(NCHW 형식)를 지정해야 합니다. 필요한 딕셔너리 형식은 다음과 같습니다.
+ 하나의 입력인 경우: `{'data':[1,3,1024,1024]}`
+ 두개의 입력인 경우: `{'var1': [1,1,28,28], 'var2':[1,1,28,28]}`

### PyTorch
<a name="collapsible-section-3"></a>

PyTorch 모델의 경우 다음 조건을 모두 충족하는 경우 필요한 데이터 입력의 이름과 형태를 제공할 필요가 없습니다.
+ PyTorch 2.0 이상을 사용하여 모델 정의 파일을 생성했습니다. 정의 파일을 생성하는 방법에 대한 자세한 내용은 *SageMaker Neo에 모델 저장* 아래의 [PyTorch](#how-to-save-pytorch) 섹션을 참조하세요.
+ 클라우드 인스턴스용 모델을 컴파일하고 있습니다. SageMaker Neo가 지원하는 인스턴스 유형에 대한 자세한 내용은 [지원되는 인스턴스 유형 및 프레임워크](neo-supported-cloud.md) 섹션을 참조하세요.

이러한 조건을 충족하는 경우 SageMaker Neo는 PyTorch로 생성하는 모델 정의 파일(.pt 또는.pth)에서 입력 구성을 가져옵니다.

그 밖에는 다음과 같은 방법이 있습니다.

훈련된 모델의 딕셔너리 형식을 사용하여 필요한 데이터 입력의 이름 및 형태(NCHW 형식)를 지정해야 합니다. 또는 목록 형식만 사용하여 형태를 지정할 수도 있습니다. 필요한 딕셔너리 형식은 다음과 같습니다.
+ 딕셔너리 형식으로 하나의 입력인 경우: `{'input0':[1,3,224,224]}`
+ 목록 형식으로 하나의 입력인 경우: `[[1,3,224,224]]`
+ 딕셔너리 형식으로 두 개의 입력인 경우: `{'input0':[1,3,224,224], 'input1':[1,3,224,224]}`
+ 목록 형식으로 두 개의 입력인 경우: `[[1,3,224,224], [1,3,224,224]]`

### TensorFlow
<a name="collapsible-section-4"></a>

훈련된 모델의 딕셔너리 형식을 사용하여 필요한 데이터 입력의 이름 및 셰이프(NHWC 형식)를 지정하세요. 필요한 딕셔너리 형식은 다음과 같습니다.
+ 하나의 입력인 경우: `{'input':[1,1024,1024,3]}`
+ 두개의 입력인 경우: `{'data1': [1,28,28,1], 'data2':[1,28,28,1]}`

### TFLite
<a name="collapsible-section-5"></a>

훈련된 모델의 딕셔너리 형식을 사용하여 필요한 데이터 입력의 이름 및 셰이프(NHWC 형식)를 지정하세요. 필요한 딕셔너리 형식은 다음과 같습니다.
+ 하나의 입력인 경우: `{'input':[1,224,224,3]}`

**참고**  
SageMaker Neo는 엣지 디바이스 대상용 TensorFlow Lite 만 지원합니다. 지원되는 SageMaker Neo 엣지 디바이스 대상 목록은 SageMaker Neo [Devices](neo-supported-devices-edge-devices.md#neo-supported-edge-devices) 페이지를 참조하세요. 지원되는 SageMaker Neo 클라우드 인스턴스 대상 목록은 SageMaker Neo [지원되는 인스턴스 유형 및 프레임워크](neo-supported-cloud.md) 페이지를 참조하세요.

### XGBoost
<a name="collapsible-section-6"></a>

입력 데이터 이름 및 형태는 필요하지 않습니다.

## SageMaker Neo에 대한 모델 저장
<a name="neo-job-compilation-how-to-save-model"></a>

다음 코드 예제는 Neo와 호환되도록 모델을 저장하는 방법을 보여줍니다. 모델은 압축된 tar 파일(`*.tar.gz`)로 패키징해야 합니다.

### Keras
<a name="how-to-save-tf-keras"></a>

Keras 모델에는 하나의 모델 정의 파일(`.h5`)이 필요합니다.

SageMaker Neo와 호환되도록 Keras 모델을 저장하는 데는 두 가지 옵션이 있습니다.

1. `model.save("<model-name>", save_format="h5")`를 사용하여 `.h5` 형식으로 내보냅니다.

1. 내보낸 후 `SavedModel`을 고정합니다.

다음은 `tf.keras` 모델을 고정 그래프로 내보내는 방법의 예입니다(옵션 2).

```
import os
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras import backend

tf.keras.backend.set_learning_phase(0)
model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3), pooling='avg')
model.summary()

# Save as a SavedModel
export_dir = 'saved_model/'
model.save(export_dir, save_format='tf')

# Freeze saved model
input_node_names = [inp.name.split(":")[0] for inp in model.inputs]
output_node_names = [output.name.split(":")[0] for output in model.outputs]
print("Input names: ", input_node_names)
with tf.Session() as sess:
    loaded = tf.saved_model.load(sess, export_dir=export_dir, tags=["serve"]) 
    frozen_graph = tf.graph_util.convert_variables_to_constants(sess,
                                                                sess.graph.as_graph_def(),
                                                                output_node_names)
    tf.io.write_graph(graph_or_graph_def=frozen_graph, logdir=".", name="frozen_graph.pb", as_text=False)

import tarfile
tar = tarfile.open("frozen_graph.tar.gz", "w:gz")
tar.add("frozen_graph.pb")
tar.close()
```

**주의**  
`model.save(<path>, save_format='tf')`를 사용하여 `SavedModel` 클래스와 함께 모델을 내보내지 마세요. 이 형식은 훈련에는 적합하지만 추론에는 적합하지 않습니다.

### MXNet
<a name="how-to-save-mxnet"></a>

MXNet 모델은 단일 기호 파일 `*-symbol.json` 및 단일 파라미터 `*.params files`로 저장해야 합니다.

------
#### [ Gluon Models ]

`HybridSequential` 클래스를 사용하여 신경망을 정의합니다. 그러면 명령형 프로그래밍이 아닌 기호 프로그래밍 스타일로 코드가 실행됩니다.

```
from mxnet import nd, sym
from mxnet.gluon import nn

def get_net():
    net = nn.HybridSequential()  # Here we use the class HybridSequential.
    net.add(nn.Dense(256, activation='relu'),
            nn.Dense(128, activation='relu'),
            nn.Dense(2))
    net.initialize()
    return net

# Define an input to compute a forward calculation. 
x = nd.random.normal(shape=(1, 512))
net = get_net()

# During the forward calculation, the neural network will automatically infer
# the shape of the weight parameters of all the layers based on the shape of
# the input.
net(x)
                        
# hybridize model
net.hybridize()
net(x)

# export model
net.export('<model_name>') # this will create model-symbol.json and model-0000.params files

import tarfile
tar = tarfile.open("<model_name>.tar.gz", "w:gz")
for name in ["<model_name>-0000.params", "<model_name>-symbol.json"]:
    tar.add(name)
tar.close()
```

하이브리드 모델에 대한 자세한 내용은 [MXNet 하이브리드 설명서](https://mxnet.apache.org/versions/1.7.0/api/python/docs/tutorials/packages/gluon/blocks/hybridize.html)를 참조하세요.

------
#### [ Gluon Model Zoo (GluonCV) ]

GluonCV 모델 동물원 모델은 사전 하이브리드된 상태로 제공됩니다. 따라서 그냥 내보내기만 하면 됩니다.

```
import numpy as np
import mxnet as mx
import gluoncv as gcv
from gluoncv.utils import export_block
import tarfile

net = gcv.model_zoo.get_model('<model_name>', pretrained=True) # For example, choose <model_name> as resnet18_v1
export_block('<model_name>', net, preprocess=True, layout='HWC')

tar = tarfile.open("<model_name>.tar.gz", "w:gz")

for name in ["<model_name>-0000.params", "<model_name>-symbol.json"]:
    tar.add(name)
tar.close()
```

------
#### [ Non Gluon Models ]

모든 GLUON이 아닌 모델을 디스크 사용 `*-symbol` 및 `*.params` 파일에 저장한 경우. 따라서 이미 Neo를 위한 올바른 형식으로 되어 있습니다.

```
# Pass the following 3 parameters: sym, args, aux
mx.model.save_checkpoint('<model_name>',0,sym,args,aux) # this will create <model_name>-symbol.json and <model_name>-0000.params files

import tarfile
tar = tarfile.open("<model_name>.tar.gz", "w:gz")

for name in ["<model_name>-0000.params", "<model_name>-symbol.json"]:
    tar.add(name)
tar.close()
```

------

### PyTorch
<a name="how-to-save-pytorch"></a>

PyTorch 모델은 입력 데이터 유형이 `float32`인 정의 파일(`.pt` 또는 `.pth`)로 저장해야 합니다.

모델을 저장하려면 `torch.jit.trace` 메서드와 `torch.save` 메서드를 차례로 사용하세요. 이 프로세스는 객체를 디스크 파일에 저장하고 기본적으로 python pickle(`pickle_module=pickle`)을 사용하여 객체와 일부 메타데이터를 저장합니다. 다음으로, 저장된 모델을 압축된 tar 파일로 변환합니다.

```
import torchvision
import torch

model = torchvision.models.resnet18(pretrained=True)
model.eval()
inp = torch.rand(1, 3, 224, 224)
model_trace = torch.jit.trace(model, inp)

# Save your model. The following code saves it with the .pth file extension
model_trace.save('model.pth')

# Save as a compressed tar file
import tarfile
with tarfile.open('model.tar.gz', 'w:gz') as f:
    f.add('model.pth')
f.close()
```

PyTorch 2.0 이상을 사용하여 모델을 저장하는 경우 SageMaker Neo는 정의 파일에서 모델의 입력 구성(입력의 이름 및 형태)을 얻습니다. 이 경우 모델을 컴파일할 때 SageMaker AI에 데이터 입력 구성을 지정하지 않아도 됩니다.

SageMaker Neo가 입력 구성을 얻지 못하도록 하려면 `torch.jit.trace`의 `_store_inputs` 파라미터를 `False`로 설정하면 됩니다. 이렇게 하면 모델을 컴파일할 때 SageMaker AI에 데이터 입력 구성을 지정해야 합니다.

`torch.jit.trace` 메서드에 대한 자세한 내용은 PyTorch 설명서의 [TORCH.JIT.TRACE](https://pytorch.org/docs/stable/generated/torch.jit.trace.html#torch.jit.trace)를 참조하세요.

### TensorFlow
<a name="how-to-save-tf"></a>

TensorFlow에는 `.pb` 하나 또는 `.pbtxt` 하나의 파일과 변수가 포함된 변수 디렉터리가 필요합니다. 고정된 모델의 경우 하나의 `.pb` 또는 `.pbtxt` 파일만 필요합니다.

다음 코드 예제는 tar Linux 명령을 사용하여 모델을 압축하는 방법을 보여줍니다. 터미널이나 Jupyter notebook에서 다음을 실행합니다(Jupyter notebook을 사용하는 경우 명령문 앞에 `!` magic 명령을 삽입하세요).

```
# Download SSD_Mobilenet trained model
!wget http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v2_coco_2018_03_29.tar.gz

# unzip the compressed tar file
!tar xvf ssd_mobilenet_v2_coco_2018_03_29.tar.gz

# Compress the tar file and save it in a directory called 'model.tar.gz'
!tar czvf model.tar.gz ssd_mobilenet_v2_coco_2018_03_29/frozen_inference_graph.pb
```

이 예제에 사용된 명령 플래그는 다음을 수행합니다.
+ `c`: 아카이브 생성
+ `z`: gzip으로 아카이브 압축
+ `v`: 아카이브 진행률 표시
+ `f`: 아카이브의 파일 이름 지정

### 내장 예측기
<a name="how-to-save-built-in"></a>

내장 추정기는 프레임워크별 컨테이너 또는 알고리즘별 컨테이너로 만들어집니다. 내장 알고리즘과 프레임워크별 예측기 모두에 대한 예측기 객체는 내장된 `.fit` 메서드를 사용하여 모델을 훈련시킬 때 사용자를 위해 모델을 올바른 형식으로 저장합니다.

예를 들어 `sagemaker.TensorFlow`를 사용하여 TensorFlow 예측기를 정의할 수 있습니다.

```
from sagemaker.tensorflow import TensorFlow

estimator = TensorFlow(entry_point='mnist.py',
                        role=role,  #param role can be arn of a sagemaker execution role
                        framework_version='1.15.3',
                        py_version='py3',
                        training_steps=1000, 
                        evaluation_steps=100,
                        instance_count=2,
                        instance_type='ml.c4.xlarge')
```

그런 다음 `.fit` 내장 메서드로 모델을 훈련시킵니다.

```
estimator.fit(inputs)
```

마지막으로 `compile_model` 메서드로 모델을 컴파일하기 전에:

```
# Specify output path of the compiled model
output_path = '/'.join(estimator.output_path.split('/')[:-1])

# Compile model
optimized_estimator = estimator.compile_model(target_instance_family='ml_c5', 
                              input_shape={'data':[1, 784]},  # Batch size 1, 3 channels, 224x224 Images.
                              output_path=output_path,
                              framework='tensorflow', framework_version='1.15.3')
```

또한 `sagemaker.estimator.Estimator` 클래스를 사용하여 SageMaker Python SDK의 `compile_model` 메서드로 내장 알고리즘을 훈련 및 컴파일하기 위한 예측기 객체를 초기화할 수 있습니다.

```
import sagemaker
from sagemaker.image_uris import retrieve
sagemaker_session = sagemaker.Session()
aws_region = sagemaker_session.boto_region_name

# Specify built-in algorithm training image
training_image = retrieve(framework='image-classification', 
                          region=aws_region, image_scope='training')

training_image = retrieve(framework='image-classification', region=aws_region, image_scope='training')

# Create estimator object for training
estimator = sagemaker.estimator.Estimator(image_uri=training_image,
                                          role=role,  #param role can be arn of a sagemaker execution role
                                          instance_count=1,
                                          instance_type='ml.p3.8xlarge',
                                          volume_size = 50,
                                          max_run = 360000,
                                          input_mode= 'File',
                                          output_path=s3_training_output_location,
                                          base_job_name='image-classification-training'
                                          )
                                          
# Setup the input data_channels to be used later for training.                                          
train_data = sagemaker.inputs.TrainingInput(s3_training_data_location,
                                            content_type='application/x-recordio',
                                            s3_data_type='S3Prefix')
validation_data = sagemaker.inputs.TrainingInput(s3_validation_data_location,
                                                content_type='application/x-recordio',
                                                s3_data_type='S3Prefix')
data_channels = {'train': train_data, 'validation': validation_data}


# Train model
estimator.fit(inputs=data_channels, logs=True)

# Compile model with Neo                                                                                  
optimized_estimator = estimator.compile_model(target_instance_family='ml_c5',
                                          input_shape={'data':[1, 3, 224, 224], 'softmax_label':[1]},
                                          output_path=s3_compilation_output_location,
                                          framework='mxnet',
                                          framework_version='1.7')
```

SageMaker Python SDK를 사용하여 모델을 컴파일하는 방법에 대한 자세한 내용은 [모델 컴파일(Amazon SageMaker AI SDK)](neo-job-compilation-sagemaker-sdk.md) 섹션을 참조하세요.

# 모델 컴파일(AWS Command Line Interface)
<a name="neo-job-compilation-cli"></a>

이 섹션에서는 AWS Command Line Interface (CLI)를 사용하여 기계 학습 모델의 Amazon SageMaker Neo 컴파일 작업을 관리하는 방법을 보여줍니다. 컴파일 작업을 생성, 설명, 중지 및 나열할 수 있습니다.

1. 컴파일 작업 생성

   [CreateCompilationJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateCompilationJob.html) API 작업을 통해 데이터 입력 형식, 모델을 저장할 S3 버킷, 컴파일된 모델을 저장할 S3 버킷, 대상 하드웨어 디바이스 또는 플랫폼을 지정할 수 있습니다.

   다음 표는 대상이 디바이스인지 플랫폼인지에 따라 `CreateCompilationJob` API를 구성하는 방법을 보여줍니다.

------
#### [ Device Example ]

   ```
   {
       "CompilationJobName": "neo-compilation-job-demo",
       "RoleArn": "arn:aws:iam::<your-account>:role/service-role/AmazonSageMaker-ExecutionRole-yyyymmddThhmmss",
       "InputConfig": {
           "S3Uri": "s3://<your-bucket>/sagemaker/neo-compilation-job-demo-data/train",
           "DataInputConfig":  "{'data': [1,3,1024,1024]}",
           "Framework": "MXNET"
       },
       "OutputConfig": {
           "S3OutputLocation": "s3://<your-bucket>/sagemaker/neo-compilation-job-demo-data/compile",
           # A target device specification example for a ml_c5 instance family
           "TargetDevice": "ml_c5"
       },
       "StoppingCondition": {
           "MaxRuntimeInSeconds": 300
       }
   }
   ```

   PyTorch 프레임워크를 사용하여 모델을 훈련시켰고 대상 디바이스가 `ml_* `대상인 경우 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_InputConfig.html#sagemaker-Type-InputConfig-FrameworkVersion](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_InputConfig.html#sagemaker-Type-InputConfig-FrameworkVersion) 필드에서 사용한 프레임워크 버전을 선택적으로 지정할 수 있습니다.

   ```
   {
       "CompilationJobName": "neo-compilation-job-demo",
       "RoleArn": "arn:aws:iam::<your-account>:role/service-role/AmazonSageMaker-ExecutionRole-yyyymmddThhmmss",
       "InputConfig": {
           "S3Uri": "s3://<your-bucket>/sagemaker/neo-compilation-job-demo-data/train",
           "DataInputConfig":  "{'data': [1,3,1024,1024]}",
           "Framework": "PYTORCH",
           "FrameworkVersion": "1.6"
       },
       "OutputConfig": {
           "S3OutputLocation": "s3://<your-bucket>/sagemaker/neo-compilation-job-demo-data/compile",
           # A target device specification example for a ml_c5 instance family
           "TargetDevice": "ml_c5",
           # When compiling for ml_* instances using PyTorch framework, use the "CompilerOptions" field in 
           # OutputConfig to provide the correct data type ("dtype") of the model’s input. Default assumed is "float32"
           "CompilerOptions": "{'dtype': 'long'}"
       },
       "StoppingCondition": {
           "MaxRuntimeInSeconds": 300
       }
   }
   ```

**참고:**  
PyTorch 2.0 이상 버전을 사용하여 모델을 저장한 경우 `DataInputConfig` 필드는 선택 사항입니다. SageMaker AI Neo는 PyTorch로 만드는 모델 정의 파일에서 입력 구성을 가져옵니다. 정의 파일을 만드는 방법에 대한 자세한 내용은 *SageMaker Neo에 모델 저장* 아래의 [PyTorch](neo-compilation-preparing-model.md#how-to-save-pytorch) 섹션을 참조하세요.
이 API 필드는 PyTorch에서만 지원됩니다.

------
#### [ Platform Example ]

   ```
   {
       "CompilationJobName": "neo-test-compilation-job",
       "RoleArn": "arn:aws:iam::<your-account>:role/service-role/AmazonSageMaker-ExecutionRole-yyyymmddThhmmss",
       "InputConfig": {
           "S3Uri": "s3://<your-bucket>/sagemaker/neo-compilation-job-demo-data/train",
           "DataInputConfig":  "{'data': [1,3,1024,1024]}",
           "Framework": "MXNET"
       },
       "OutputConfig": {
           "S3OutputLocation": "s3://<your-bucket>/sagemaker/neo-compilation-job-demo-data/compile",
           # A target platform configuration example for a p3.2xlarge instance
           "TargetPlatform": {
               "Os": "LINUX",
               "Arch": "X86_64",
               "Accelerator": "NVIDIA"
           },
           "CompilerOptions": "{'cuda-ver': '10.0', 'trt-ver': '6.0.1', 'gpu-code': 'sm_70'}"
       },
       "StoppingCondition": {
           "MaxRuntimeInSeconds": 300
       }
   }
   ```

------
**참고**  
`OutputConfig` API 연산의 경우 `TargetDevice` 및 `TargetPlatform` API 연산은 상호 배타적입니다. 두 옵션 중 하나를 선택해야 합니다.

   프레임워크에 따른 `DataInputConfig`의 JSON 문자열 예제를 찾으려면 [Neo에 필요한 입력 데이터 형태](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-troubleshooting-compilation.html#neo-troubleshooting-errors-preventing)를 참조하세요.

   구성 설정에 대한 자세한 내용은 SageMaker API 참조에서 [InputConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_InputConfig.html), [OutputConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_OutputConfig.html) 및 [TargetPlatform](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_TargetPlatform.html) API 연산을 참조하세요.

1. JSON 파일을 구성한 후 다음 명령을 실행하여 컴파일 작업을 생성합니다.

   ```
   aws sagemaker create-compilation-job \
   --cli-input-json file://job.json \
   --region us-west-2 
   
   # You should get CompilationJobArn
   ```

1. 다음 명령어를 실행하여 컴파일 작업을 설명합니다.

   ```
   aws sagemaker describe-compilation-job \
   --compilation-job-name $JOB_NM \
   --region us-west-2
   ```

1. 다음 명령을 실행하여 컴파일 작업을 중지합니다.

   ```
   aws sagemaker stop-compilation-job \
   --compilation-job-name $JOB_NM \
   --region us-west-2
   
   # There is no output for compilation-job operation
   ```

1. 다음 명령을 실행하여 컴파일 작업을 나열합니다.

   ```
   aws sagemaker list-compilation-jobs \
   --region us-west-2
   ```

# 모델 컴파일(Amazon SageMaker AI 콘솔)
<a name="neo-job-compilation-console"></a>

Amazon SageMaker AI 콘솔에서 Amazon SageMaker Neo 컴파일 작업을 만들 수 있습니다.

1. **Amazon SageMaker AI** 콘솔에서 **컴파일 작업**을 선택한 후 **컴파일 작업 생성**을 선택합니다.  
![\[컴파일 작업 생성\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/8-create-compilation-job.png)

1. **컴파일 작업 생성** 페이지에서 **작업 이름**에 이름을 입력합니다. **IAM 역할**을 선택합니다.  
![\[컴파일 작업 페이지를 생성합니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/9-create-compilation-job-config.png)

1. IAM 역할이 아직 없는 경우 **새 역할 생성**을 선택합니다.  
![\[IAM 역할 위치를 생성합니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/10a-create-iam-role.png)

1. **IAM 역할 생성** 페이지에서 **모든 S3 버킷**을 선택하고 **역할 생성**을 선택합니다.  
![\[IAM 역할 페이지를 생성합니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/10-create-iam-role.png)

1. 

------
#### [ Non PyTorch Frameworks ]

   **입력 구성** 섹션에서 **모델 아티팩트의 위치** 입력 필드에 모델 아티팩트가 포함된 Amazon S3 버킷의 전체 경로를 입력합니다. 모델 아티팩트는 압축된 tarball 파일 형식(`.tar.gz`) 이어야 합니다.

   **데이터 입력 구성** 필드에 입력 데이터의 형태를 지정하는 JSON 문자열을 입력합니다.

   **기계 학습 프레임워크**에서 선택한 프레임워크를 선택합니다.

![\[입력 구성 페이지.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/neo-create-compilation-job-input-config.png)


   프레임워크에 따른 입력 데이터 형태의 JSON 문자열 예제를 찾으려면 [Neo에 필요한 입력 데이터 형태](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-troubleshooting.html#neo-troubleshooting-errors-preventing)를 참조하세요.

------
#### [ PyTorch Framework ]

   PyTorch 모델 컴파일에도 유사한 지침이 적용됩니다. 그러나 PyTorch로 훈련하고 target `ml_*`(`ml_inf` 제외)에 대해 모델을 컴파일하려는 경우 사용한 PyTorch의 버전을 선택적으로 지정할 수 있습니다.

![\[프레임워크 버전 를 선택할 수 있는 위치를 보여주는 예제 입력 구성 섹션입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/compile_console_pytorch.png)


   프레임워크에 따른 입력 데이터 형태의 JSON 문자열 예제를 찾으려면 [Neo에 필요한 입력 데이터 형태](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-troubleshooting.html#neo-troubleshooting-errors-preventing)를 참조하세요.

**참고**  
PyTorch 2.0 이상 버전을 사용하여 모델을 저장한 경우 **데이터 입력 구성 필드**는 선택 사항입니다. SageMaker Neo는 PyTorch로 생성하는 모델 정의 파일에서 입력 구성을 가져옵니다. 정의 파일을 만드는 방법에 대한 자세한 내용은 *SageMaker Neo에 모델 저장* 아래의 [PyTorch](neo-compilation-preparing-model.md#how-to-save-pytorch) 섹션을 참조하세요.
PyTorch 프레임워크를 사용하여 `ml_*` 인스턴스를 컴파일할 때 **출력 구성**의 **컴파일러 옵션** 필드를 사용하여 모델 입력의 올바른 데이터 유형(`dtype`)을 제공하세요. 기본값은 `"float32"`로 설정됩니다.

![\[예제 출력 구성 섹션.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/neo_compilation_console_pytorch_compiler_options.png)


**주의**  
 `.pth` 파일로 연결되는 Amazon S3 버킷 URI 경로를 지정하는 경우 컴파일을 시작한 후 다음 오류가 발생합니다. `ClientError: InputConfiguration: Unable to untar input model.Please confirm the model is a tar.gz file` 

------

1.  **출력 구성** 섹션으로 이동하세요. 모델을 배포할 위치를 선택합니다. 모델을 **대상 디바이스** 또는 **대상 플랫폼**에 배포할 수 있습니다. 대상 디바이스에는 클라우드 및 에지 디바이스가 포함됩니다. 대상 플랫폼은 모델을 실행하려는 특정 OS, 아키텍처 및 가속기를 말합니다.

    **S3 출력 위치**에 모델을 저장할 S3 버킷의 경로를 입력합니다. **컴파일러 옵션** 섹션에서 JSON 형식의 컴파일러 옵션을 선택적으로 추가할 수 있습니다.  
![\[출력 구성 페이지.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/neo-console-output-config.png)

1. 시작되면 컴파일 작업의 상태를 확인합니다. 이 작업 상태는 다음 스크린샷과 같이 **컴파일 작업** 페이지 상단에서 확인할 수 있습니다. 또한 **상태** 열에서 상태를 확인할 수도 있습니다.  
![\[컴파일 작업 상태\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/12-run-model-compilation.png)

1. 완료되면 컴파일 작업의 상태를 확인합니다. 다음 스크린샷과 같이 **상태** 열에서 상태를 확인할 수 있습니다.  
![\[컴파일 작업 상태\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/neo/12a-completed-model-compilation.png)

# 모델 컴파일(Amazon SageMaker AI SDK)
<a name="neo-job-compilation-sagemaker-sdk"></a>

 [Amazon SageMaker AI SDK for Python](https://sagemaker.readthedocs.io/en/stable/)의 [https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html?#sagemaker.estimator.Estimator.compile_model](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html?#sagemaker.estimator.Estimator.compile_model) API를 사용하여 훈련된 모델을 컴파일하고 특정 대상 하드웨어에 맞게 최적화할 수 있습니다. 모델 훈련 중에 사용되는 예측기 객체에서 API를 호출해야 합니다.

**참고**  
MXNet 또는 PyTorch로 모델을 컴파일할 때는 `MMS_DEFAULT_RESPONSE_TIMEOUT` 환경 변수를 `500`으로 설정해야 합니다. TensorFlow에는 환경 변수가 필요하지 않습니다.

 다음은 `trained_model_estimator` 객체를 사용하여 모델을 컴파일하는 방법의 예시입니다.

```
# Replace the value of expected_trained_model_input below and
# specify the name & shape of the expected inputs for your trained model
# in json dictionary form
expected_trained_model_input = {'data':[1, 784]}

# Replace the example target_instance_family below to your preferred target_instance_family
compiled_model = trained_model_estimator.compile_model(target_instance_family='ml_c5',
        input_shape=expected_trained_model_input,
        output_path='insert s3 output path',
        env={'MMS_DEFAULT_RESPONSE_TIMEOUT': '500'})
```

코드는 모델을 컴파일하고, 최적화된 모델을 `output_path`에 저장하고, 엔드포인트에 배포할 수 있는 SageMaker AI 모델을 만듭니다.