<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Getting started
Step1:  Restart the kernel
Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages.
Step2:  Before you begin
GPU runtime
This tutorial does not require a GPU runtime.
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the following APIs
Step3:  Region
You can also change the REGION variable, which is used for operations
throughout the rest of this notebook.  Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.
Americas
Step4:  Timestamp
If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial.
Step5:  Authenticate your Google Cloud account
If you are running Notebook from Vertex AI Workbench, your environment is already authenticated.
Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.
Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization.
Step6:  Only if your bucket doesn't already exist
Step7:  Finally, validate access to your Cloud Storage bucket by examining its contents
Step8:  Set up variables
Next, set up some variables used throughout the tutorial.
Import libraries and define constants
Step9:  MODEL_ARTIFACTS_REPOSITORY is a root GCS location where the Triton model artifacts will be stored.
Step10:  The following set of constants will be used to create names and display names of Vertex Prediction resources like models, endpoints, and model deployments.
Step11:  Initialize Vertex SDK for Python
Initialize the Vertex SDK for Python for your project and corresponding bucket.
Step12:  Download model artifacts
For this tutorial, download the object detection model provided on TensorFlow Hub that has been trained on the COCO 2017 dataset. Triton expects model repository to be organized in the following structure for serving TensorFlow SavedModel formats
Step13:  After downloading the model locally, model repository will be organized as following
Step14:  Create model configuration file
The model configuration file config.pbtxt provides information about the model such as inputs and outputs. Refer to the Triton docs for the configuration format. For TensorFlow models, you could use the saved_model_cli command and map to the Triton's configuration format. Note that Triton datatypes are different from the frameworks and should be mapped accordingly based on the table here.
Step15:  Push model artifacts to GCS Bucket
The downloaded model artifacts including model configuration file are pushed to GCS bucket defined by MODEL_ARTIFACTS_REPOSITORY which will be used when creating the Vertex AI Model resource.
Step16:  Validate model artifacts are copied in the GCS model artifacts uri location.
Step17:  Download test image file and generate payload to make prediction requests
The following function downloads a test image file, formats the request payload as JSON file that will be passed to prediction requests.
Step18:  Download and view the sample image
Step19:  Format the request payload as JSON
Step20:  Run prediction with the object detection model downloaded from TensorFlow Hub on the test image
Step21:  Building and pushing the container image
To use a custom container for serving predictions, you must specify a Docker container image that meets the custom container requirements. This section describes how to create the container image running Triton and push it to Google Artifact Registry (GAR) or Google Container Registry (GCR). This tutorial shows how to push the custom container to Artifact Registry.
Setting up Artifact Registry
Enable the Artifact Registry API service for your project.
Step22:  Create a private Docker repository to push the container images
Step23:  Configure authentication to the private repo
Before you push or pull container images, configure Docker to use the gcloud command-line tool to authenticate requests to Artifact Registry for your region.
Step24:  Build the image and tag the Artifact Registry path that the image will be pushed to
Step25:  Run the container locally [optional]
Before pushing the custom container image to Artifact Registry to use it with Vertex AI Predictions, run the container in local environment to verify that the server responds to prediction instances.
To run the container image as a container locally, run the following command
Step26:  To send the container's server a health check, run the following command. It should return the status code as 200
Step27:  To send the container's server a prediction request, run the following command with sample image file as the payload and get prediction responses
Step28:  To stop the container, run the following command
Step29:  Push the container image to Artifact Registry
After testing the container image locally, push the image to Artifact Registry. The Artifact Registry image URI will be used when creating the Vertex AI model resource.
Step30:  Create Vertex AI Model resource
A  Vertex AI Model resource must be created to deploy the model to a Vertex AI Prediction Endpoint. Create a Vertex AI Model resource with the deployment image pointing to the model artifacts. Refer to Vertex AI Prediction guide for creating Vertex AI Model resource with custom container.
Step31:  Deploy the model to Vertex AI Predictions
Deploying a Vertex AI Prediction Model is a two step process.
Create an Endpoint exposing an external interface to users consuming the model. 
After the Endpoint is ready, deploy multiple versions of a model to the Endpoint. The deployed model runs the custom container image running Triton to serve predictions.
Refer to Vertex AI Predictions guide to Deploy a model using the Vertex AI API for more information about the APIs used in the following cells.
Create an endpoint
Before deploying the model you need to create a Vertex AI Prediction endpoint.
Step32:  Deploy model to an endpoint
After the endpoint is ready, deploy model to the endpoint.The deployed model runs the Triton Server on a GPU node equipped with the NVIDIA Tesla T4 GPUs. Refer to Deploy a model using the Vertex AI API guide for more information.
NOTE
Step33:  Invoking the model and getting predictions
To invoke the model through Vertex AI Prediction endpoint, format prediction request using a standard Inference Request JSON Object or a Inference Request JSON Object with a binary extension and submit the request to Vertex AI Prediction REST rawPredict endpoint. 
Instead of predict API, you must use the rawPredict API  because prediction request formats used by Triton are not compatible with the Vertex AI Prediction standard input format.
In the previous section the request body was formatted as a standard Inference Request JSON Object.
You can invoke the Vertex AI Prediction rawPredict endpoint using [Vertex AI SDK](https
Step34:  Calling rawPredict using Vertex AI SDK to get prediction response
Initialize prediction service client
Step35:  Format the http request
Step36:  Make the prediction request
Step37:  Get detection classes from the output
Step38:  Making curl request to get prediction response
Notice the use of rawPredict API endpoint in the URI below
Step39:  Cleaning up
Cleaning up training and deployment resources
To clean up all Google Cloud resources used in this notebook, you can delete the Google Cloud project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial
Step40:  Undeploy models and Delete endpoints
Step41:  Deleting models
Step42:  Delete contents from the staging bucket
NOTE
Step43:  Delete images from Artifact Registry
Deletes all the container images created in this tutorial with name defined by variable IMAGE_NAME from the registry. All associated tags are also deleted.
<ASSISTANT_TASK:>
Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
    USER_FLAG = "--user"
else:
    USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Getting started: Serving Models with NVIDIA Triton Inference Server with a custom container
<hr/>
<table align="left">
  <tr>
<!--       <td>
        <a align="center" href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/tree/master/notebooks/community/vertex_endpoints/nvidia-triton/nvidia-triton-custom-container-prediction.ipynb">
          <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab
        </a>
      </td> -->
      <td>
        <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/master/notebooks/community/vertex_endpoints/nvidia-triton/nvidia-triton-custom-container-prediction.ipynb">
          <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
          View on GitHub
        </a>
      </td>
      <td>
        <a href="https://console.cloud.google.com/ai/platform/notebooks/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/tree/master/notebooks/community/vertex_endpoints/nvidia-triton/nvidia-triton-custom-container-prediction.ipynb">
            <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxESEBUSExIVFBIWFhUXGRcWEhcTIRkVFB0nFhgdExckHSgsHBolHhgVKDMtJzIrLi8vFx8zOTY4OCowMC0BCgoKDg0OGRAQGi0mICIuKystLTcvListLi02MDIrLS03LTU3LTctKzctMS0tLS01LS43MS8tLSs1LSstMC0tLv/AABEIAGYAZgMBEQACEQEDEQH/xAAbAAEAAwEBAQEAAAAAAAAAAAAABAUGAwIBB//EADoQAAEDAgQEAgcECwEAAAAAAAEAAhEDEgQFITEGIkFRE2EycXKRocHRB1JzsRQzNEJigYKywuHwI//EABoBAQADAQEBAAAAAAAAAAAAAAADBAUCAQb/xAAyEQABBAEDAAYJBQEBAAAAAAAAAQIDEQQSITEFIkFRcfATMjNhgZGxwdEUI6Hh8UI0/9oADAMBAAIRAxEAPwD9xQBAEAQBAEAQBAEAQBAEAQBAEByxFWxpcegXTW6lo8VaSyJl2YeKSC2CNd50UksOjeziOTUWChJAgCAIAgMlj+MxTxZoeFLGuaxz7oMnctbGwnvqtSLo3XB6TVvyif2UX5mmXRp2NassvBAEAQBARM0/Uv8AV81JB66HEnqqVmQem72fmrOV6qEMPJZ4vHMpwHTJ6Dsqz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ylREcm3jx8P6Of1UCKtc+HPxM3mub1sU4Ng2zy02ydfP7xWjDjxwNvt7V88FWSV8q1/Bf5FwsGw+uA53Rm4HtfePlt61Ryc9XdWPjvLMOLW7/kalZhdPqAIAgCAIAgCAIDG/aLhYw17BH/oA/tBBgn+qz3rX6Jfcul3dt58LM/PaqR234+fGit4iblowQNDwvF5LbYv3F3i9fRum7qrGIuYuR+5db33e6vj3EM/6dIrZV7ePx+Hf9TT8LZS2jQY8tPjOY0vLtwSJLR2H0WZm5DpJHNReqi7fku40SNYiqm/aXqplkIAgCAIAgCAIAgCA5VqTXtLXNDmkQQRIIPQhetcrVtF3PHNRyUpUYbhTBsf4jaPMDIl7ngHfRpJH0Vt/SGQ9ulXfwiFduJE11on1LxUyyEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAf/9k="  width="32" height="32" alt="Vertex AI Logo">
          Run on Vertex AI Workbench
        </a>
      </td>
    </tr>
</table>
<br/>
<br/>
<br/>
<hr/>
Overview
This tutorial shows how to use a custom container running NVIDIA Triton Inference Server (Triton) to deploy a machine learning (ML) model on Vertex AI Prediction that serves online predictions.
Dataset
The tutorial uses Faster R-CNN with ResNet-101 v1 object detection model provided on TensorFlow Hub that has been trained on the COCO 2017 dataset with training images scaled to 640x640.
Objective
In this tutorial, you deploy a container running Triton to serve predictions from an object detection model on Vertex AI Predictions and then use the Vertex AI Endpoints to detect objects in an image.
The steps performed in this tutorial include:
Download model artifacts from TensorFlow Hub
Create Triton configuration file for the model
Pull a custom serving container running Triton
Upload the model as a Vertex Model resource
Deploy the Model resource to a serving Endpoint resource.
Make a prediction request
Undeploy the Model resource and delete the Endpoint
Costs
This tutorial uses billable components of Google Cloud:
Vertex AI
Cloud Storage
Learn about Vertex AI pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage.
NVIDIA Triton Inference Server (Triton) Overview
NVIDIA Triton Inference Server (Triton) provides an inference solution optimized for both CPUs and GPUs. Triton can run multiple models from the same or different frameworks concurrently on a single GPU or CPU. In a multi-GPU server, it automatically creates an instance of each model on each GPU to increase utilization without extra coding. It supports real-time inferencing, batch inferencing to maximize GPU/CPU utilization, and streaming inference with built-in support for audio streaming input. It also supports model ensembles for use cases that require multiple models to perform end-to-end inference.
The following figure shows the Triton's high-level architecture.
The model repository is a file-system based repository of the models that Triton will make available for inference.
Inference requests arrive at the server via either HTTP/REST or gRPC and are then routed to the appropriate per-model scheduler.
Triton implements multiple scheduling and batching algorithms that can be configured on a model-by-model basis.
The backend performs inference using the inputs provided in the batched requests to produce the requested outputs.
Triton provides readiness and liveness health endpoints, as well as utilization, throughput, and latency metrics, which enable the integration of Triton into deployment environments, such as Vertex AI Prediction.
Refer to Triton architecture for more detailed information.
Triton on Vertex AI Prediction
Triton inference server runs inside a container published by NVIDIA GPU Cloud (NGC) - NVIDIA Triton Inference Server Image. NVIDIA and GCP Vertex AI team collaborated and added packages and configurations to align Triton with Vertex AI requirements for custom serving container images.
The model to be served by Triton should be registered with Vertex AI as a Model resource. The Model's metadata refer to a location of the ensemble artifacts in Google Cloud Storage (GCS) and the custom serving container including configuration.
Triton loads the models and exposes inference, health, and model management REST endpoints using standard inference protocols. While deploying to Vertex AI, Triton recognizes Vertex AI environment and adopts Vertex AI Prediction protocol for health checks and predictions.
To invoke the model through the Vertex AI Prediction endpoint, format prediction request using a standard Inference Request JSON Object or a Inference Request JSON Object with a binary extension and submit a request to Vertex AI Prediction REST rawPredict endpoint. You need to use the rawPredict rather than predict endpoint because inference request formats used by Triton are not compatible with the Vertex AI Prediction standard input format.
Set up your local development environment
This notebook is only supported on Vertex AI Workbench, and the Vertex AI Workbench environment already meets all the requirements to run this notebook. Please make sure you are running the notebook in TensorFlow kernel in the Vertex AI Workbench notebook environment.
NOTE: This notebook uses docker commands to build and test the containers in the local development environment before deploying a custom container to Vertex AI Predictions. Google Colab currently does not natively support running docker and hence the notebook is supported only on Vertex AI Workbench.
Installation
Install the latest version of Vertex AI SDK for Python.
End of explanation
import os
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
Explanation: Restart the kernel
Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages.
End of explanation
PROJECT_ID = "[your-project-id]"  # @param {type:"string"}
import os
# Get your Google Cloud project ID using google.auth
import google.auth
_, PROJECT_ID = google.auth.default()
print("Project ID: ", PROJECT_ID)
# validate PROJECT_ID
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
    print(
        f"Please set your project id before proceeding to next step. Currently it's set as {PROJECT_ID}"
    )
! gcloud config set project $PROJECT_ID
Explanation: Before you begin
GPU runtime
This tutorial does not require a GPU runtime.
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.
The Google Cloud SDK is already installed in Google Cloud Notebook.
Enter your project ID in the cell below. Then run the  cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $.
End of explanation
REGION = "us-central1"  # @param {type: "string"}
Explanation: Region
You can also change the REGION variable, which is used for operations
throughout the rest of this notebook.  Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.
Americas: us-central1
Europe: europe-west4
Asia Pacific: asia-east1
You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.
Learn more about Vertex AI regions
End of explanation
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
Explanation: Timestamp
If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial.
End of explanation
BUCKET_NAME = "gs://[your-bucket-name]"  # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
    BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP
Explanation: Authenticate your Google Cloud account
If you are running Notebook from Vertex AI Workbench, your environment is already authenticated.
Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.
Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization.
End of explanation
! gsutil mb -l $REGION $BUCKET_NAME
Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.
End of explanation
! gsutil ls -al $BUCKET_NAME
Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents:
End of explanation
import json
import os
from pathlib import Path
import numpy as np
import requests
from google.api import httpbody_pb2
from google.cloud import aiplatform as aip
from google.cloud import aiplatform_v1 as gapic
from PIL import Image
Explanation: Set up variables
Next, set up some variables used throughout the tutorial.
Import libraries and define constants
End of explanation
MODEL_ARTIFACTS_REPOSITORY = f"{BUCKET_NAME}/triton-on-vertex/models"
Explanation: MODEL_ARTIFACTS_REPOSITORY is a root GCS location where the Triton model artifacts will be stored.
End of explanation
# set model names and version
MODEL_NAME = "faster-rcnn"
MODEL_VERSION = "v01"
MODEL_DISPLAY_NAME = f"triton-{MODEL_NAME}-{MODEL_VERSION}"
ENDPOINT_DISPLAY_NAME = f"endpoint-{MODEL_NAME}-{MODEL_VERSION}"
# You can get the latest Triton image uri from
# https://catalog.ngc.nvidia.com/orgs/nvidia/containers/tritonserver
NGC_TRITON_IMAGE_URI = "nvcr.io/nvidia/tritonserver:22.01-py3"
# prediction container image name
IMAGE_NAME = "vertex-triton-inference:22.01"
Explanation: The following set of constants will be used to create names and display names of Vertex Prediction resources like models, endpoints, and model deployments.
End of explanation
aip.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME)
Explanation: Initialize Vertex SDK for Python
Initialize the Vertex SDK for Python for your project and corresponding bucket.
End of explanation
# download and organize model artifacts as per Triton model repository spec
! mkdir -p models/object_detector/1/model.savedmodel/
! curl -L "https://tfhub.dev/tensorflow/faster_rcnn/resnet101_v1_640x640/1?tf-hub-format=compressed" | \
    tar -zxvC ./models/object_detector/1/model.savedmodel/
! ls -ltr ./models/object_detector/1/model.savedmodel/
Explanation: Download model artifacts
For this tutorial, download the object detection model provided on TensorFlow Hub that has been trained on the COCO 2017 dataset. Triton expects model repository to be organized in the following structure for serving TensorFlow SavedModel formats:
└── model-repository-path
       └── model_name
              ├── config.pbtxt
              └── 1
                  └── model.savedmodel
                        └── &lt;saved-model-files&gt;
The config.pbtxt file describes the model configuration for the model.
End of explanation
!tree ./models
Explanation: After downloading the model locally, model repository will be organized as following:
./models
└── object_detector
    └── 1
        └── model.savedmodel
            ├── saved_model.pb
            └── variables
                ├── variables.data-00000-of-00001
                └── variables.index
End of explanation
!saved_model_cli show --dir ./models/object_detector/1/model.savedmodel/ --all
%%writefile ./models/object_detector/config.pbtxt
name: "object_detector"
platform: "tensorflow_savedmodel"
backend: "tensorflow"
max_batch_size: 0
input [
  {
    name: "input_tensor"
    data_type: TYPE_UINT8
    dims: [ 1, -1, -1, 3 ]
  }
]
output [
  {
    name: "detection_anchor_indices"
    data_type: TYPE_FP32
    dims: [ 1, 300 ]
  },
  {
    name: "detection_boxes"
    data_type: TYPE_FP32
    dims: [ 1, 300, 4 ]
  },
  {
    name: "detection_classes"
    data_type: TYPE_FP32
    dims: [ 1, 300 ]
  },
  {
    name: "detection_multiclass_scores"
    data_type: TYPE_FP32,
    dims: [ 1, 300, 91]
  },
  {
    name: "detection_scores"
    data_type: TYPE_FP32
    dims: [ 1, 300 ]
  },
  {
    name: "num_detections"
    data_type: TYPE_FP32
    dims: [ 1 ]
  },
  {
    name: "raw_detection_boxes"
    data_type: TYPE_FP32
    dims: [ 1, 300, 4 ]
  },
  {
    name: "raw_detection_scores"
    data_type: TYPE_FP32
    dims: [ 1, 300, 91 ]
  }
]
Explanation: Create model configuration file
The model configuration file config.pbtxt provides information about the model such as inputs and outputs. Refer to the Triton docs for the configuration format. For TensorFlow models, you could use the saved_model_cli command and map to the Triton's configuration format. Note that Triton datatypes are different from the frameworks and should be mapped accordingly based on the table here.
End of explanation
! gsutil cp -r ./models/object_detector $MODEL_ARTIFACTS_REPOSITORY/
Explanation: Push model artifacts to GCS Bucket
The downloaded model artifacts including model configuration file are pushed to GCS bucket defined by MODEL_ARTIFACTS_REPOSITORY which will be used when creating the Vertex AI Model resource.
End of explanation
!gsutil ls -r $MODEL_ARTIFACTS_REPOSITORY/object_detector/
Explanation: Validate model artifacts are copied in the GCS model artifacts uri location.
End of explanation
def generate_payload(image_url):
    # download image to memory and resize
    image_inputs = Image.open(requests.get(image_url, stream=True).raw).resize(
        (200, 200)
    )
    # convert image to numpy array
    image_tensor = np.asarray(image_inputs)
    # derive image shape
    image_shape = [1] + list(image_tensor.shape)
    # create/set directory to save payload
    base = Path("./test")
    base.mkdir(exist_ok=True)
    # create payload request
    payload = {
        "id": "0",
        "inputs": [
            {
                "name": "input_tensor",
                "shape": image_shape,
                "datatype": "UINT8",
                "parameters": {},
                "data": image_tensor.tolist(),
            }
        ],
    }
    # save payload as json file
    payload_file = os.path.join(base, "payload.json")
    with open(payload_file, "w") as f:
        json.dump(payload, f)
    print(f"Payload generated at {payload_file}")
    return payload_file
Explanation: Download test image file and generate payload to make prediction requests
The following function downloads a test image file, formats the request payload as JSON file that will be passed to prediction requests.
End of explanation
# set image url
image_url = "https://github.com/tensorflow/models/raw/master/research/object_detection/test_images/image2.jpg"
# show image
image = Image.open(requests.get(image_url, stream=True).raw).resize((200, 200))
image
Explanation: Download and view the sample image
End of explanation
# format payload as JSON
payload_file = generate_payload(image_url)
Explanation: Format the request payload as JSON
End of explanation
import tensorflow as tf
import tensorflow_hub as hub
# download model
detector = hub.load("https://tfhub.dev/tensorflow/faster_rcnn/resnet101_v1_640x640/1")
# download image
image = Image.open(requests.get(image_url, stream=True).raw).resize((200, 200))
# convert image to a tensor using `tf.convert_to_tensor`
image_tensor = tf.convert_to_tensor(np.asarray(image))
# model expects an image batch, for single image add an axis with `tf.newaxis`
image_tensor = image_tensor[tf.newaxis, ...]
# run inference
detector_output = detector(image_tensor)
# return class_ids
class_ids = detector_output["detection_classes"]
print(class_ids)
Explanation: Run prediction with the object detection model downloaded from TensorFlow Hub on the test image
End of explanation
! gcloud services enable artifactregistry.googleapis.com
Explanation: Building and pushing the container image
To use a custom container for serving predictions, you must specify a Docker container image that meets the custom container requirements. This section describes how to create the container image running Triton and push it to Google Artifact Registry (GAR) or Google Container Registry (GCR). This tutorial shows how to push the custom container to Artifact Registry.
Setting up Artifact Registry
Enable the Artifact Registry API service for your project.
End of explanation
DOCKER_ARTIFACT_REPO = "triton-prediction-container"
# create a new Docker repository with your region with the description
! gcloud artifacts repositories create {DOCKER_ARTIFACT_REPO} \
    --repository-format=docker \
    --location={REGION} \
    --description="Triton Docker repository"
# verify that your repository was created.
! gcloud artifacts repositories list \
    --location={REGION} \
    --filter="name~"{DOCKER_ARTIFACT_REPO}
Explanation: Create a private Docker repository to push the container images
End of explanation
! gcloud auth configure-docker {REGION}-docker.pkg.dev --quiet
Explanation: Configure authentication to the private repo
Before you push or pull container images, configure Docker to use the gcloud command-line tool to authenticate requests to Artifact Registry for your region.
End of explanation
IMAGE_URI = f"{REGION}-docker.pkg.dev/{PROJECT_ID}/{DOCKER_ARTIFACT_REPO}/{IMAGE_NAME}"
! docker pull $NGC_TRITON_IMAGE_URI
! docker tag $NGC_TRITON_IMAGE_URI $IMAGE_URI
Explanation: Build the image and tag the Artifact Registry path that the image will be pushed to
End of explanation
! docker stop local_object_detector
! docker run -t -d -p 8000:8000 --rm \
    --name=local_object_detector \
    -e AIP_MODE=True \
    $IMAGE_URI \
    --model-repository $MODEL_ARTIFACTS_REPOSITORY
! sleep 10
# check if the triton container is running locally
!docker container ls -f"name=local_object_detector" --no-trunc
Explanation: Run the container locally [optional]
Before pushing the custom container image to Artifact Registry to use it with Vertex AI Predictions, run the container in local environment to verify that the server responds to prediction instances.
To run the container image as a container locally, run the following command:
NOTE: You can ignore error No such container which is thrown when the container is not running.
End of explanation
! curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/v2/health/ready
Explanation: To send the container's server a health check, run the following command. It should return the status code as 200
End of explanation
# request prediction response
! curl -X POST -H "Content-Type: application/octet-stream" \
    -H "Accept: */*" \
    --data-binary @$payload_file \
    localhost:8000/v2/models/object_detector/infer | \
  jq -c '.outputs[] | select(.name == "detection_classes")'
Explanation: To send the container's server a prediction request, run the following command with sample image file as the payload and get prediction responses
End of explanation
! docker stop local_object_detector
Explanation: To stop the container, run the following command:
End of explanation
! docker push $IMAGE_URI
Explanation: Push the container image to Artifact Registry
After testing the container image locally, push the image to Artifact Registry. The Artifact Registry image URI will be used when creating the Vertex AI model resource.
End of explanation
model = aip.Model.upload(
    display_name=MODEL_DISPLAY_NAME,
    serving_container_image_uri=IMAGE_URI,
    artifact_uri=MODEL_ARTIFACTS_REPOSITORY,
    sync=True,
)
model.resource_name
Explanation: Create Vertex AI Model resource
A  Vertex AI Model resource must be created to deploy the model to a Vertex AI Prediction Endpoint. Create a Vertex AI Model resource with the deployment image pointing to the model artifacts. Refer to Vertex AI Prediction guide for creating Vertex AI Model resource with custom container.
End of explanation
endpoint = aip.Endpoint.create(display_name=ENDPOINT_DISPLAY_NAME)
Explanation: Deploy the model to Vertex AI Predictions
Deploying a Vertex AI Prediction Model is a two step process.
Create an Endpoint exposing an external interface to users consuming the model. 
After the Endpoint is ready, deploy multiple versions of a model to the Endpoint. The deployed model runs the custom container image running Triton to serve predictions.
Refer to Vertex AI Predictions guide to Deploy a model using the Vertex AI API for more information about the APIs used in the following cells.
Create an endpoint
Before deploying the model you need to create a Vertex AI Prediction endpoint.
End of explanation
traffic_percentage = 100
machine_type = "n1-standard-4"
accelerator_type = "NVIDIA_TESLA_T4"
accelerator_count = 1
min_replica_count = 1
max_replica_count = 2
model.deploy(
    endpoint=endpoint,
    deployed_model_display_name=MODEL_DISPLAY_NAME,
    machine_type=machine_type,
    min_replica_count=min_replica_count,
    max_replica_count=max_replica_count,
    traffic_percentage=traffic_percentage,
    accelerator_type=accelerator_type,
    accelerator_count=accelerator_count,
    sync=True,
)
endpoint.name
Explanation: Deploy model to an endpoint
After the endpoint is ready, deploy model to the endpoint.The deployed model runs the Triton Server on a GPU node equipped with the NVIDIA Tesla T4 GPUs. Refer to Deploy a model using the Vertex AI API guide for more information.
NOTE: This step can take up to 20 min.
End of explanation
endpoint_name = f"projects/{PROJECT_ID}/locations/{REGION}/endpoints/{endpoint.name}"
Explanation: Invoking the model and getting predictions
To invoke the model through Vertex AI Prediction endpoint, format prediction request using a standard Inference Request JSON Object or a Inference Request JSON Object with a binary extension and submit the request to Vertex AI Prediction REST rawPredict endpoint. 
Instead of predict API, you must use the rawPredict API  because prediction request formats used by Triton are not compatible with the Vertex AI Prediction standard input format.
In the previous section the request body was formatted as a standard Inference Request JSON Object.
You can invoke the Vertex AI Prediction rawPredict endpoint using [Vertex AI SDK](https://googleapis.dev/python/aiplatform/latest/aiplatform_v1/prediction_service.html#:~:text=async-,raw_predict,-(request%3A%20Optional%5BUnion), any HTTP tool or library, including curl.
To use Endpoint in another session: set endpoint as following
endpoint = aip.Endpoint('projects/&lt;project-number&gt;/locations/&lt;region&gt;/endpoints/&lt;endpoint-id&gt;')
End of explanation
# initialize service client
client_options = {"api_endpoint": f"{REGION}-aiplatform.googleapis.com"}
prediction_client = gapic.PredictionServiceClient(client_options=client_options)
Explanation: Calling rawPredict using Vertex AI SDK to get prediction response
Initialize prediction service client
End of explanation
# format payload
http_body = httpbody_pb2.HttpBody(
    data=open(payload_file).read().encode("utf-8"),
    content_type="application/json",
)
# Initialize request argument(s)
request = gapic.RawPredictRequest(endpoint=endpoint_name, http_body=http_body)
Explanation: Format the http request
End of explanation
# Make the prediction request
response = prediction_client.raw_predict(request=request)
result = json.loads(response.data)
Explanation: Make the prediction request
End of explanation
detection_classes = [
    item for item in result["outputs"] if item["name"] == "detection_classes"
][0]
json.dumps(detection_classes)
Explanation: Get detection classes from the output
End of explanation
endpoint_uri = f"https://{REGION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/endpoints/{endpoint.name}:rawPredict"
! curl -X POST \
   -H "Authorization: Bearer $(gcloud auth print-access-token)" \
   -H "Content-Type: application/json"  \
   -H "Accept: */*" \
   $endpoint_uri \
   -d @$payload_file | \
  jq -c '.outputs[] | select(.name == "detection_classes")'
Explanation: Making curl request to get prediction response
Notice the use of rawPredict API endpoint in the URI below
End of explanation
delete_endpoint = True
delete_model = True
delete_bucket = False
delete_image = True
Explanation: Cleaning up
Cleaning up training and deployment resources
To clean up all Google Cloud resources used in this notebook, you can delete the Google Cloud project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial:
Model
Endpoint
Cloud Storage Bucket
Container Images
Set flags for the resource type to be deleted
End of explanation
# Delete the endpoint using the Vertex AI fully qualified identifier for the endpoint
try:
    if delete_endpoint or os.getenv("IS_TESTING"):
        # get endpoint resource
        endpoints = aip.Endpoint.list(
            filter=f"display_name={ENDPOINT_DISPLAY_NAME}", order_by="create_time"
        )
        endpoint = endpoints[0]
        # undeploy models from the endpoint
        print(
            f"Undeploying all deployed models from the endpoint {endpoint.display_name} [{endpoint._gca_resource.name}]"
        )
        endpoint.undeploy_all(sync=True)
        # deleting endpoint
        print(
            f"Deleting endpoint {endpoint.display_name} [{endpoint._gca_resource.name}]"
        )
        aip.Endpoint.delete(endpoint)
        print(f"Deleted endpoint {endpoint.display_name}")
except Exception as e:
    print(e)
Explanation: Undeploy models and Delete endpoints
End of explanation
# Delete the model using the Vertex AI fully qualified identifier for the model
try:
    if delete_model or os.getenv("IS_TESTING"):
        # get model resource
        models = aip.Model.list(
            filter=f"display_name={MODEL_DISPLAY_NAME}", order_by="create_time"
        )
        for model in models:
            # deleting model
            print(f"Deleting model {model.display_name} [{model._gca_resource.name}]")
            aip.Model.delete(model)
            print(f"Deleted model {model.display_name}")
except Exception as e:
    print(e)
Explanation: Deleting models
End of explanation
if (delete_bucket or os.getenv("IS_TESTING")) and "BUCKET_NAME" in globals():
    print(f"Deleting all contents from the bucket {BUCKET_NAME}")
    shell_output = ! gsutil du -as $BUCKET_NAME
    print(
        f"Size of the bucket {BUCKET_NAME} before deleting = {shell_output[0].split()[0]} bytes"
    )
    # uncomment below line to delete contents of the bucket
    # ! gsutil rm -r $BUCKET_NAME
    shell_output = ! gsutil du -as $BUCKET_NAME
    if float(shell_output[0].split()[0]) > 0:
        print(
            "PLEASE UNCOMMENT LINE TO DELETE BUCKET. CONTENT FROM THE BUCKET NOT DELETED"
        )
    print(
        f"Size of the bucket {BUCKET_NAME} after deleting = {shell_output[0].split()[0]} bytes"
    )
Explanation: Delete contents from the staging bucket
NOTE: Everything in this Cloud Storage bucket will be DELETED. Please run it with caution.
End of explanation
gar_images = ! gcloud artifacts docker images list $REGION-docker.pkg.dev/$PROJECT_ID/$DOCKER_ARTIFACT_REPO \
      --filter="package~"$(echo $IMAGE_NAME | sed 's/:.*//') \
      --format="get(package)"
try:
    if delete_image or os.getenv("IS_TESTING"):
        for image in gar_images:
            # delete only if image name starts with valid region
            if image.startswith(f'{REGION}-docker.pkg.dev'):
                print(f"Deleting image {image} including all tags")
                ! gcloud artifacts docker images delete $image --delete-tags --quiet
except Exception as e:
    print(e)
Explanation: Delete images from Artifact Registry
Deletes all the container images created in this tutorial with name defined by variable IMAGE_NAME from the registry. All associated tags are also deleted.
End of explanation
<END_TASK>