

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

# Instans Cloud
<a name="neo-cloud-instances"></a>

Amazon SageMaker Neo menyediakan dukungan kompilasi untuk kerangka kerja machine learning populer seperti TensorFlow,, PyTorch MXNet, dan banyak lagi. Anda dapat menerapkan model yang dikompilasi ke instance cloud dan instans AWS Inferentia. Untuk daftar lengkap jenis kerangka kerja dan instance yang didukung, lihat Jenis dan Kerangka [Instance yang Didukung](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-supported-cloud.html). 

Anda dapat mengkompilasi model Anda dengan salah satu dari tiga cara: melalui AWS CLI, Konsol SageMaker AI, atau SageMaker AI SDK untuk Python. Lihat, [Gunakan Neo untuk Mengompilasi Model](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-job-compilation.html) untuk informasi lebih lanjut. Setelah dikompilasi, artefak model Anda disimpan di URI bucket Amazon S3 yang Anda tentukan selama pekerjaan kompilasi. Anda dapat menerapkan model yang dikompilasi ke instance cloud dan instans AWS Inferentia menggunakan AI SageMaker SDK untuk Python,,, atau konsol. AWS SDK untuk Python (Boto3) AWS CLI AWS 

Jika Anda menerapkan model menggunakan AWS CLI, konsol, atau Boto3, Anda harus memilih URI ECR Amazon image Docker untuk container utama Anda. Lihat [Neo Inference Container Images](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-deployment-hosting-services-container-images.html) untuk daftar Amazon URIs ECR.

**Topics**
+ [

# Jenis dan Kerangka Instance yang Didukung
](neo-supported-cloud.md)
+ [

# Menyebarkan Model
](neo-deployment-hosting-services.md)
+ [

# Permintaan Inferensi Dengan Layanan yang Diterapkan
](neo-requests.md)
+ [

# Gambar Kontainer Inferensi
](neo-deployment-hosting-services-container-images.md)

# Jenis dan Kerangka Instance yang Didukung
<a name="neo-supported-cloud"></a>

Amazon SageMaker Neo mendukung kerangka pembelajaran mendalam yang populer untuk kompilasi dan penerapan. Anda dapat menerapkan model Anda ke instance cloud atau jenis instans AWS Inferentia.

Berikut ini menjelaskan kerangka kerja yang didukung SageMaker Neo dan instance cloud target yang dapat Anda kompilasi dan terapkan. Untuk informasi tentang cara menerapkan model yang dikompilasi ke instans cloud atau Inferentia, lihat [Menerapkan Model dengan](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-deployment-hosting-services.html) Instans Cloud.

## Instans Cloud
<a name="neo-supported-cloud-instances"></a>

SageMaker Neo mendukung kerangka kerja pembelajaran mendalam berikut untuk instance cloud CPU dan GPU: 


| Kerangka Kerja | Versi Kerangka | Versi Model | Model | Format Model (dikemas dalam\$1.tar.gz) | Toolkit | 
| --- | --- | --- | --- | --- | --- | 
| MXNet | 1.8.0 | Mendukung 1.8.0 atau sebelumnya | Klasifikasi Gambar, Deteksi Objek, Segmentasi Semantik, Estimasi Pose, Pengenalan Aktivitas | Satu file simbol (.json) dan satu file parameter (.params) | GluonCV v0.8.0 | 
| ONNX | 1.7.0 | Mendukung 1.7.0 atau sebelumnya | Klasifikasi Gambar, SVM | Satu file model (.onnx) |  | 
| Keras | 2.2.4 | Mendukung 2.2.4 atau sebelumnya | Klasifikasi Gambar | Satu file definisi model (.h5) |  | 
| PyTorch | 1.4, 1.5, 1.6, 1.7, 1.8, 1.12, 1.13, atau 2.0 | Mendukung 1.4, 1.5, 1.6, 1.7, 1.8, 1.12, 1.13, dan 2.0 |  Klasifikasi Gambar Versi 1.13 dan 2.0 mendukung Object Detection, Vision Transformer, dan HuggingFace  | Satu file definisi model (.pt atau.pth) dengan input dtype float32 |  | 
| TensorFlow | 1.15.3 atau 2.9 | Mendukung 1.15.3 dan 2.9 | Klasifikasi Gambar | Untuk model yang disimpan, satu file.pb atau satu file.pbtxt dan direktori variabel yang berisi variabel Untuk model beku, hanya satu file.pb atau .pbtxt |  | 
| XGBoost | 1.3.3 | Mendukung 1.3.3 atau sebelumnya | Pohon Keputusan | Satu file XGBoost model (.model) di mana jumlah node dalam pohon kurang dari 2 ^ 31 |  | 

**catatan**  
“Versi Model” adalah versi kerangka kerja yang digunakan untuk melatih dan mengekspor model. 

## Tipe instans
<a name="neo-supported-cloud-instances-types"></a>

 Anda dapat menerapkan model yang dikompilasi SageMaker AI ke salah satu instance cloud yang tercantum di bawah ini: 


| Instans | Jenis Komputasi | 
| --- | --- | 
| `ml_c4` | Standar | 
| `ml_c5` | Standar | 
| `ml_m4` | Standar | 
| `ml_m5` | Standar | 
| `ml_p2` | Komputasi yang dipercepat | 
| `ml_p3` | Komputasi yang dipercepat | 
| `ml_g4dn` | Komputasi yang dipercepat | 

 Untuk informasi tentang vCPU, memori, dan harga per jam yang tersedia untuk setiap jenis instans, lihat Harga [Amazon SageMaker ](https://aws.amazon.com/sagemaker/pricing/). 

**catatan**  
Saat mengompilasi `ml_*` instance menggunakan PyTorch framework, gunakan bidang **opsi Compiler** di **Output Configuration** untuk memberikan tipe data (`dtype`) yang benar dari input model.  
Default diatur ke `"float32"`.

## AWS Inferensia
<a name="neo-supported-inferentia"></a>

 SageMaker Neo mendukung kerangka kerja pembelajaran mendalam berikut untuk Inf1: 


| Kerangka Kerja | Versi Kerangka | Versi Model | Model | Format Model (dikemas dalam\$1.tar.gz) | Toolkit | 
| --- | --- | --- | --- | --- | --- | 
| MXNet | 1.5 atau 1.8  | Mendukung 1.8, 1.5 dan sebelumnya | Klasifikasi Gambar, Deteksi Objek, Segmentasi Semantik, Estimasi Pose, Pengenalan Aktivitas | Satu file simbol (.json) dan satu file parameter (.params) | GluonCV v0.8.0 | 
| PyTorch | 1.7, 1.8 atau 1.9 | Mendukung 1.9 dan sebelumnya | Klasifikasi Gambar | Satu file definisi model (.pt atau.pth) dengan input dtype float32 |  | 
| TensorFlow | 1.15 atau 2.5 | Mendukung 2.5, 1.15 dan sebelumnya | Klasifikasi Gambar | Untuk model yang disimpan, satu file.pb atau satu file.pbtxt dan direktori variabel yang berisi variabel Untuk model beku, hanya satu file.pb atau .pbtxt |  | 

**catatan**  
“Versi Model” adalah versi kerangka kerja yang digunakan untuk melatih dan mengekspor model.

Anda dapat menerapkan model yang SageMaker dikompilasi NEO ke instans Amazon Inf1 berbasis Inferensia AWS . EC2 AWS Inferentia adalah chip silikon khusus pertama Amazon yang dirancang untuk mempercepat pembelajaran mendalam. Saat ini, Anda dapat menggunakan `ml_inf1` instance untuk menerapkan model yang dikompilasi.

### AWS Inferensia2 dan Trainium AWS
<a name="neo-supported-inferentia-trainium"></a>

Saat ini, Anda dapat menerapkan model yang SageMaker dikompilasi NEO ke instans AWS Amazon EC2 Inf2 berbasis Inferensia2 (di Wilayah AS Timur (Ohio)), dan ke instans Amazon EC2 Trn1 AWS berbasis Train (di Wilayah AS Timur (Virginia N.)). Untuk informasi lebih lanjut tentang model yang didukung pada instance ini, lihat [Panduan Kesesuaian Arsitektur Model](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/arch/model-architecture-fit.html) dalam dokumentasi AWS Neuron, dan contoh di repositori [Neuron Github](https://github.com/aws-neuron/aws-neuron-sagemaker-samples).

# Menyebarkan Model
<a name="neo-deployment-hosting-services"></a>

Untuk menerapkan model yang SageMaker dikompilasi Amazon Neo ke titik akhir HTTPS, Anda harus mengonfigurasi dan membuat titik akhir untuk model menggunakan layanan hosting Amazon AI. SageMaker Saat ini, pengembang dapat menggunakan Amazon SageMaker APIs untuk menyebarkan modul ke instance ml.c5, ml.c4, ml.m5, ml.m4, ml.p3, ml.p2, dan ml.inf1. 

Untuk instance [Inferentia](https://aws.amazon.com/machine-learning/inferentia/) dan [Trainium](https://aws.amazon.com/machine-learning/trainium/), model perlu dikompilasi secara khusus untuk instance tersebut. Model yang dikompilasi untuk jenis instance lain tidak dijamin berfungsi dengan instans Inferentia atau Trainium.

Saat menerapkan model yang dikompilasi, Anda perlu menggunakan instance yang sama untuk target yang Anda gunakan untuk kompilasi. Ini menciptakan titik akhir SageMaker AI yang dapat Anda gunakan untuk melakukan inferensi. [Anda dapat menerapkan model yang dikompilasi NEO menggunakan salah satu dari berikut ini: [Amazon SageMaker AI SDK untuk Python, SDK for](https://sagemaker.readthedocs.io/en/stable/)[Python (Boto3),](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) dan konsol AI. [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/reference/)SageMaker ](https://console.aws.amazon.com/sagemaker)

**catatan**  
Untuk menerapkan model menggunakan AWS CLI, konsol, atau Boto3, lihat [Neo Inference Container Images untuk memilih URI gambar inferensi untuk container](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-deployment-hosting-services-container-images.html) utama Anda. 

**Topics**
+ [

# Prasyarat
](neo-deployment-hosting-services-prerequisites.md)
+ [

# Menerapkan Model Terkompilasi Menggunakan SageMaker SDK
](neo-deployment-hosting-services-sdk.md)
+ [

# Menyebarkan Model Kompilasi Menggunakan Boto3
](neo-deployment-hosting-services-boto3.md)
+ [

# Menerapkan Model Kompilasi Menggunakan AWS CLI
](neo-deployment-hosting-services-cli.md)
+ [

# Menerapkan Model Kompilasi Menggunakan Konsol
](neo-deployment-hosting-services-console.md)

# Prasyarat
<a name="neo-deployment-hosting-services-prerequisites"></a>

**catatan**  
Ikuti petunjuk di bagian ini jika Anda mengkompilasi model menggunakan AWS SDK untuk Python (Boto3), AWS CLI, atau konsol SageMaker AI. 

Untuk membuat model yang SageMaker dikompilasi NEO, Anda memerlukan yang berikut ini:

1. Gambar Docker Amazon ECR URI. Anda dapat memilih salah satu yang memenuhi kebutuhan Anda dari [daftar ini](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-deployment-hosting-services-container-images.html). 

1. File skrip titik masuk:

   1. **Untuk PyTorch dan MXNet model:**

      *Jika Anda melatih model Anda menggunakan SageMaker AI*, skrip pelatihan harus mengimplementasikan fungsi yang dijelaskan di bawah ini. Skrip pelatihan berfungsi sebagai skrip titik masuk selama inferensi. Dalam contoh yang dirinci dalam [Pelatihan MNIST, Kompilasi dan Penerapan dengan MXNet Modul dan SageMaker Neo](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_neo_compilation_jobs/mxnet_mnist/mxnet_mnist_neo.html), skrip pelatihan (`mnist.py`) mengimplementasikan fungsi yang diperlukan.

      *Jika Anda tidak melatih model Anda menggunakan SageMaker AI*, Anda perlu menyediakan file entry point script (`inference.py`) yang dapat digunakan pada saat inferensi. [Berdasarkan kerangka kerja— MXNet atau PyTorch —lokasi skrip inferensi harus sesuai dengan Struktur Direktori Model SDK SageMaker Python untuk atau [Struktur Direktori Model untuk MxNet](https://sagemaker.readthedocs.io/en/stable/frameworks/mxnet/using_mxnet.html#model-directory-structure). PyTorch](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#model-directory-structure) 

      Saat menggunakan gambar Neo Inference Optimized Container dengan **PyTorch**dan **MXNet**pada tipe instance CPU dan GPU, skrip inferensi harus mengimplementasikan fungsi-fungsi berikut: 
      + `model_fn`: Memuat model. (Opsional)
      + `input_fn`: Mengkonversi payload permintaan masuk ke array numpy.
      + `predict_fn`: Melakukan prediksi.
      + `output_fn`: Mengkonversi output prediksi ke payload respon.
      + Atau, Anda dapat menentukan `transform_fn` untuk menggabungkan`input_fn`,`predict_fn`, dan`output_fn`.

      Berikut ini adalah contoh `inference.py` skrip dalam direktori bernama `code` (`code/inference.py`) untuk **PyTorch dan MXNet (Gluon dan Modul)**. Contoh pertama memuat model dan kemudian menyajikannya pada data gambar pada GPU: 

------
#### [ MXNet Module ]

      ```
      import numpy as np
      import json
      import mxnet as mx
      import neomx  # noqa: F401
      from collections import namedtuple
      
      Batch = namedtuple('Batch', ['data'])
      
      # Change the context to mx.cpu() if deploying to a CPU endpoint
      ctx = mx.gpu()
      
      def model_fn(model_dir):
          # The compiled model artifacts are saved with the prefix 'compiled'
          sym, arg_params, aux_params = mx.model.load_checkpoint('compiled', 0)
          mod = mx.mod.Module(symbol=sym, context=ctx, label_names=None)
          exe = mod.bind(for_training=False,
                         data_shapes=[('data', (1,3,224,224))],
                         label_shapes=mod._label_shapes)
          mod.set_params(arg_params, aux_params, allow_missing=True)
          
          # Run warm-up inference on empty data during model load (required for GPU)
          data = mx.nd.empty((1,3,224,224), ctx=ctx)
          mod.forward(Batch([data]))
          return mod
      
      
      def transform_fn(mod, image, input_content_type, output_content_type):
          # pre-processing
          decoded = mx.image.imdecode(image)
          resized = mx.image.resize_short(decoded, 224)
          cropped, crop_info = mx.image.center_crop(resized, (224, 224))
          normalized = mx.image.color_normalize(cropped.astype(np.float32) / 255,
                                        mean=mx.nd.array([0.485, 0.456, 0.406]),
                                        std=mx.nd.array([0.229, 0.224, 0.225]))
          transposed = normalized.transpose((2, 0, 1))
          batchified = transposed.expand_dims(axis=0)
          casted = batchified.astype(dtype='float32')
          processed_input = casted.as_in_context(ctx)
      
          # prediction/inference
          mod.forward(Batch([processed_input]))
      
          # post-processing
          prob = mod.get_outputs()[0].asnumpy().tolist()
          prob_json = json.dumps(prob)
          return prob_json, output_content_type
      ```

------
#### [ MXNet Gluon ]

      ```
      import numpy as np
      import json
      import mxnet as mx
      import neomx  # noqa: F401
      
      # Change the context to mx.cpu() if deploying to a CPU endpoint
      ctx = mx.gpu()
      
      def model_fn(model_dir):
          # The compiled model artifacts are saved with the prefix 'compiled'
          block = mx.gluon.nn.SymbolBlock.imports('compiled-symbol.json',['data'],'compiled-0000.params', ctx=ctx)
          
          # Hybridize the model & pass required options for Neo: static_alloc=True & static_shape=True
          block.hybridize(static_alloc=True, static_shape=True)
          
          # Run warm-up inference on empty data during model load (required for GPU)
          data = mx.nd.empty((1,3,224,224), ctx=ctx)
          warm_up = block(data)
          return block
      
      
      def input_fn(image, input_content_type):
          # pre-processing
          decoded = mx.image.imdecode(image)
          resized = mx.image.resize_short(decoded, 224)
          cropped, crop_info = mx.image.center_crop(resized, (224, 224))
          normalized = mx.image.color_normalize(cropped.astype(np.float32) / 255,
                                        mean=mx.nd.array([0.485, 0.456, 0.406]),
                                        std=mx.nd.array([0.229, 0.224, 0.225]))
          transposed = normalized.transpose((2, 0, 1))
          batchified = transposed.expand_dims(axis=0)
          casted = batchified.astype(dtype='float32')
          processed_input = casted.as_in_context(ctx)
          return processed_input
      
      
      def predict_fn(processed_input_data, block):
          # prediction/inference
          prediction = block(processed_input_data)
          return prediction
      
      def output_fn(prediction, output_content_type):
          # post-processing
          prob = prediction.asnumpy().tolist()
          prob_json = json.dumps(prob)
          return prob_json, output_content_type
      ```

------
#### [ PyTorch 1.4 and Older ]

      ```
      import os
      import torch
      import torch.nn.parallel
      import torch.optim
      import torch.utils.data
      import torch.utils.data.distributed
      import torchvision.transforms as transforms
      from PIL import Image
      import io
      import json
      import pickle
      
      
      def model_fn(model_dir):
          """Load the model and return it.
          Providing this function is optional.
          There is a default model_fn available which will load the model
          compiled using SageMaker Neo. You can override it here.
      
          Keyword arguments:
          model_dir -- the directory path where the model artifacts are present
          """
      
          # The compiled model is saved as "compiled.pt"
          model_path = os.path.join(model_dir, 'compiled.pt')
          with torch.neo.config(model_dir=model_dir, neo_runtime=True):
              model = torch.jit.load(model_path)
              device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
              model = model.to(device)
      
          # We recommend that you run warm-up inference during model load
          sample_input_path = os.path.join(model_dir, 'sample_input.pkl')
          with open(sample_input_path, 'rb') as input_file:
              model_input = pickle.load(input_file)
          if torch.is_tensor(model_input):
              model_input = model_input.to(device)
              model(model_input)
          elif isinstance(model_input, tuple):
              model_input = (inp.to(device) for inp in model_input if torch.is_tensor(inp))
              model(*model_input)
          else:
              print("Only supports a torch tensor or a tuple of torch tensors")
              return model
      
      
      def transform_fn(model, request_body, request_content_type,
                       response_content_type):
          """Run prediction and return the output.
          The function
          1. Pre-processes the input request
          2. Runs prediction
          3. Post-processes the prediction output.
          """
          # preprocess
          decoded = Image.open(io.BytesIO(request_body))
          preprocess = transforms.Compose([
              transforms.Resize(256),
              transforms.CenterCrop(224),
              transforms.ToTensor(),
              transforms.Normalize(
                  mean=[
                      0.485, 0.456, 0.406], std=[
                      0.229, 0.224, 0.225]),
          ])
          normalized = preprocess(decoded)
          batchified = normalized.unsqueeze(0)
          # predict
          device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
          batchified = batchified.to(device)
          output = model.forward(batchified)
      
          return json.dumps(output.cpu().numpy().tolist()), response_content_type
      ```

------
#### [ PyTorch 1.5 and Newer ]

      ```
      import os
      import torch
      import torch.nn.parallel
      import torch.optim
      import torch.utils.data
      import torch.utils.data.distributed
      import torchvision.transforms as transforms
      from PIL import Image
      import io
      import json
      import pickle
      
      
      def model_fn(model_dir):
          """Load the model and return it.
          Providing this function is optional.
          There is a default_model_fn available, which will load the model
          compiled using SageMaker Neo. You can override the default here.
          The model_fn only needs to be defined if your model needs extra
          steps to load, and can otherwise be left undefined.
      
          Keyword arguments:
          model_dir -- the directory path where the model artifacts are present
          """
      
          # The compiled model is saved as "model.pt"
          model_path = os.path.join(model_dir, 'model.pt')
          device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
          model = torch.jit.load(model_path, map_location=device)
          model = model.to(device)
      
          return model
      
      
      def transform_fn(model, request_body, request_content_type,
                          response_content_type):
          """Run prediction and return the output.
          The function
          1. Pre-processes the input request
          2. Runs prediction
          3. Post-processes the prediction output.
          """
          # preprocess
          decoded = Image.open(io.BytesIO(request_body))
          preprocess = transforms.Compose([
                                      transforms.Resize(256),
                                      transforms.CenterCrop(224),
                                      transforms.ToTensor(),
                                      transforms.Normalize(
                                          mean=[
                                              0.485, 0.456, 0.406], std=[
                                              0.229, 0.224, 0.225]),
                                          ])
          normalized = preprocess(decoded)
          batchified = normalized.unsqueeze(0)
          
          # predict
          device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
          batchified = batchified.to(device)
          output = model.forward(batchified)
          return json.dumps(output.cpu().numpy().tolist()), response_content_type
      ```

------

   1.  **Untuk instance inf1 atau onnx, xgboost, gambar kontainer keras** 

      Untuk semua gambar kontainer yang dioptimalkan Neo Inference lainnya, atau jenis instance inferentia, skrip titik masuk harus mengimplementasikan fungsi berikut untuk Neo Deep Learning Runtime: 
      + `neo_preprocess`: Mengkonversi payload permintaan masuk ke array numpy.
      + `neo_postprocess`: Mengonversi output prediksi dari Neo Deep Learning Runtime menjadi badan respons.
**catatan**  
Dua fungsi sebelumnya tidak menggunakan salah satu fungsi, MXNet, PyTorch atau. TensorFlow

      Untuk contoh cara menggunakan fungsi-fungsi ini, lihat [Notebook Contoh Kompilasi Model Neo](https://docs.aws.amazon.com//sagemaker/latest/dg/neo.html#neo-sample-notebooks). 

   1. **Untuk TensorFlow model**

      Jika model Anda memerlukan logika pra-dan pasca-pemrosesan khusus sebelum data dikirim ke model, maka Anda harus menentukan `inference.py` file skrip titik masuk yang dapat digunakan pada saat inferensi. Script harus mengimplementasikan baik sepasang `input_handler` dan `output_handler` fungsi atau fungsi handler tunggal. 
**catatan**  
Perhatikan bahwa jika fungsi handler diimplementasikan, `input_handler` dan `output_handler` diabaikan. 

      Berikut ini adalah contoh kode `inference.py` skrip yang dapat Anda kumpulkan dengan model kompilasi untuk melakukan pra-dan sesudah pemrosesan khusus pada model klasifikasi gambar. Klien SageMaker AI mengirimkan file gambar sebagai tipe `application/x-image` konten ke `input_handler` fungsi, di mana ia dikonversi ke JSON. File gambar yang dikonversi kemudian dikirim ke [Tensorflow Model Server (TFX)](https://www.tensorflow.org/tfx/serving/api_rest) menggunakan REST API. 

      ```
      import json
      import numpy as np
      import json
      import io
      from PIL import Image
      
      def input_handler(data, context):
          """ Pre-process request input before it is sent to TensorFlow Serving REST API
          
          Args:
          data (obj): the request data, in format of dict or string
          context (Context): an object containing request and configuration details
          
          Returns:
          (dict): a JSON-serializable dict that contains request body and headers
          """
          f = data.read()
          f = io.BytesIO(f)
          image = Image.open(f).convert('RGB')
          batch_size = 1
          image = np.asarray(image.resize((512, 512)))
          image = np.concatenate([image[np.newaxis, :, :]] * batch_size)
          body = json.dumps({"signature_name": "serving_default", "instances": image.tolist()})
          return body
      
      def output_handler(data, context):
          """Post-process TensorFlow Serving output before it is returned to the client.
          
          Args:
          data (obj): the TensorFlow serving response
          context (Context): an object containing request and configuration details
          
          Returns:
          (bytes, string): data to return to client, response content type
          """
          if data.status_code != 200:
              raise ValueError(data.content.decode('utf-8'))
      
          response_content_type = context.accept_header
          prediction = data.content
          return prediction, response_content_type
      ```

      Jika tidak ada pra-atau pasca-pemrosesan khusus, klien SageMaker AI mengonversi gambar file ke JSON dengan cara yang sama sebelum mengirimnya ke titik akhir AI. SageMaker 

      Untuk informasi selengkapnya, lihat [Deploying to TensorFlow Serving Endpoints di Python SageMaker SDK](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/deploying_tensorflow_serving.html#providing-python-scripts-for-pre-pos-processing). 

1. URI bucket Amazon S3 yang berisi artefak model yang dikompilasi. 

# Menerapkan Model Terkompilasi Menggunakan SageMaker SDK
<a name="neo-deployment-hosting-services-sdk"></a>

Anda harus memenuhi bagian [prasyarat](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-prerequisites) jika model dikompilasi menggunakan AWS SDK untuk Python (Boto3),, AWS CLI atau konsol Amazon AI. SageMaker Ikuti salah satu kasus penggunaan berikut untuk menerapkan model yang dikompilasi dengan SageMaker Neo berdasarkan cara Anda mengkompilasi model Anda.

**Topics**
+ [

## Jika Anda mengkompilasi model menggunakan SageMaker SDK
](#neo-deployment-hosting-services-sdk-deploy-sm-sdk)
+ [

## Jika Anda mengkompilasi model Anda menggunakan MXNet atau PyTorch
](#neo-deployment-hosting-services-sdk-deploy-sm-boto3)
+ [

## Jika Anda mengkompilasi model Anda menggunakan Boto3, SageMaker konsol, atau CLI untuk TensorFlow
](#neo-deployment-hosting-services-sdk-deploy-sm-boto3-tensorflow)

## Jika Anda mengkompilasi model menggunakan SageMaker SDK
<a name="neo-deployment-hosting-services-sdk-deploy-sm-sdk"></a>

Pegangan objek [SageMaker.model](https://sagemaker.readthedocs.io/en/stable/api/inference/model.html?highlight=sagemaker.Model) untuk model yang dikompilasi menyediakan fungsi [deploy ()](https://sagemaker.readthedocs.io/en/stable/api/inference/model.html?highlight=sagemaker.Model#sagemaker.model.Model.deploy), yang memungkinkan Anda membuat titik akhir untuk menyajikan permintaan inferensi. Fungsi ini memungkinkan Anda mengatur jumlah dan jenis instance yang digunakan untuk titik akhir. Anda harus memilih contoh yang telah Anda kompilasi model Anda. Misalnya, dalam pekerjaan yang dikompilasi di bagian [Compile a Model (Amazon SageMaker SDK)](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-job-compilation-sagemaker-sdk.html), ini adalah. `ml_c5` 

```
predictor = compiled_model.deploy(initial_instance_count = 1, instance_type = 'ml.c5.4xlarge')

# Print the name of newly created endpoint
print(predictor.endpoint_name)
```

## Jika Anda mengkompilasi model Anda menggunakan MXNet atau PyTorch
<a name="neo-deployment-hosting-services-sdk-deploy-sm-boto3"></a>

Buat model SageMaker AI dan terapkan menggunakan deploy () API di bawah Model khusus kerangka kerja. APIs Karena MXNet, itu adalah [MXNetModel](https://sagemaker.readthedocs.io/en/stable/frameworks/mxnet/sagemaker.mxnet.html?highlight=MXNetModel#mxnet-model) dan untuk PyTorch, itu [ PyTorchModel](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html?highlight=PyTorchModel#sagemaker.pytorch.model.PyTorchModel). Saat membuat dan menerapkan model SageMaker AI, Anda harus menyetel variabel `MMS_DEFAULT_RESPONSE_TIMEOUT` lingkungan ke `500` dan menentukan `entry_point` parameter sebagai skrip inferensi (`inference.py`) dan `source_dir` parameter sebagai lokasi direktori (`code`) dari skrip inferensi. Untuk menyiapkan skrip inferensi (`inference.py`) ikuti langkah Prasyarat. 

Contoh berikut menunjukkan cara menggunakan fungsi-fungsi ini untuk menerapkan model yang dikompilasi menggunakan SageMaker AI SDK untuk Python: 

------
#### [ MXNet ]

```
from sagemaker.mxnet import MXNetModel

# Create SageMaker model and deploy an endpoint
sm_mxnet_compiled_model = MXNetModel(
    model_data='insert S3 path of compiled MXNet model archive',
    role='AmazonSageMaker-ExecutionRole',
    entry_point='inference.py',
    source_dir='code',
    framework_version='1.8.0',
    py_version='py3',
    image_uri='insert appropriate ECR Image URI for MXNet',
    env={'MMS_DEFAULT_RESPONSE_TIMEOUT': '500'},
)

# Replace the example instance_type below to your preferred instance_type
predictor = sm_mxnet_compiled_model.deploy(initial_instance_count = 1, instance_type = 'ml.p3.2xlarge')

# Print the name of newly created endpoint
print(predictor.endpoint_name)
```

------
#### [ PyTorch 1.4 and Older ]

```
from sagemaker.pytorch import PyTorchModel

# Create SageMaker model and deploy an endpoint
sm_pytorch_compiled_model = PyTorchModel(
    model_data='insert S3 path of compiled PyTorch model archive',
    role='AmazonSageMaker-ExecutionRole',
    entry_point='inference.py',
    source_dir='code',
    framework_version='1.4.0',
    py_version='py3',
    image_uri='insert appropriate ECR Image URI for PyTorch',
    env={'MMS_DEFAULT_RESPONSE_TIMEOUT': '500'},
)

# Replace the example instance_type below to your preferred instance_type
predictor = sm_pytorch_compiled_model.deploy(initial_instance_count = 1, instance_type = 'ml.p3.2xlarge')

# Print the name of newly created endpoint
print(predictor.endpoint_name)
```

------
#### [ PyTorch 1.5 and Newer ]

```
from sagemaker.pytorch import PyTorchModel

# Create SageMaker model and deploy an endpoint
sm_pytorch_compiled_model = PyTorchModel(
    model_data='insert S3 path of compiled PyTorch model archive',
    role='AmazonSageMaker-ExecutionRole',
    entry_point='inference.py',
    source_dir='code',
    framework_version='1.5',
    py_version='py3',
    image_uri='insert appropriate ECR Image URI for PyTorch',
)

# Replace the example instance_type below to your preferred instance_type
predictor = sm_pytorch_compiled_model.deploy(initial_instance_count = 1, instance_type = 'ml.p3.2xlarge')

# Print the name of newly created endpoint
print(predictor.endpoint_name)
```

------

**catatan**  
`AmazonS3ReadOnlyAccess`Kebijakan `AmazonSageMakerFullAccess` dan kebijakan harus dilampirkan pada peran `AmazonSageMaker-ExecutionRole` IAM. 

## Jika Anda mengkompilasi model Anda menggunakan Boto3, SageMaker konsol, atau CLI untuk TensorFlow
<a name="neo-deployment-hosting-services-sdk-deploy-sm-boto3-tensorflow"></a>

Buat `TensorFlowModel` objek, lalu panggil deploy: 

```
role='AmazonSageMaker-ExecutionRole'
model_path='S3 path for model file'
framework_image='inference container arn'
tf_model = TensorFlowModel(model_data=model_path,
                framework_version='1.15.3',
                role=role, 
                image_uri=framework_image)
instance_type='ml.c5.xlarge'
predictor = tf_model.deploy(instance_type=instance_type,
                    initial_instance_count=1)
```

Lihat [Menerapkan langsung dari artefak model untuk informasi](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/deploying_tensorflow_serving.html#deploying-directly-from-model-artifacts) selengkapnya. 

Anda dapat memilih gambar Docker Amazon ECR URI yang memenuhi kebutuhan Anda dari daftar [ini](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-container-images.html). 

Untuk informasi selengkapnya tentang cara membuat `TensorFlowModel` objek, lihat [SageMaker SDK](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-serving-model). 

**catatan**  
Permintaan inferensi pertama Anda mungkin memiliki latensi tinggi jika Anda menerapkan model Anda pada GPU. Ini karena kernel komputasi yang dioptimalkan dibuat pada permintaan inferensi pertama. Kami menyarankan Anda membuat file pemanasan permintaan inferensi dan menyimpannya di samping file model Anda sebelum mengirimkannya ke TFX. Ini dikenal sebagai “pemanasan” model. 

[Cuplikan kode berikut menunjukkan cara menghasilkan file pemanasan untuk contoh klasifikasi gambar di bagian prasyarat:](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-prerequisites) 

```
import tensorflow as tf
from tensorflow_serving.apis import classification_pb2
from tensorflow_serving.apis import inference_pb2
from tensorflow_serving.apis import model_pb2
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_log_pb2
from tensorflow_serving.apis import regression_pb2
import numpy as np

with tf.python_io.TFRecordWriter("tf_serving_warmup_requests") as writer:       
    img = np.random.uniform(0, 1, size=[224, 224, 3]).astype(np.float32)
    img = np.expand_dims(img, axis=0)
    test_data = np.repeat(img, 1, axis=0)
    request = predict_pb2.PredictRequest()
    request.model_spec.name = 'compiled_models'
    request.model_spec.signature_name = 'serving_default'
    request.inputs['Placeholder:0'].CopyFrom(tf.compat.v1.make_tensor_proto(test_data, shape=test_data.shape, dtype=tf.float32))
    log = prediction_log_pb2.PredictionLog(
    predict_log=prediction_log_pb2.PredictLog(request=request))
    writer.write(log.SerializeToString())
```

Untuk informasi lebih lanjut tentang cara “menghangatkan” model Anda, lihat [halaman TensorFlow TFX](https://www.tensorflow.org/tfx/serving/saved_model_warmup).

# Menyebarkan Model Kompilasi Menggunakan Boto3
<a name="neo-deployment-hosting-services-boto3"></a>

Anda harus memenuhi bagian [prasyarat](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-prerequisites) jika model dikompilasi menggunakan AWS SDK untuk Python (Boto3),, AWS CLI atau konsol Amazon AI. SageMaker Ikuti langkah-langkah di bawah ini untuk membuat dan menerapkan model yang SageMaker dikompilasi NEO menggunakan [Amazon Web Services SDK for Python (Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)). 

**Topics**
+ [

## Menyebarkan Model
](#neo-deployment-hosting-services-boto3-steps)

## Menyebarkan Model
<a name="neo-deployment-hosting-services-boto3-steps"></a>

Setelah Anda memenuhi [prasyarat](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-prerequisites), gunakan,, dan`create_model`. `create_enpoint_config` `create_endpoint` APIs 

Contoh berikut menunjukkan cara menggunakan ini APIs untuk menyebarkan model yang dikompilasi dengan Neo: 

```
import boto3
client = boto3.client('sagemaker')

# create sagemaker model
create_model_api_response = client.create_model(
                                    ModelName='my-sagemaker-model',
                                    PrimaryContainer={
                                        'Image': <insert the ECR Image URI>,
                                        'ModelDataUrl': 's3://path/to/model/artifact/model.tar.gz',
                                        'Environment': {}
                                    },
                                    ExecutionRoleArn='ARN for AmazonSageMaker-ExecutionRole'
                            )

print ("create_model API response", create_model_api_response)

# create sagemaker endpoint config
create_endpoint_config_api_response = client.create_endpoint_config(
                                            EndpointConfigName='sagemaker-neomxnet-endpoint-configuration',
                                            ProductionVariants=[
                                                {
                                                    'VariantName': <provide your variant name>,
                                                    'ModelName': 'my-sagemaker-model',
                                                    'InitialInstanceCount': 1,
                                                    'InstanceType': <provide your instance type here>
                                                },
                                            ]
                                       )

print ("create_endpoint_config API response", create_endpoint_config_api_response)

# create sagemaker endpoint
create_endpoint_api_response = client.create_endpoint(
                                    EndpointName='provide your endpoint name',
                                    EndpointConfigName=<insert your endpoint config name>,
                                )

print ("create_endpoint API response", create_endpoint_api_response)
```

**catatan**  
`AmazonS3ReadOnlyAccess`Kebijakan `AmazonSageMakerFullAccess` dan kebijakan harus dilampirkan pada peran `AmazonSageMaker-ExecutionRole` IAM. 

Untuk sintaks lengkap`create_model`,`create_endpoint_config`, dan `create_endpoint` APIs, lihat [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_model](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_model), [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_endpoint_config](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_endpoint_config), dan [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_endpoint](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_endpoint), masing-masing. 

Jika Anda tidak melatih model Anda menggunakan SageMaker AI, tentukan variabel lingkungan berikut: 

------
#### [ MXNet and PyTorch ]

```
"Environment": {
    "SAGEMAKER_PROGRAM": "inference.py",
    "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code",
    "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
    "SAGEMAKER_REGION": "insert your region",
    "MMS_DEFAULT_RESPONSE_TIMEOUT": "500"
}
```

------
#### [ TensorFlow ]

```
"Environment": {
    "SAGEMAKER_PROGRAM": "inference.py",
    "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code",
    "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
    "SAGEMAKER_REGION": "insert your region"
}
```

------

 Jika Anda melatih model menggunakan SageMaker AI, tentukan variabel lingkungan `SAGEMAKER_SUBMIT_DIRECTORY` sebagai URI bucket Amazon S3 lengkap yang berisi skrip pelatihan. 

# Menerapkan Model Kompilasi Menggunakan AWS CLI
<a name="neo-deployment-hosting-services-cli"></a>

Anda harus memenuhi bagian [prasyarat](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-prerequisites) jika model dikompilasi menggunakan AWS SDK untuk Python (Boto3),, AWS CLI atau konsol Amazon AI. SageMaker Ikuti langkah-langkah di bawah ini untuk membuat dan menerapkan model yang SageMaker dikompilasi NEO menggunakan. [AWS CLI](https://docs.aws.amazon.com/cli/latest/reference/) 

**Topics**
+ [

## Menyebarkan Model
](#neo-deploy-cli)

## Menyebarkan Model
<a name="neo-deploy-cli"></a>

Setelah Anda memenuhi [prasyarat](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-prerequisites), gunakan,, dan perintah`create-model`. `create-enpoint-config` `create-endpoint` AWS CLI Langkah-langkah berikut menjelaskan cara menggunakan perintah ini untuk menyebarkan model yang dikompilasi dengan Neo: 



### Buat Model
<a name="neo-deployment-hosting-services-cli-create-model"></a>

Dari [Neo Inference Container Images](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-deployment-hosting-services-container-images.html), pilih URI gambar inferensi dan kemudian gunakan `create-model` API untuk membuat model SageMaker AI. Anda dapat melakukan ini dengan dua langkah: 

1. Buat `create_model.json` file. Di dalam file, tentukan nama model, URI gambar, jalur ke `model.tar.gz` file di bucket Amazon S3, dan peran eksekusi SageMaker AI Anda: 

   ```
   {
       "ModelName": "insert model name",
       "PrimaryContainer": {
           "Image": "insert the ECR Image URI",
           "ModelDataUrl": "insert S3 archive URL",
           "Environment": {"See details below"}
       },
       "ExecutionRoleArn": "ARN for AmazonSageMaker-ExecutionRole"
   }
   ```

   Jika Anda melatih model Anda menggunakan SageMaker AI, tentukan variabel lingkungan berikut: 

   ```
   "Environment": {
       "SAGEMAKER_SUBMIT_DIRECTORY" : "[Full S3 path for *.tar.gz file containing the training script]"
   }
   ```

   Jika Anda tidak melatih model Anda menggunakan SageMaker AI, tentukan variabel lingkungan berikut: 

------
#### [ MXNet and PyTorch ]

   ```
   "Environment": {
       "SAGEMAKER_PROGRAM": "inference.py",
       "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code",
       "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
       "SAGEMAKER_REGION": "insert your region",
       "MMS_DEFAULT_RESPONSE_TIMEOUT": "500"
   }
   ```

------
#### [ TensorFlow ]

   ```
   "Environment": {
       "SAGEMAKER_PROGRAM": "inference.py",
       "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code",
       "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
       "SAGEMAKER_REGION": "insert your region"
   }
   ```

------
**catatan**  
`AmazonS3ReadOnlyAccess`Kebijakan `AmazonSageMakerFullAccess` dan kebijakan harus dilampirkan pada peran `AmazonSageMaker-ExecutionRole` IAM. 

1. Jalankan perintah berikut:

   ```
   aws sagemaker create-model --cli-input-json file://create_model.json
   ```

   Untuk sintaks lengkap `create-model` API, lihat [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-model.html). 

### Buat Konfigurasi Endpoint
<a name="neo-deployment-hosting-services-cli-create-endpoint-config"></a>

Setelah membuat model SageMaker AI, buat konfigurasi titik akhir menggunakan `create-endpoint-config` API. Untuk melakukan ini, buat file JSON dengan spesifikasi konfigurasi titik akhir Anda. Misalnya, Anda dapat menggunakan template kode berikut dan menyimpannya sebagai`create_config.json`: 

```
{
    "EndpointConfigName": "<provide your endpoint config name>",
    "ProductionVariants": [
        {
            "VariantName": "<provide your variant name>",
            "ModelName": "my-sagemaker-model",
            "InitialInstanceCount": 1,
            "InstanceType": "<provide your instance type here>",
            "InitialVariantWeight": 1.0
        }
    ]
}
```

Sekarang jalankan AWS CLI perintah berikut untuk membuat konfigurasi endpoint Anda: 

```
aws sagemaker create-endpoint-config --cli-input-json file://create_config.json
```

Untuk sintaks lengkap `create-endpoint-config` API, lihat [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint-config.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint-config.html). 

### Buat Endpoint
<a name="neo-deployment-hosting-services-cli-create-endpoint"></a>

Setelah Anda membuat konfigurasi titik akhir, buat titik akhir menggunakan API: `create-endpoint` 

```
aws sagemaker create-endpoint --endpoint-name '<provide your endpoint name>' --endpoint-config-name '<insert your endpoint config name>'
```

Untuk sintaks lengkap `create-endpoint` API, lihat [https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/create-endpoint.html). 

# Menerapkan Model Kompilasi Menggunakan Konsol
<a name="neo-deployment-hosting-services-console"></a>

Anda harus memenuhi bagian [prasyarat](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-prerequisites) jika model dikompilasi menggunakan AWS SDK untuk Python (Boto3), konsol, AWS CLI atau Amazon AI. SageMaker [Ikuti langkah-langkah di bawah ini untuk membuat dan menerapkan model yang dikompilasi SageMaker AI Neo menggunakan konsol SageMaker https://console.aws.amazon.com AI/AI. SageMaker ](https://console.aws.amazon.com/sagemaker/)

**Topics**
+ [

## Menyebarkan Model
](#deploy-the-model-console-steps)

## Menyebarkan Model
<a name="deploy-the-model-console-steps"></a>

 Setelah Anda memenuhi [prasyarat](https://docs.aws.amazon.com//sagemaker/latest/dg/neo-deployment-hosting-services-prerequisites), gunakan langkah-langkah berikut untuk menerapkan model yang dikompilasi dengan Neo: 

1. Pilih **Model**, lalu pilih **Buat model** dari grup **Inferensi**. Pada halaman **Buat model**, lengkapi **nama Model**, **peran IAM**, dan bidang **VPC** (opsional), jika diperlukan.  
![\[Buat model Neo untuk inferensi\]](http://docs.aws.amazon.com/id_id/sagemaker/latest/dg/images/create-pipeline-model.png)

1. Untuk menambahkan informasi tentang kontainer yang digunakan untuk menyebarkan model Anda, pilih **Tambahkan kontainer kontainer**, lalu pilih **Berikutnya**. Lengkapi **opsi input Container**, **Lokasi gambar kode inferensi**, dan **Lokasi artefak model**, dan opsional, **nama host kontainer**, dan bidang variabel **Lingkungan**.  
![\[Buat model Neo untuk inferensi\]](http://docs.aws.amazon.com/id_id/sagemaker/latest/dg/images/neo-deploy-console-container-definition.png)

1. Untuk menerapkan model yang dikompilasi NEO, pilih yang berikut ini:
   + **Opsi input kontainer**: Pilih **Berikan artefak model dan gambar inferensi**.
   + **Lokasi gambar kode inferensi: Pilih URI gambar** inferensi dari [Neo Inference Container Images](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-deployment-hosting-services-container-images.html), tergantung pada AWS Wilayah dan jenis aplikasi. 
   + **Lokasi artefak model**: Masukkan URI bucket Amazon S3 dari artefak model terkompilasi yang dihasilkan oleh API kompilasi Neo.
   + **Variabel lingkungan**:
     + Biarkan bidang ini kosong untuk **SageMaker XGBoost**.
     + Jika Anda melatih model menggunakan SageMaker AI, tentukan variabel lingkungan `SAGEMAKER_SUBMIT_DIRECTORY` sebagai URI bucket Amazon S3 yang berisi skrip pelatihan. 
     + Jika Anda tidak melatih model Anda menggunakan SageMaker AI, tentukan variabel lingkungan berikut:     
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/sagemaker/latest/dg/neo-deployment-hosting-services-console.html)

1. Konfirmasikan bahwa informasi untuk kontainer akurat, lalu pilih **Buat model**. Pada **halaman landing Create model**, pilih **Create endpoint**.   
![\[Buat halaman arahan Model\]](http://docs.aws.amazon.com/id_id/sagemaker/latest/dg/images/neo-deploy-console-create-model-land-page.png)

1. Di **Buat dan konfigurasikan diagram titik akhir**, tentukan nama **Endpoint**. Untuk **konfigurasi Attach endpoint**, pilih **Create a new endpoint** configuration.  
![\[Konsol Neo membuat dan mengonfigurasi UI titik akhir.\]](http://docs.aws.amazon.com/id_id/sagemaker/latest/dg/images/neo-deploy-console-config-endpoint.png)

1. Di halaman **konfigurasi titik akhir baru**, tentukan nama **konfigurasi Endpoint**.   
![\[UI konfigurasi titik akhir baru konsol Neo.\]](http://docs.aws.amazon.com/id_id/sagemaker/latest/dg/images/neo-deploy-console-new-endpoint-config.png)

1. Pilih **Edit** di samping nama model dan tentukan **jenis Instance** yang benar pada halaman **Edit Production Variant**. Sangat penting bahwa nilai **tipe Instance** cocok dengan yang ditentukan dalam pekerjaan kompilasi Anda.  
![\[UI konfigurasi titik akhir baru konsol Neo.\]](http://docs.aws.amazon.com/id_id/sagemaker/latest/dg/images/neo-deploy-console-edit-production-variant.png)

1. Pilih **Simpan**.

1. Pada halaman **konfigurasi titik akhir baru**, pilih **Buat konfigurasi titik akhir**, lalu pilih **Buat** titik akhir. 

# Permintaan Inferensi Dengan Layanan yang Diterapkan
<a name="neo-requests"></a>

Jika Anda telah mengikuti instruksi[Menyebarkan Model](neo-deployment-hosting-services.md), Anda harus menyiapkan dan menjalankan titik akhir SageMaker AI. Terlepas dari bagaimana Anda menerapkan model yang dikompilasi NEO, ada tiga cara Anda dapat mengirimkan permintaan inferensi: 

**Topics**
+ [

# Meminta Inferensi dari Layanan yang Diterapkan (Amazon SageMaker SDK)
](neo-requests-sdk.md)
+ [

# Minta Inferensi dari Layanan yang Diterapkan (Boto3)
](neo-requests-boto3.md)
+ [

# Minta Inferensi dari Layanan yang Diterapkan (CLI AWS )
](neo-requests-cli.md)

# Meminta Inferensi dari Layanan yang Diterapkan (Amazon SageMaker SDK)
<a name="neo-requests-sdk"></a>

Gunakan contoh kode berikut untuk meminta kesimpulan dari layanan yang Anda gunakan berdasarkan kerangka kerja yang Anda gunakan untuk melatih model Anda. Contoh kode untuk kerangka kerja yang berbeda serupa. Perbedaan utama adalah bahwa TensorFlow membutuhkan `application/json` sebagai jenis konten. 

 

## PyTorch dan MXNet
<a name="neo-requests-sdk-py-mxnet"></a>

 Jika Anda menggunakan **PyTorch v1.4 atau versi lebih baru** atau **MXNet 1.7.0 atau yang lebih baru** dan Anda memiliki titik akhir Amazon SageMaker AI`InService`, Anda dapat membuat permintaan inferensi menggunakan `predictor` paket AI SageMaker SDK untuk Python. 

**catatan**  
API bervariasi berdasarkan SageMaker AI SDK untuk versi Python:  
Untuk versi 1.x, gunakan [https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor](https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor)dan [https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor.predict](https://sagemaker.readthedocs.io/en/v1.72.0/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor.predict)API.
Untuk versi 2.x, gunakan [https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.Predictor](https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.Predictor)dan [https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.Predictor.predict](https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.Predictor.predict)API.

Contoh kode berikut menunjukkan cara menggunakan ini APIs untuk mengirim gambar untuk inferensi: 

------
#### [ SageMaker Python SDK v1.x ]

```
from sagemaker.predictor import RealTimePredictor

endpoint = 'insert name of your endpoint here'

# Read image into memory
payload = None
with open("image.jpg", 'rb') as f:
    payload = f.read()

predictor = RealTimePredictor(endpoint=endpoint, content_type='application/x-image')
inference_response = predictor.predict(data=payload)
print (inference_response)
```

------
#### [ SageMaker Python SDK v2.x ]

```
from sagemaker.predictor import Predictor

endpoint = 'insert name of your endpoint here'

# Read image into memory
payload = None
with open("image.jpg", 'rb') as f:
    payload = f.read()
    
predictor = Predictor(endpoint)
inference_response = predictor.predict(data=payload)
print (inference_response)
```

------

## TensorFlow
<a name="neo-requests-sdk-py-tf"></a>

Contoh kode berikut menunjukkan cara menggunakan SageMaker Python SDK API untuk mengirim gambar untuk inferensi: 

```
from sagemaker.predictor import Predictor
from PIL import Image
import numpy as np
import json

endpoint = 'insert the name of your endpoint here'

# Read image into memory
image = Image.open(input_file)
batch_size = 1
image = np.asarray(image.resize((224, 224)))
image = image / 128 - 1
image = np.concatenate([image[np.newaxis, :, :]] * batch_size)
body = json.dumps({"instances": image.tolist()})
    
predictor = Predictor(endpoint)
inference_response = predictor.predict(data=body)
print(inference_response)
```

# Minta Inferensi dari Layanan yang Diterapkan (Boto3)
<a name="neo-requests-boto3"></a>

 Anda dapat mengirimkan permintaan inferensi menggunakan SageMaker AI SDK for Python (Boto3) klien dan API setelah Anda memiliki titik [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-runtime.html#SageMakerRuntime.Client.invoke_endpoint](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-runtime.html#SageMakerRuntime.Client.invoke_endpoint)akhir AI. SageMaker `InService` Contoh kode berikut menunjukkan cara mengirim gambar untuk inferensi: 

------
#### [ PyTorch and MXNet ]

```
import boto3

import json
 
endpoint = 'insert name of your endpoint here'
 
runtime = boto3.Session().client('sagemaker-runtime')
 
# Read image into memory
with open(image, 'rb') as f:
    payload = f.read()
# Send image via InvokeEndpoint API
response = runtime.invoke_endpoint(EndpointName=endpoint, ContentType='application/x-image', Body=payload)

# Unpack response
result = json.loads(response['Body'].read().decode())
```

------
#### [ TensorFlow ]

Untuk TensorFlow mengirimkan masukan dengan `application/json` untuk jenis konten. 

```
from PIL import Image
import numpy as np
import json
import boto3

client = boto3.client('sagemaker-runtime') 
input_file = 'path/to/image'
image = Image.open(input_file)
batch_size = 1
image = np.asarray(image.resize((224, 224)))
image = image / 128 - 1
image = np.concatenate([image[np.newaxis, :, :]] * batch_size)
body = json.dumps({"instances": image.tolist()})
ioc_predictor_endpoint_name = 'insert name of your endpoint here'
content_type = 'application/json'   
ioc_response = client.invoke_endpoint(
    EndpointName=ioc_predictor_endpoint_name,
    Body=body,
    ContentType=content_type
 )
```

------
#### [ XGBoost ]

 Untuk XGBoost aplikasi, Anda harus mengirimkan teks CSV sebagai gantinya: 

```
import boto3
import json
 
endpoint = 'insert your endpoint name here'
 
runtime = boto3.Session().client('sagemaker-runtime')
 
csv_text = '1,-1.0,1.0,1.5,2.6'
# Send CSV text via InvokeEndpoint API
response = runtime.invoke_endpoint(EndpointName=endpoint, ContentType='text/csv', Body=csv_text)
# Unpack response
result = json.loads(response['Body'].read().decode())
```

------

 Perhatikan bahwa BYOM memungkinkan untuk jenis konten kustom. Untuk informasi selengkapnya, lihat [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html). 

# Minta Inferensi dari Layanan yang Diterapkan (CLI AWS )
<a name="neo-requests-cli"></a>

Permintaan inferensi dapat dibuat dengan [https://docs.aws.amazon.com/cli/latest/reference/sagemaker-runtime/invoke-endpoint.html](https://docs.aws.amazon.com/cli/latest/reference/sagemaker-runtime/invoke-endpoint.html)setelah Anda memiliki titik akhir `InService` Amazon SageMaker AI. Anda dapat membuat permintaan inferensi dengan AWS Command Line Interface (AWS CLI). Contoh berikut menunjukkan cara mengirim gambar untuk inferensi: 

```
aws sagemaker-runtime invoke-endpoint --endpoint-name 'insert name of your endpoint here' --body fileb://image.jpg --content-type=application/x-image output_file.txt
```

Informasi `output_file.txt` dengan tentang permintaan inferensi Anda dibuat jika inferensi berhasil. 

 Untuk TensorFlow kirimkan masukan dengan `application/json` sebagai jenis konten. 

```
aws sagemaker-runtime invoke-endpoint --endpoint-name 'insert name of your endpoint here' --body fileb://input.json --content-type=application/json output_file.txt
```

# Gambar Kontainer Inferensi
<a name="neo-deployment-hosting-services-container-images"></a>

SageMaker Neo sekarang menyediakan informasi URI gambar inferensi untuk `ml_*` target. Untuk mengetahui informasi selengkapnya, lihat [DescribeCompilationJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeCompilationJob.html#sagemaker-DescribeCompilationJob-response-InferenceImage).

Berdasarkan kasus penggunaan Anda, ganti bagian yang disorot dalam template URI gambar inferensi yang disediakan di bawah ini dengan nilai yang sesuai. 

## Amazon SageMaker AI XGBoost
<a name="inference-container-collapse-xgboost"></a>

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/xgboost-neo:latest
```

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan.

## Keras
<a name="inference-container-collapse-keras"></a>

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/sagemaker-neo-keras:fx_version-instance_type-py3
```

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan.

Ganti *fx\$1version* dengan`2.2.4`.

Ganti *instance\$1type* dengan salah satu `cpu` atau`gpu`.

## MXNet
<a name="inference-container-collapse-mxnet"></a>

------
#### [ CPU or GPU instance types ]

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/sagemaker-inference-mxnet:fx_version-instance_type-py3
```

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan. 

Ganti *fx\$1version* dengan`1.8.0`. 

Ganti *instance\$1type* dengan salah satu `cpu` atau`gpu`. 

------
#### [ Inferentia1 ]

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/sagemaker-neo-mxnet:fx_version-instance_type-py3
```

Ganti *aws\$1region* dengan salah satu `us-east-1` atau`us-west-2`. 

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan. 

Ganti *fx\$1version* dengan`1.5.1`. 

Ganti *`instance_type`* dengan`inf`.

------

## ONNX
<a name="inference-container-collapse-onnx"></a>

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/sagemaker-neo-onnx:fx_version-instance_type-py3
```

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan.

Ganti *fx\$1version* dengan`1.5.0`.

Ganti *instance\$1type* dengan salah satu `cpu` atau`gpu`.

## PyTorch
<a name="inference-container-collapse-pytorch"></a>

------
#### [ CPU or GPU instance types ]

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/sagemaker-inference-pytorch:fx_version-instance_type-py3
```

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan. 

Ganti *fx\$1version* dengan `1.4``1.5`,`1.6`,`1.7`,,`1.8`,`1.12`,`1.13`, atau`2.0`.

Ganti *instance\$1type* dengan salah satu `cpu` atau`gpu`. 

------
#### [ Inferentia1 ]

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/sagemaker-neo-pytorch:fx_version-instance_type-py3
```

Ganti *aws\$1region* dengan salah satu `us-east-1` atau`us-west-2`. 

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan. 

Ganti *fx\$1version* dengan`1.5.1`. 

Ganti *`instance_type`* dengan`inf`.

------
#### [ Inferentia2 and Trainium1 ]

```
763104351884.dkr.ecr.aws_region.amazonaws.com/pytorch-inference-neuronx:1.13.1-neuronx-py38-sdk2.10.0-ubuntu20.04
```

Ganti *aws\$1region* dengan `us-east-2` untuk Inferentia2, dan `us-east-1` untuk Trainium1.

------

## TensorFlow
<a name="inference-container-collapse-tf"></a>

------
#### [ CPU or GPU instance types ]

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/sagemaker-inference-tensorflow:fx_version-instance_type-py3
```

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan. 

Ganti *fx\$1version* dengan `1.15.3` atau`2.9`. 

Ganti *instance\$1type* dengan salah satu `cpu` atau`gpu`. 

------
#### [ Inferentia1 ]

```
aws_account_id.dkr.ecr.aws_region.amazonaws.com/sagemaker-neo-tensorflow:fx_version-instance_type-py3
```

Ganti *aws\$1account\$1id* dari tabel di akhir halaman ini berdasarkan yang *aws\$1region* Anda gunakan. Perhatikan bahwa misalnya ketik `inf` saja `us-east-1` dan `us-west-2` didukung.

Ganti *fx\$1version* dengan `1.15.0`

Ganti *instance\$1type* dengan`inf`.

------
#### [ Inferentia2 and Trainium1 ]

```
763104351884.dkr.ecr.aws_region.amazonaws.com/tensorflow-inference-neuronx:2.10.1-neuronx-py38-sdk2.10.0-ubuntu20.04
```

Ganti *aws\$1region* dengan `us-east-2` untuk Inferentia2, dan `us-east-1` untuk Trainium1.

------

Peta tabel berikut *aws\$1account\$1id* dengan*aws\$1region*. Gunakan tabel ini untuk menemukan URI gambar inferensi yang benar yang Anda butuhkan untuk aplikasi Anda. 


| aws\$1account\$1id | aws\$1region | 
| --- | --- | 
| 785573368785 | us-east-1 | 
| 007439368137 | us-east-2 | 
| 710691900526 | us-west-1 | 
| 301217895009 | us-west-2 | 
| 802834080501 | eu-west-1 | 
| 205493899709 | eu-west-2 | 
| 254080097072 | eu-west-3 | 
| 601324751636 | eu-north-1 | 
| 966458181534 | eu-south-1 | 
| 746233611703 | eu-central-1 | 
| 110948597952 | ap-east-1 | 
| 763008648453 | ap-south-1 | 
| 941853720454 | ap-northeast-1 | 
| 151534178276 | ap-northeast-2 | 
| 925152966179 | ap-northeast-3 | 
| 324986816169 | ap-southeast-1 | 
| 355873309152 | ap-southeast-2 | 
| 474822919863 | cn-northwest-1 | 
| 472730292857 | cn-north-1 | 
| 756306329178 | sa-east-1 | 
| 464438896020 | ca-central-1 | 
| 836785723513 | me-south-1 | 
| 774647643957 | af-south-1 | 
| 275950707576 | il-central-1 | 