mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
22 KiB
22 KiB
In [ ]:
# Copyright 2024 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 --quiet google-cloud-aiplatform \
google-cloud-storage \
kfp \
google-cloud-pipeline-componentsIn [ ]:
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 [ ]:
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
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
from google.cloud import aiplatform
from kfp import compiler, dsl
from kfp.dsl import componentIn [ ]:
PIPELINE_ROOT = "{}/pipeline_root/control".format(BUCKET_URI)In [ ]:
aiplatform.init(project=PROJECT_ID, staging_bucket=BUCKET_URI)In [ ]:
@component
def args_generator_op() -> str:
import json
return json.dumps(
[{"cats": "1", "dogs": "2"}, {"cats": "10", "dogs": "20"}],
sort_keys=True,
)
@component
def print_op(msg: str):
print(msg)
@component
def flip_coin_op() -> str:
"""Flip a coin and return heads or tails randomly."""
import random
result = "heads" if random.randint(0, 1) == 0 else "tails"
return resultIn [ ]:
@dsl.pipeline(
name="control",
pipeline_root=PIPELINE_ROOT,
)
def pipeline(
json_string: str = json.dumps(
[
{
"snakes": "anaconda",
"lizards": "anole",
"bunnies": [{"cottontail": "bugs"}, {"cottontail": "thumper"}],
},
{
"snakes": "cobra",
"lizards": "gecko",
"bunnies": [{"cottontail": "roger"}],
},
{
"snakes": "boa",
"lizards": "iguana",
"bunnies": [
{"cottontail": "fluffy"},
{"fuzzy_lop": "petunia", "cottontail": "peter"},
],
},
],
sort_keys=True,
)
):
flip1 = flip_coin_op()
with dsl.Condition(
flip1.output != "no-such-result", name="alwaystrue"
): # always true
args_generator = args_generator_op()
with dsl.ParallelFor(args_generator.output) as item:
print_op(msg=json_string)
with dsl.Condition(flip1.output == "heads", name="heads"):
print_op(msg=item.cats)
with dsl.Condition(flip1.output == "tails", name="tails"):
print_op(msg=item.dogs)
with dsl.ParallelFor(json_string) as item:
with dsl.Condition(item.snakes == "boa", name="snakes"):
print_op(msg=item.snakes)
print_op(msg=item.lizards)
print_op(msg=item.bunnies)
# it is possible to access sub-items
with dsl.ParallelFor(json_string) as item:
with dsl.ParallelFor(item.bunnies) as item_bunnies:
print_op(msg=item_bunnies.cottontail)In [ ]:
compiler.Compiler().compile(
pipeline_func=pipeline, package_path="control_pipeline.yaml"
)In [ ]:
DISPLAY_NAME = "control"
job = aiplatform.PipelineJob(
display_name=DISPLAY_NAME,
template_path="control_pipeline.yaml",
pipeline_root=PIPELINE_ROOT,
)
job.run()In [ ]:
delete_bucket = False
# Delete the pipeline job
job.delete()
# Delete the locally generated files
! rm control_pipeline.yaml
if delete_bucket:
! gcloud storage rm --recursive $BUCKET_URI