mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
39 KiB
39 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 [ ]:
import os
! pip3 install --upgrade google-cloud-aiplatform \
google-cloud-pipeline-components --quiet
! pip3 install kfp==2.7.0 --quiet
! pip3 install tensorflow==2.15.1 --quietIn [ ]:
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"}
# Set the project id
! gcloud config set project {PROJECT_ID}
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} {BUCKET_URI}In [ ]:
SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"}In [ ]:
import sys
IS_COLAB = "google.colab" in sys.modules
if (
SERVICE_ACCOUNT == ""
or SERVICE_ACCOUNT is None
or SERVICE_ACCOUNT == "[your-service-account]"
):
# Get your service account from gcloud
if not IS_COLAB:
shell_output = !gcloud auth list 2>/dev/null
SERVICE_ACCOUNT = shell_output[2].replace("*", "").strip()
if IS_COLAB:
shell_output = ! gcloud projects describe $PROJECT_ID
# print("shell_output=", shell_output)
project_number = shell_output[-1].split(":")[1].strip().replace("'", "")
SERVICE_ACCOUNT = f"{project_number}-compute@developer.gserviceaccount.com"
print("Service Account:", SERVICE_ACCOUNT)In [ ]:
! gcloud storage buckets add-iam-policy-binding $BUCKET_URI --member=serviceAccount:{SERVICE_ACCOUNT} --role=roles/storage.objectCreator
! gcloud storage buckets add-iam-policy-binding $BUCKET_URI --member=serviceAccount:{SERVICE_ACCOUNT} --role=roles/storage.objectViewerIn [ ]:
import json
import tensorflow as tf
from google.cloud import aiplatform
from google_cloud_pipeline_components.v1.custom_job import \
create_custom_training_job_from_component
from kfp import compiler, dsl
from kfp.dsl import componentIn [ ]:
aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)In [ ]:
TRAIN_GPU, TRAIN_NGPU = (aiplatform.gapic.AcceleratorType.NVIDIA_TESLA_T4, 1)
DEPLOY_GPU, DEPLOY_NGPU = (None, None)In [ ]:
TF = "2.13".replace(".", "-")
TRAIN_VERSION = "tf-gpu.{}".format(TF)
DEPLOY_VERSION = "tf2-gpu.{}".format(TF)
TRAIN_IMAGE = "{}-docker.pkg.dev/vertex-ai/training/{}.py310:latest".format(
LOCATION.split("-")[0], TRAIN_VERSION
)
DEPLOY_IMAGE = "{}-docker.pkg.dev/vertex-ai/prediction/{}:latest".format(
LOCATION.split("-")[0], DEPLOY_VERSION
)
print("Training:", TRAIN_IMAGE, TRAIN_GPU, TRAIN_NGPU)
print("Deployment:", DEPLOY_IMAGE, DEPLOY_GPU, DEPLOY_NGPU)In [ ]:
TRAIN_COMPUTE = "n1-standard-4"
print("Train machine type", TRAIN_COMPUTE)
DEPLOY_COMPUTE = "n1-standard-4"
print("Deploy machine type", DEPLOY_COMPUTE)In [ ]:
@component(
base_image=TRAIN_IMAGE,
packages_to_install=["tensorflow"],
)
def self_contained_training_component(
model_dir: str,
epochs: int,
) -> str:
import numpy as np
def get_data():
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = (x_train / 255.0).astype(np.float32)
x_test = (x_test / 255.0).astype(np.float32)
return (x_train, y_train, x_test, y_test)
def get_model():
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Flatten
model = Sequential(
[
Flatten(input_shape=(28, 28, 1)),
Dense(128, activation="relu"),
Dense(256, activation="relu"),
Dense(128, activation="relu"),
Dense(10, activation="softmax"),
]
)
model.compile(
optimizer="Adam", loss="sparse_categorical_crossentropy", metrics=["acc"]
)
return model
def train_model(x_train, y_train, model, epochs):
history = model.fit(x_train, y_train, epochs=epochs)
return history
(x_train, y_train, _, _) = get_data()
model = get_model()
train_model(x_train, y_train, model, epochs)
model.save(model_dir)
return model_dir
compiler.Compiler().compile(self_contained_training_component, "demo_component.yaml")In [ ]:
PIPELINE_ROOT = "{}/pipeline_root/machine_settings".format(BUCKET_URI)
CPU_LIMIT = "8" # vCPUs
MEMORY_LIMIT = "8G"
@dsl.pipeline(
name="component-level-set-resources",
description="A simple pipeline that requests component-level machine resource",
pipeline_root=PIPELINE_ROOT,
)
def pipeline(epochs: int, model_dir: str, project: str = PROJECT_ID):
from google_cloud_pipeline_components.types import artifact_types
from google_cloud_pipeline_components.v1.model import ModelUploadOp
from kfp.dsl import importer_node
training_job_task = (
self_contained_training_component(epochs=epochs, model_dir=model_dir)
.set_display_name("self-contained-training")
.set_cpu_limit(CPU_LIMIT)
.set_memory_limit(MEMORY_LIMIT)
.add_node_selector_constraint("NVIDIA_TESLA_T4")
.set_gpu_limit(TRAIN_NGPU)
)
import_unmanaged_model_task = importer_node.importer(
artifact_uri=training_job_task.output,
artifact_class=artifact_types.UnmanagedContainerModel,
metadata={
"containerSpec": {
"imageUri": DEPLOY_IMAGE,
},
},
).after(training_job_task)
_ = ModelUploadOp(
project=project,
display_name="mnist_model",
unmanaged_container_model=import_unmanaged_model_task.outputs["artifact"],
).after(import_unmanaged_model_task)In [ ]:
compiler.Compiler().compile(
pipeline_func=pipeline,
package_path="component_level_settings.yaml",
)
pipeline = aiplatform.PipelineJob(
display_name="component-level-settings",
template_path="component_level_settings.yaml",
pipeline_root=PIPELINE_ROOT,
parameter_values={"model_dir": BUCKET_URI, "epochs": 20, "project": PROJECT_ID},
enable_caching=False,
)
pipeline.run()
! rm -rf component_level_settings.yamlIn [ ]:
PROJECT_NUMBER = pipeline.gca_resource.name.split("/")[1]
print(PROJECT_NUMBER)
def print_pipeline_output(job, output_task_name):
JOB_ID = job.name
print(JOB_ID)
for _ in range(len(job.gca_resource.job_detail.task_details)):
TASK_ID = job.gca_resource.job_detail.task_details[_].task_id
EXECUTE_OUTPUT = (
PIPELINE_ROOT
+ "/"
+ PROJECT_NUMBER
+ "/"
+ JOB_ID
+ "/"
+ output_task_name
+ "_"
+ str(TASK_ID)
+ "/executor_output.json"
)
GCP_RESOURCES = (
PIPELINE_ROOT
+ "/"
+ PROJECT_NUMBER
+ "/"
+ JOB_ID
+ "/"
+ output_task_name
+ "_"
+ str(TASK_ID)
+ "/gcp_resources"
)
EVAL_METRICS = (
PIPELINE_ROOT
+ "/"
+ PROJECT_NUMBER
+ "/"
+ JOB_ID
+ "/"
+ output_task_name
+ "_"
+ str(TASK_ID)
+ "/evaluation_metrics"
)
if tf.io.gfile.exists(EXECUTE_OUTPUT):
! gcloud storage cat $EXECUTE_OUTPUT
return EXECUTE_OUTPUT
elif tf.io.gfile.exists(GCP_RESOURCES):
! gcloud storage cat $GCP_RESOURCES
return GCP_RESOURCES
elif tf.io.gfile.exists(EVAL_METRICS):
! gcloud storage cat $EVAL_METRICS
return EVAL_METRICS
return None
print("self-contained-training")
artifacts = print_pipeline_output(pipeline, "self-contained-training")
print("\n\n")
print("importer")
artifacts = print_pipeline_output(pipeline, "importer")
print("\n\n")
print("model-upload")
artifacts = print_pipeline_output(pipeline, "model-upload")
output = !gcloud storage cat $artifacts
output = json.loads(output[0])
model_id = output["artifacts"]["model"]["artifacts"][0]["metadata"]["resourceName"]
print("\n")
print("MODEL ID", model_id)
print("\n\n")In [ ]:
pipeline.delete()In [ ]:
model = aiplatform.Model(model_id)
model.delete()In [ ]:
custom_job_op = create_custom_training_job_from_component(
self_contained_training_component,
display_name="test-component",
machine_type=TRAIN_COMPUTE,
accelerator_type=TRAIN_GPU.name,
accelerator_count=TRAIN_NGPU,
)In [ ]:
@dsl.pipeline(
name="customjob-set-resources",
description="A simple pipeline that requests customjob-level machine resource",
pipeline_root=PIPELINE_ROOT,
)
def pipeline(
epochs: int, model_dir: str, project: str = PROJECT_ID, region: str = LOCATION
):
from google_cloud_pipeline_components.types import artifact_types
from google_cloud_pipeline_components.v1.model import ModelUploadOp
from kfp.dsl import importer_node
training_job_task = custom_job_op(
epochs=epochs, model_dir=model_dir, project=project, location=LOCATION
)
import_unmanaged_model_task = importer_node.importer(
artifact_uri=training_job_task.outputs["Output"],
artifact_class=artifact_types.UnmanagedContainerModel,
metadata={
"containerSpec": {
"imageUri": DEPLOY_IMAGE,
},
},
).after(training_job_task)
_ = ModelUploadOp(
project=project,
display_name="mnist_model",
unmanaged_container_model=import_unmanaged_model_task.outputs["artifact"],
).after(import_unmanaged_model_task)In [ ]:
compiler.Compiler().compile(
pipeline_func=pipeline,
package_path="customjob_level_settings.yaml",
)
pipeline = aiplatform.PipelineJob(
display_name="customjob-level-settings",
template_path="customjob_level_settings.yaml",
pipeline_root=PIPELINE_ROOT,
parameter_values={"model_dir": BUCKET_URI, "epochs": 20, "project": PROJECT_ID},
enable_caching=False,
)
pipeline.run()
! rm -rf customjob_level_settings.yamlIn [ ]:
print("self-contained-training-component")
artifacts = print_pipeline_output(pipeline, "self-contained-training-component")
print("\n\n")
print("importer")
artifacts = print_pipeline_output(pipeline, "importer")
print("\n\n")
print("model-upload")
artifacts = print_pipeline_output(pipeline, "model-upload")
output = !gcloud storage cat $artifacts
output = json.loads(output[0])
model_id = output["artifacts"]["model"]["artifacts"][0]["metadata"]["resourceName"]
print("\n")
print("MODEL ID", model_id)
print("\n\n")In [ ]:
pipeline.delete()In [ ]:
model = aiplatform.Model(model_id)
model.delete()In [ ]:
# Set this to true only if you'd like to delete your bucket
delete_bucket = False
if delete_bucket:
! gcloud storage rm --recursive $BUCKET_URI
!rm -rf demo_component.yaml