

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

# 모델 제공
<a name="model-serving"></a>

다음은 Conda를 사용하는 DLAMI에 설치된 모델 제공 옵션입니다. 옵션 중 한 가지를 클릭하여 사용법을 알아보십시오.

**Topics**
+ [TensorFlow Serving](tutorial-tfserving.md)
+ [TorchServe](tutorial-torchserve.md)

# TensorFlow Serving
<a name="tutorial-tfserving"></a>

[TensorFlow Serving은 머신 러닝 모델을 위한 유연한 고성능 서비스 시스템입니다.](https://www.tensorflow.org/tfx/guide/serving)

`tensorflow-serving-api`에는 단일 프레임워크 DLAMI가 사전 설치되어 있습니다. tensorflow serving을 사용하려면 먼저 TensorFlow 환경을 활성화합니다.

```
$ source /opt/tensorflow/bin/activate
```

그런 다음 원하는 텍스트 편집기를 사용하여 다음 내용이 들어 있는 스크립트를 생성합니다. 이름을 `test_train_mnist.py`로 지정합니다. 이 스크립트는 이미지를 분류하는 신경망 기계 학습 모델을 훈련하고 평가하는 [TensorFlow 자습서](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/quickstart/beginner.ipynb)에서 참조할 수 있습니다.

```
import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
```

이제 서버 위치, 포트 및 허스키 사진의 파일 이름을 파라미터로 전달하는 스크립트를 실행합니다.

```
$ /opt/tensorflow/bin/python3 test_train_mnist.py
```

 이 스크립트에서 결과가 출력되려면 시간이 걸리므로 인내심을 가지고 기다리십시오. 훈련 완료 시 다음과 같은 결과를 보게 됩니다.

```
I0000 00:00:1739482012.389276    4284 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.
1875/1875 [==============================] - 24s 2ms/step - loss: 0.2973 - accuracy: 0.9134 
Epoch 2/5
1875/1875 [==============================] - 3s 2ms/step - loss: 0.1422 - accuracy: 0.9582
Epoch 3/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.1076 - accuracy: 0.9687
Epoch 4/5
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0872 - accuracy: 0.9731
Epoch 5/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.0731 - accuracy: 0.9771
313/313 [==============================] - 0s 1ms/step - loss: 0.0749 - accuracy: 0.9780
```

## 더 많은 기능과 예제
<a name="tutorial-tfserving-project"></a>

TensorFlow Serving에 대한 자세한 내용은 [TensorFlow 웹 사이트](https://www.tensorflow.org/serving/)를 참조하세요.

# TorchServe
<a name="tutorial-torchserve"></a>

TorchServe는 PyTorch에서 내보낸 딥 러닝 모델을 제공하기 위한 유연한 도구입니다. TorchServe에는 Conda를 사용하는 Deep Learning AMI가 사전 설치되어 있습니다.

TorchServe 사용에 대한 자세한 내용은 [PyTorch용 모델 서버 설명서](https://github.com/pytorch/serve/blob/master/docs/README.md)를 참조하세요.

 **주제** 

## TorchServe에서 이미지 분류 모델 서비스
<a name="tutorial-torchserve-serving"></a>

이 자습서에서는 TorchServe로 이미지 분류 모델을 서비스하는 방법을 보여줍니다. PyTorch에서 제공하는 DenseNet-161 모델을 사용합니다. 서버가 실행되면 예측 요청을 수신합니다. 예를 들어 고양이의 이미지와 같은 이미지를 업로드할 때 서버는 모델이 교육한 클래스 가운데 가장 일치하는 5개 클래스에 대한 예측을 반환합니다.

**TorchServe에서 예제 이미지 분류 모델을 서비스하려면**

1. Conda를 사용하는 DLAMI(버전 34 이상)의 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스에 연결합니다.

1. `pytorch_p310` 환경을 활성화합니다.

   ```
   source activate pytorch_p310
   ```

1. TorchServe 리포지토리를 복제한 다음 모델을 저장할 디렉토리를 생성합니다.  

   ```
   git clone https://github.com/pytorch/serve.git
   mkdir model_store
   ```

1. 모델 아카이버를 사용하여 모델을 보관합니다. `extra-files` 매개변수는 `TorchServe` 리포지토리의 파일을 사용하므로 필요한 경우 경로를 업데이트하세요. 모델 아카이버에 대한 자세한 내용은 [TorchServe용 Torch 모델 아카이버](https://github.com/pytorch/serve/blob/master/model-archiver/README.md)를 참조하세요.

   ```
   wget https://download.pytorch.org/models/densenet161-8d451a50.pth
   torch-model-archiver --model-name densenet161 --version 1.0 --model-file ./serve/examples/image_classifier/densenet_161/model.py --serialized-file densenet161-8d451a50.pth --export-path model_store --extra-files ./serve/examples/image_classifier/index_to_name.json --handler image_classifier
   ```

1. TorchServe를 실행하여 엔드포인트를 시작합니다. `> /dev/null`을 추가하면 로그 출력이 중지됩니다.

   ```
   torchserve --start --ncs --model-store model_store --models densenet161.mar > /dev/null
   ```

1. 고양이의 이미지를 다운로드한 다음 TorchServe 예측 엔드포인트로 전송합니다.

   ```
   curl -O https://s3.amazonaws.com/model-server/inputs/kitten.jpg
   curl http://127.0.0.1:8080/predictions/densenet161 -T kitten.jpg
   ```

   예측 엔드포인트는 다음 상위 5개의 예측과 유사한 예측을 JSON으로 반환합니다. 여기에서 이미지는 47%의 확률로 이집트 고양이를 포함하고, 그 다음으로 46%의 확률로 태비 고양이를 포함합니다.

   ```
   {
    "tiger_cat": 0.46933576464653015,
    "tabby": 0.463387668132782,
    "Egyptian_cat": 0.0645613968372345,
    "lynx": 0.0012828196631744504,
    "plastic_bag": 0.00023323058849200606
   }
   ```

1. 테스트를 마친 후 서버를 중단합니다.

   ```
   torchserve --stop
   ```

 **기타 예제** 

TorchServe에는 사용자가 DLAMI 인스턴스에서 실행할 수 있는 다양한 예제가 있습니다. 이러한 예제는 [TorchServe 프로젝트 리포지토리](https://github.com/pytorch/serve/tree/master/examples)에서 볼 수 있습니다.

 **추가 정보** 

 Docker와 최신 TorchServe 기능을 사용하여 TorchServe를 설정하는 방법을 포함한 더 많은 TorchServe 설명서는 GitHub의 [TorchServe 프로젝트](https://github.com/pytorch/serve) 페이지를 참조하세요.