mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
50 KiB
50 KiB
In [ ]:
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.In [ ]:
! pip3 install --upgrade google-cloud-aiplatform \
google-cloud-pipeline-components \
tensorflow==2.15.1 \
tensorflow-hub -qIn [ ]:
import sys
if "google.colab" in sys.modules:
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)In [ ]:
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()In [ ]:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}In [ ]:
BUCKET_URI = f"gs://your-bucket-name-{PROJECT_ID}-unique" # @param {type:"string"}In [ ]:
! gcloud storage buckets create --location={LOCATION} --project={PROJECT_ID} {BUCKET_URI}In [ ]:
import json
import tensorflow as tf
import tensorflow_hub as hub
from google.cloud import aiplatformIn [ ]:
aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)In [ ]:
DEPLOY_GPU, DEPLOY_NGPU = (None, None)In [ ]:
MACHINE_TYPE = "n1-standard"
VCPU = "4"
DEPLOY_COMPUTE = MACHINE_TYPE + "-" + VCPU
print("Train machine type", DEPLOY_COMPUTE)In [ ]:
! gcloud services enable artifactregistry.googleapis.comIn [ ]:
PRIVATE_REPO = "my-docker-repo"
! gcloud artifacts repositories create {PRIVATE_REPO} --repository-format=docker --location={LOCATION} --description="Docker repository"
! gcloud artifacts repositories listIn [ ]:
! gcloud auth configure-docker {LOCATION}-docker.pkg.dev --quietIn [ ]:
import sys
IS_COLAB = "google.colab" in sys.modules
# Executes in Vertex AI Workbench
if DEPLOY_GPU:
DEPLOY_IMAGE = (
f"{LOCATION}-docker.pkg.dev/"
+ PROJECT_ID
+ f"/{PRIVATE_REPO}"
+ "/tf_serving:gpu"
)
TF_IMAGE = "tensorflow/serving:2.5.4-gpu"
else:
DEPLOY_IMAGE = (
f"{LOCATION}-docker.pkg.dev/"
+ PROJECT_ID
+ f"/{PRIVATE_REPO}"
+ "/tf_serving:cpu"
)
TF_IMAGE = "tensorflow/serving:2.5.4"
if not IS_COLAB:
if DEPLOY_GPU:
! sudo docker pull tensorflow/serving:2.5.4-gpu
else:
! sudo docker pull tensorflow/serving:2.5.4
! docker tag $TF_IMAGE $DEPLOY_IMAGE
! docker push $DEPLOY_IMAGE
else:
# install docker daemon
! apt-get -qq install docker.io
print("Deployment:", DEPLOY_IMAGE, DEPLOY_GPU, DEPLOY_NGPU)In [ ]:
%%bash -s $IS_COLAB $DEPLOY_IMAGE $TF_IMAGE
if [ $1 == "False" ]; then
exit 0
fi
set -x
dockerd -b none --iptables=0 -l warn &
for i in $(seq 5); do [ ! -S "/var/run/docker.sock" ] && sleep 2 || break; done
docker pull $3
docker tag $3 $2
docker push $2
kill $(jobs -p)In [ ]:
tfhub_model = tf.keras.Sequential(
[hub.KerasLayer("https://tfhub.dev/google/imagenet/resnet_v2_101/classification/5")]
)
tfhub_model.build([None, 224, 224, 3])
tfhub_model.summary()In [ ]:
MODEL_DIR = BUCKET_URI + "/model/1"
tfhub_model.save(MODEL_DIR)In [ ]:
CONCRETE_INPUT = "numpy_inputs"
def _preprocess(bytes_input):
decoded = tf.io.decode_jpeg(bytes_input, channels=3)
decoded = tf.image.convert_image_dtype(decoded, tf.float32)
resized = tf.image.resize(decoded, size=(224, 224))
return resized
@tf.function(input_signature=[tf.TensorSpec([None], tf.string)])
def preprocess_fn(bytes_inputs):
decoded_images = tf.map_fn(
_preprocess, bytes_inputs, dtype=tf.float32, back_prop=False
)
return {
CONCRETE_INPUT: decoded_images
} # User needs to make sure the key matches model's input
@tf.function(input_signature=[tf.TensorSpec([None], tf.string)])
def serving_fn(bytes_inputs):
images = preprocess_fn(bytes_inputs)
prob = m_call(**images)
return prob
m_call = tf.function(tfhub_model.call).get_concrete_function(
[tf.TensorSpec(shape=[None, 224, 224, 3], dtype=tf.float32, name=CONCRETE_INPUT)]
)
tf.saved_model.save(tfhub_model, MODEL_DIR, signatures={"serving_default": serving_fn})In [ ]:
loaded = tf.saved_model.load(MODEL_DIR)
serving_input = list(
loaded.signatures["serving_default"].structured_input_signature[1].keys()
)[0]
print("Serving function input:", serving_input)In [ ]:
MODEL_NAME = "example_"
model = aiplatform.Model.upload(
display_name="example_",
artifact_uri=MODEL_DIR[:-2],
serving_container_image_uri=DEPLOY_IMAGE,
serving_container_health_route="/v1/models/" + MODEL_NAME,
serving_container_predict_route="/v1/models/" + MODEL_NAME + ":predict",
serving_container_command=["/usr/bin/tensorflow_model_server"],
serving_container_args=[
"--model_name=" + MODEL_NAME,
"--model_base_path=" + "$(AIP_STORAGE_URI)",
"--rest_api_port=8080",
"--port=8500",
"--file_system_poll_wait_seconds=31540000",
],
serving_container_ports=[8080],
)
print(model)In [ ]:
endpoint = aiplatform.Endpoint.create(
display_name="example_",
project=PROJECT_ID,
location=LOCATION,
labels={"your_key": "your_value"},
)
print(endpoint)In [ ]:
response = endpoint.deploy(
model=model,
deployed_model_display_name="example_",
machine_type=DEPLOY_COMPUTE,
)
print(endpoint)In [ ]:
! gcloud storage cp gs://cloud-ml-data/img/flower_photos/daisy/100080576_f52e8ee070_n.jpg test.jpgIn [ ]:
import base64
with open("test.jpg", "rb") as f:
data = f.read()
b64str = base64.b64encode(data).decode("utf-8")In [ ]:
# The format of each instance should conform to the deployed model's prediction input schema.
instances = [{serving_input: {"b64": b64str}}]
prediction = endpoint.predict(instances=instances)
print(prediction)In [ ]:
# For demonstration purposes, you write the same image (instance[0]) request twice to the JSONL file.
# You receive back two predictions, one for each instance.
with open("test.jsonl", "w") as f:
json.dump(instances[0], f)
f.write("\n")
json.dump(instances[0], f)
! gcloud storage cp test.jsonl {BUCKET_URI}/test.jsonlIn [ ]:
MIN_NODES = 1
MAX_NODES = 1
batch_predict_job = model.batch_predict(
job_display_name="example_",
instances_format="jsonl",
predictions_format="jsonl",
model_parameters=None,
gcs_source=f"{BUCKET_URI}/test.jsonl",
gcs_destination_prefix=f"{BUCKET_URI}/results",
machine_type=DEPLOY_COMPUTE,
accelerator_type=DEPLOY_GPU,
accelerator_count=DEPLOY_NGPU,
starting_replica_count=MIN_NODES,
max_replica_count=MAX_NODES,
sync=False,
)In [ ]:
batch_predict_job.wait()In [ ]:
bp_iter_outputs = batch_predict_job.iter_outputs()
prediction_results = list()
for blob in bp_iter_outputs:
if blob.name.split("/")[-1].startswith("prediction"):
prediction_results.append(blob.name)
tags = list()
for prediction_result in prediction_results:
gfile_name = f"gs://{bp_iter_outputs.bucket.name}/{prediction_result}"
with tf.io.gfile.GFile(name=gfile_name, mode="r") as gfile:
for line in gfile.readlines():
line = json.loads(line)
print(line)
breakIn [ ]:
# set delete_bucket to True to delete your bucket
delete_bucket = False
# undeploy the model from the endpoint
endpoint.undeploy_all()
# delete the endpoint
endpoint.delete()
# delete the model
model.delete()
# delete the batch job
batch_predict_job.delete()
# delete the bucket
if delete_bucket:
! gcloud storage rm --recursive --continue-on-error {BUCKET_URI}