mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
* fix: objective conformance * fix: objective conformance * fix: objective conformance * fix: objective conformance * fix: objective conformance
48 KiB
48 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
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"In [ ]:
! pip3 install {USER_FLAG} --upgrade tensorflow
! pip3 install {USER_FLAG} --upgrade google-cloud-aiplatform tensorboard-plugin-profile
! gcloud components update --quietIn [ ]:
# Automatically restart kernel after installs
import os
if not os.getenv("IS_TESTING"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)In [ ]:
import os
PROJECT_ID = ""
# Get your Google Cloud project ID from gcloud
if not os.getenv("IS_TESTING"):
shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID: ", PROJECT_ID)In [ ]:
if PROJECT_ID == "" or PROJECT_ID is None:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
! gcloud config set project {PROJECT_ID}In [ ]:
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")In [ ]:
import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# If on Google Cloud Notebooks, then don't execute this code
if not IS_GOOGLE_CLOUD_NOTEBOOK:
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this notebook locally, replace the string below with the
# path to your service account key and run this cell to authenticate your GCP
# account.
elif not os.getenv("IS_TESTING"):
%env GOOGLE_APPLICATION_CREDENTIALS ''In [ ]:
BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"}
REGION = "us-central1" # @param {type:"string"}In [ ]:
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMPIn [ ]:
! gsutil mb -l $REGION $BUCKET_NAMEIn [ ]:
! gsutil ls -al $BUCKET_NAMEIn [ ]:
import os
import re
import time
from google.cloud import aiplatform
%load_ext tensorboardIn [ ]:
DATASET_NAME = "movielens_100k" # Change to your dataset name.
# Change to your data and schema paths. These are paths to the movielens_100k
# sample data.
TRAINING_DATA_PATH = f"gs://cloud-samples-data/vertex-ai/matching-engine/two-tower/{DATASET_NAME}/training_data/*"
INPUT_SCHEMA_PATH = f"gs://cloud-samples-data/vertex-ai/matching-engine/two-tower/{DATASET_NAME}/input_schema.json"
# URI of the two-tower training Docker image.
LEARNER_IMAGE_URI = "us-docker.pkg.dev/vertex-ai-restricted/builtin-algorithm/two-tower"
# Change to your output location.
OUTPUT_DIR = f"{BUCKET_NAME}/experiment/output"
TRAIN_BATCH_SIZE = 100 # Batch size for training.
NUM_EPOCHS = 3 # Number of epochs for training.
print(f"Dataset name: {DATASET_NAME}")
print(f"Training data path: {TRAINING_DATA_PATH}")
print(f"Input schema path: {INPUT_SCHEMA_PATH}")
print(f"Output directory: {OUTPUT_DIR}")
print(f"Train batch size: {TRAIN_BATCH_SIZE}")
print(f"Number of epochs: {NUM_EPOCHS}")In [ ]:
learning_job_name = f"two_tower_cpu_{DATASET_NAME}_{TIMESTAMP}"
CREATION_LOG = ! gcloud ai custom-jobs create \
--display-name={learning_job_name} \
--worker-pool-spec=machine-type=n1-standard-8,replica-count=1,container-image-uri={LEARNER_IMAGE_URI} \
--region={REGION} \
--args=--training_data_path={TRAINING_DATA_PATH} \
--args=--input_schema_path={INPUT_SCHEMA_PATH} \
--args=--job-dir={OUTPUT_DIR} \
--args=--train_batch_size={TRAIN_BATCH_SIZE} \
--args=--num_epochs={NUM_EPOCHS}
print(CREATION_LOG)In [ ]:
learning_job_name = f"two_tower_gpu_{DATASET_NAME}_{TIMESTAMP}"
config = f"""workerPoolSpecs:
-
machineSpec:
machineType: n1-highmem-4
acceleratorType: NVIDIA_TESLA_K80
acceleratorCount: 1
replicaCount: 1
containerSpec:
imageUri: {LEARNER_IMAGE_URI}
args:
- --training_data_path={TRAINING_DATA_PATH}
- --input_schema_path={INPUT_SCHEMA_PATH}
- --job-dir={OUTPUT_DIR}
- --training_steps_per_epoch=1500
- --eval_steps_per_epoch=1500
"""
!echo $'{config}' > ./config.yaml
CREATION_LOG = ! gcloud ai custom-jobs create \
--display-name={learning_job_name} \
--region={REGION} \
--config=config.yaml
print(CREATION_LOG)In [ ]:
TRAINING_DATA_PATH = f"gs://cloud-samples-data/vertex-ai/matching-engine/two-tower/{DATASET_NAME}/tfrecord/*"
learning_job_name = f"two_tower_cpu_tfrecord_{DATASET_NAME}_{TIMESTAMP}"
CREATION_LOG = ! gcloud ai custom-jobs create \
--display-name={learning_job_name} \
--worker-pool-spec=machine-type=n1-standard-8,replica-count=1,container-image-uri={LEARNER_IMAGE_URI} \
--region={REGION} \
--args=--training_data_path={TRAINING_DATA_PATH} \
--args=--input_schema_path={INPUT_SCHEMA_PATH} \
--args=--job-dir={OUTPUT_DIR} \
--args=--train_batch_size={TRAIN_BATCH_SIZE} \
--args=--num_epochs={NUM_EPOCHS} \
--args=--input_file_format=tfrecord
print(CREATION_LOG)In [ ]:
JOB_ID = re.search(r"(?<=/customJobs/)\d+", CREATION_LOG[1]).group(0)
print(JOB_ID)In [ ]:
# View the job's configuration and state.
STATE = "state: JOB_STATE_PENDING"
while STATE not in ["state: JOB_STATE_SUCCEEDED", "state: JOB_STATE_FAILED"]:
DESCRIPTION = ! gcloud ai custom-jobs describe {JOB_ID} --region={REGION}
STATE = DESCRIPTION[-2]
print(STATE)
time.sleep(60)In [ ]:
TENSORBOARD_DIR = os.path.join(OUTPUT_DIR, "tensorboard")
%tensorboard --logdir {TENSORBOARD_DIR}In [ ]:
! gsutil ls {OUTPUT_DIR}In [ ]:
# The following imports the query (user) encoder model.
MODEL_TYPE = "query"
# Use the following instead to import the candidate (movie) encoder model.
# MODEL_TYPE = 'candidate'
DISPLAY_NAME = f"{DATASET_NAME}_{MODEL_TYPE}" # The display name of the model.
MODEL_NAME = f"{MODEL_TYPE}_model" # Used by the deployment container.In [ ]:
aiplatform.init(
project=PROJECT_ID,
location=REGION,
staging_bucket=BUCKET_NAME,
)
model = aiplatform.Model.upload(
display_name=DISPLAY_NAME,
artifact_uri=OUTPUT_DIR,
serving_container_image_uri="us-central1-docker.pkg.dev/cloud-ml-algos/two-tower/deploy",
serving_container_health_route=f"/v1/models/{MODEL_NAME}",
serving_container_predict_route=f"/v1/models/{MODEL_NAME}:predict",
serving_container_environment_variables={
"MODEL_BASE_PATH": "$(AIP_STORAGE_URI)",
"MODEL_NAME": MODEL_NAME,
},
)In [ ]:
! gcloud ai models list --region={REGION} --filter={DISPLAY_NAME}In [ ]:
endpoint = aiplatform.Endpoint.create(display_name=DATASET_NAME)In [ ]:
model.deploy(
endpoint=endpoint,
machine_type="n1-standard-4",
traffic_split={"0": 100},
deployed_model_display_name=DISPLAY_NAME,
)In [ ]:
# Input items for the query model:
input_items = [
{"data": '{"user_id": ["1"]}', "key": "key1"},
{"data": '{"user_id": ["2"]}', "key": "key2"},
]
# Input items for the candidate model:
# input_items = [{
# 'data' : '{"movie_id": ["1"], "movie_title": ["fake title"]}',
# 'key': 'key1'
# }]
encodings = endpoint.predict(input_items)
print(f"Number of encodings: {len(encodings.predictions)}")
print(encodings.predictions[0]["encoding"])In [ ]:
import json
request = json.dumps({"instances": input_items})
with open("request.json", "w") as writer:
writer.write(f"{request}\n")
ENDPOINT_ID = endpoint.resource_name
! gcloud ai endpoints predict {ENDPOINT_ID} \
--region={REGION} \
--json-request=request.jsonIn [ ]:
QUERY_SAMPLE_PATH = f"gs://cloud-samples-data/vertex-ai/matching-engine/two-tower/{DATASET_NAME}/query_sample.jsonl"
! gsutil cat {QUERY_SAMPLE_PATH}In [ ]:
model.batch_predict(
job_display_name=f"batch_predict_{DISPLAY_NAME}",
gcs_source=[QUERY_SAMPLE_PATH],
gcs_destination_prefix=OUTPUT_DIR,
machine_type="n1-standard-4",
starting_replica_count=1,
)In [ ]:
PARALLEL_TRIAL_COUNT = 4
MAX_TRIAL_COUNT = 8
METRIC = "val_auc"
hyper_tune_job_name = f"hyper_tune_{DATASET_NAME}_{TIMESTAMP}"
config = json.dumps(
{
"displayName": hyper_tune_job_name,
"studySpec": {
"metrics": [{"metricId": METRIC, "goal": "MAXIMIZE"}],
"parameters": [
{
"parameterId": "num_hidden_layers",
"scaleType": "UNIT_LINEAR_SCALE",
"integerValueSpec": {"minValue": 0, "maxValue": 2},
"conditionalParameterSpecs": [
{
"parameterSpec": {
"parameterId": "num_nodes_hidden_layer1",
"scaleType": "UNIT_LOG_SCALE",
"integerValueSpec": {"minValue": 1, "maxValue": 128},
},
"parentIntValues": {"values": [1, 2]},
},
{
"parameterSpec": {
"parameterId": "num_nodes_hidden_layer2",
"scaleType": "UNIT_LOG_SCALE",
"integerValueSpec": {"minValue": 1, "maxValue": 128},
},
"parentIntValues": {"values": [2]},
},
],
},
{
"parameterId": "learning_rate",
"scaleType": "UNIT_LOG_SCALE",
"doubleValueSpec": {"minValue": 0.0001, "maxValue": 1.0},
},
],
"algorithm": "ALGORITHM_UNSPECIFIED",
},
"maxTrialCount": MAX_TRIAL_COUNT,
"parallelTrialCount": PARALLEL_TRIAL_COUNT,
"maxFailedTrialCount": 3,
"trialJobSpec": {
"workerPoolSpecs": [
{
"machineSpec": {
"machineType": "n1-standard-4",
},
"replicaCount": 1,
"containerSpec": {
"imageUri": LEARNER_IMAGE_URI,
"args": [
f"--training_data_path={TRAINING_DATA_PATH}",
f"--input_schema_path={INPUT_SCHEMA_PATH}",
f"--job-dir={OUTPUT_DIR}",
],
},
}
]
},
}
)
! curl -X POST -H "Authorization: Bearer "$(gcloud auth print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d '{config}' https://us-central1-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{REGION}/hyperparameterTuningJobsIn [ ]:
# Delete endpoint resource
endpoint.delete(force=True)
# Delete model resource
model.delete()
# Delete Cloud Storage objects that were created
! gsutil -m rm -r $OUTPUT_DIR
Run in Colab
View on GitHub