mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
* Did required changes in notebook template * Service account permission changed as we don't need admin level access for this notebook * Fixed issue based on PR feedback
31 KiB
31 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 --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"}
LOCATION = "us-central1" # @param {type:"string"}In [ ]:
BUCKET_URI = f"gs://your-bucket-name-{PROJECT_ID}-unique" # @param {type:"string"}In [ ]:
! gsutil mb -l $LOCATION -p $PROJECT_ID $BUCKET_URIIn [ ]:
from google.cloud import aiplatform
aiplatform.init(project=PROJECT_ID, location=LOCATION, staging_bucket=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()
else: # IS_COLAB:
shell_output = ! gcloud projects describe $PROJECT_ID
project_number = shell_output[-1].split(":")[1].strip().replace("'", "")
SERVICE_ACCOUNT = f"{project_number}-compute@developer.gserviceaccount.com"
print("Service Account:", SERVICE_ACCOUNT)In [ ]:
! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_URI
! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_URIIn [ ]:
if IS_COLAB:
! gcloud config set project $PROJECT_IDIn [ ]:
# Enable Artifact Registry API
! gcloud services enable artifactregistry.googleapis.com --quietIn [ ]:
TENSORBOARD_NAME = "your-tensorboard-unique" # @param {type:"string"}In [ ]:
tensorboard = aiplatform.Tensorboard.create(
display_name=TENSORBOARD_NAME, project=PROJECT_ID, location=LOCATION
)
TENSORBOARD_INSTANCE_NAME = tensorboard.resource_name
print("TensorBoard instance name:", TENSORBOARD_INSTANCE_NAME)In [ ]:
import os
DOCKER_REPOSITORY = f"{PROJECT_ID}-repo-unique"
! gcloud services enable artifactregistry.googleapis.com
if os.getenv("IS_TESTING"):
! sudo apt-get update --yes && sudo apt-get --only-upgrade --yes install google-cloud-sdk-cloud-run-proxy google-cloud-sdk-harbourbridge google-cloud-sdk-cbt google-cloud-sdk-gke-gcloud-auth-plugin google-cloud-sdk-kpt google-cloud-sdk-local-extract google-cloud-sdk-minikube google-cloud-sdk-app-engine-java google-cloud-sdk-app-engine-go google-cloud-sdk-app-engine-python google-cloud-sdk-spanner-emulator google-cloud-sdk-bigtable-emulator google-cloud-sdk-nomos google-cloud-sdk-package-go-module google-cloud-sdk-firestore-emulator kubectl google-cloud-sdk-datastore-emulator google-cloud-sdk-app-engine-python-extras google-cloud-sdk-cloud-build-local google-cloud-sdk-kubectl-oidc google-cloud-sdk-anthos-auth google-cloud-sdk-app-engine-grpc google-cloud-sdk-pubsub-emulator google-cloud-sdk-datalab google-cloud-sdk-skaffold google-cloud-sdk google-cloud-sdk-terraform-tools google-cloud-sdk-config-connector
! gcloud components update --quiet
! gcloud artifacts repositories create {DOCKER_REPOSITORY} \
--repository-format=docker \
--location={LOCATION} \
--description="Repository for TensorBoard Custom Training Job" \
--quiet
! gcloud artifacts repositories listIn [ ]:
import sys
IS_COLAB = "google.colab" in sys.modules
if not IS_COLAB:
! gcloud auth configure-docker {LOCATION}-docker.pkg.dev --quietIn [ ]:
PYTHON_PACKAGE_APPLICATION_DIR = "trainer"
!mkdir -p $PYTHON_PACKAGE_APPLICATION_DIRIn [ ]:
%%writefile trainer/task.py
import tensorflow as tf
import argparse
import os
import sys, traceback
from google.cloud.aiplatform.training_utils import cloud_profiler
"""Train an mnist model and use cloud_profiler for profiling."""
def _create_model():
model = tf.keras.models.Sequential(
[
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10),
]
)
return model
def main(args):
print('Loading and preprocessing data ...')
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
print('Creating and training model ...')
model = _create_model()
model.compile(
optimizer="adam",
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=["accuracy"],
)
# Initialize the profiler.
print('Initialize the profiler ...')
try:
cloud_profiler.init()
except:
ex_type, ex_value, ex_traceback = sys.exc_info()
print("*** Unexpected:", ex_type.__name__, ex_value)
traceback.print_tb(ex_traceback, limit=10, file=sys.stdout)
print('The profiler initiated.')
log_dir = "logs"
if 'AIP_TENSORBOARD_LOG_DIR' in os.environ:
log_dir = os.environ['AIP_TENSORBOARD_LOG_DIR']
print('Setting up the TensorBoard callback ...')
tensorboard_callback = tf.keras.callbacks.TensorBoard(
log_dir=log_dir,
histogram_freq=1)
print('Training model ...')
model.fit(
x_train,
y_train,
epochs=args.epochs,
verbose=0,
callbacks=[tensorboard_callback],
)
print('Training completed.')
print('Saving model ...')
model_dir = "model"
if 'AIP_MODEL_DIR' in os.environ:
model_dir = os.environ['AIP_MODEL_DIR']
tf.saved_model.save(model, model_dir)
print('Model saved at ' + model_dir)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--epochs", type=int, default=100, help="Number of epochs to run model."
)
args = parser.parse_args()
main(args)In [ ]:
%%writefile Dockerfile
# Specifies base image and tag
FROM us-docker.pkg.dev/vertex-ai/training/tf-cpu.2-9:latest
WORKDIR /root
# Installs additional packages as you need.
RUN pip3 install google-cloud-aiplatform[cloud_profiler]
RUN pip3 install protobuf==3.20.2
# Copies the trainer code to the docker image.
RUN mkdir /root/trainer
COPY trainer/task.py /root/trainer/task.py
# Sets up the entry point to invoke the trainer.
ENTRYPOINT ["python", "-m", "trainer.task"]In [ ]:
IMAGE_NAME = "tensorboard-custom-container"
IMAGE_URI = f"{LOCATION}-docker.pkg.dev/{PROJECT_ID}/{DOCKER_REPOSITORY}/{IMAGE_NAME}"
! gcloud builds submit --project {PROJECT_ID} --region={LOCATION} --tag {IMAGE_URI} --timeout=60m --quietIn [ ]:
JOB_NAME = "tensorboard-job-unique"
job = aiplatform.CustomContainerTrainingJob(
display_name=JOB_NAME, container_uri=IMAGE_URI
)In [ ]:
base_output_dir = "{}/{}".format(BUCKET_URI, JOB_NAME)
MACHINE_TYPE = "n1-standard-4"
EPOCHS = 2
training_args = [
"--epochs=" + str(EPOCHS),
]
job.run(
args=training_args,
replica_count=1,
machine_type=MACHINE_TYPE,
base_output_dir=base_output_dir,
tensorboard=TENSORBOARD_INSTANCE_NAME,
service_account=SERVICE_ACCOUNT,
)In [ ]:
delete_tensorboard = True
delete_bucket = False
delete_generated_files_after_execution = False
# Delete docker repository.
! gcloud artifacts repositories delete $DOCKER_REPOSITORY --project {PROJECT_ID} --location {LOCATION} --quiet
job.delete()
if delete_tensorboard:
tensorboard.delete()
if delete_bucket and "BUCKET_URI" in globals():
! gsutil -m rm -r $BUCKET_URI
if delete_generated_files_after_execution:
! rm -rf $PYTHON_PACKAGE_APPLICATION_DIR Dockerfile Dockerfile

