Files
model_garden/notebooks/notebook_template.ipynb
T
Alec GlassfordandGitHub b078e50cc0 Relax language re: multi-region bucket for training (#142)
I believe you *can* use a multi-region; it just might not work as well (e.g. for latency, cost) as a regional bucket where you are doing other operations. This removes in inaccurate statement.
2021-11-12 11:22:30 -06:00

25 KiB

In [ ]:
# Copyright 2021 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.

Overview

{TODO: Include a paragraph or two explaining what this example demonstrates, who should be interested in it, and what you need to know before you get started.}

Dataset

{TODO: Include a paragraph with Dataset information and where to obtain it.}

{TODO: Make sure the dataset is accessible to the public. Googlers: Add your dataset to the public samples bucket within gs://cloud-samples-data/ai-platform-unified, if it doesn't already exist there.}

Objective

In this notebook, you will learn how to {TODO: Complete the sentence explaining briefly what you will learn from the notebook, such as training, hyperparameter tuning, or serving}:

* {TODO: Add high level bullets for the steps of what you will perform in the notebook}

Costs

{TODO: Update the list of billable products that your tutorial uses.}

This tutorial uses billable components of Google Cloud:

  • Vertex AI
  • Cloud Storage

{TODO: Include links to pricing documentation for each product you listed above.}

Learn about Vertex AI pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage.

Set up your local development environment

If you are using Colab or Google Cloud Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step.

Otherwise, make sure your environment meets this notebook's requirements. You need the following:

  • The Google Cloud SDK
  • Git
  • Python 3
  • virtualenv
  • Jupyter notebook running in a virtual environment with Python 3

The Google Cloud guide to Setting up a Python development environment and the Jupyter installation guide provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions:

  1. Install and initialize the Cloud SDK.

  2. Install Python 3.

  3. Install virtualenv and create a virtual environment that uses Python 3. Activate the virtual environment.

  4. To install Jupyter, run pip3 install jupyter on the command-line in a terminal shell.

  5. To launch Jupyter, run jupyter notebook on the command-line in a terminal shell.

  6. Open this notebook in the Jupyter Notebook Dashboard.

Install additional packages

Install additional package dependencies not installed in your notebook environment, such as {XGBoost, AdaNet, or TensorFlow Hub TODO: Replace with relevant packages for the tutorial}. Use the latest major GA version of each package.

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

Restart the kernel

After you install the additional packages, you need to restart the notebook kernel so it can find the packages.

In [ ]:
# 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)

Before you begin

Select a GPU runtime

Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select "Runtime --> Change runtime type > GPU"

Set up your Google Cloud project

The following steps are required, regardless of your notebook environment.

  1. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.

  2. Make sure that billing is enabled for your project.

  3. Enable the Vertex AI API. {TODO: Update the APIs needed for your tutorial. Edit the API names, and update the link to append the API IDs, separating each one with a comma. For example, container.googleapis.com,cloudbuild.googleapis.com}

  4. If you are running this notebook locally, you will need to install the Cloud SDK.

  5. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook.

Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands.

Set your project ID

If you don't know your project ID, you may be able to get your project ID using gcloud.

In [ ]:
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)

Otherwise, set your project ID here.

In [ ]:
if PROJECT_ID == "" or PROJECT_ID is None:
    PROJECT_ID = "[your-project-id]"  # @param {type:"string"}

Timestamp

If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial.

In [ ]:
from datetime import datetime

TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")

Authenticate your Google Cloud account

If you are using Google Cloud Notebooks, your environment is already authenticated. Skip this step.

If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.

Otherwise, follow these steps:

  1. In the Cloud Console, go to the Create service account key page.

  2. Click Create service account.

  3. In the Service account name field, enter a name, and click Create.

  4. In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex AI" into the filter box, and select Vertex AI Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin.

  5. Click Create. A JSON file that contains your key downloads to your local environment.

  6. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.

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 ''

Create a Cloud Storage bucket

The following steps are required, regardless of your notebook environment.

{TODO: Adjust wording in the first paragraph to fit your use case - explain how your tutorial uses the Cloud Storage bucket. The example below shows how Vertex AI uses the bucket for training.}

When you submit a training job using the Cloud SDK, you upload a Python package containing your training code to a Cloud Storage bucket. Vertex AI runs the code from this package. In this tutorial, Vertex AI also saves the trained model that results from your job in the same bucket. Using this model artifact, you can then create Vertex AI model and endpoint resources in order to serve online predictions.

Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.

You may also change the REGION variable, which is used for operations throughout the rest of this notebook. We suggest that you choose a region where Vertex AI services are available.

In [ ]:
BUCKET_URI = "gs://[your-bucket-name]"  # @param {type:"string"}
REGION = "[your-region]"  # @param {type:"string"}
In [ ]:
if BUCKET_URI == "" or BUCKET_URI is None or BUCKET_URI == "gs://[your-bucket-name]":
    BUCKET_URI = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP

if REGION == "[your-region]":
    REGION = "us-central1"

Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.

In [ ]:
! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI

Finally, validate access to your Cloud Storage bucket by examining its contents:

In [ ]:
! gsutil ls -al $BUCKET_URI

Import libraries and define constants

{TODO: Put all your imports and installs up into a setup section.}

In [ ]:
import os
import sys

import numpy as np
import tensorflow as tf

General style examples

Notebook heading

  • Include the collapsed license at the top (this uses Colab's "Form" mode to hide the cells).
  • Only include a single H1 title.
  • Include the button-bar immediately under the H1.
  • Check that the Colab and GitHub links at the top are correct.

Notebook sections

  • Use H2 (##) and H3 (###) titles for notebook section headings.
  • Use sentence case to capitalize titles and headings. ("Train the model" instead of "Train the Model")
  • Include a brief text explanation before any code cells.
  • Use short titles/headings: "Download the data", "Build the model", "Train the model".

Writing style

  • Use present tense. ("You receive a response" instead of "You will receive a response")
  • Use active voice. ("The service processes the request" instead of "The request is processed by the service")
  • Use second person and an imperative style.
    • Correct examples: "Update the field", "You must update the field"
    • Incorrect examples: "Let's update the field", "We'll update the field", "The user should update the field"
  • Googlers: Please follow our branding guidelines.

Code

  • Put all your installs and imports in a setup section.
  • Save the notebook with the Table of Contents open.
  • Write Python 3 compatible code.
  • Follow the Google Python Style guide and write readable code.
  • Keep cells small (max ~20 lines).

TensorFlow code style

Use the highest level API that gets the job done (unless the goal is to demonstrate the low level API). For example, when using Tensorflow:

  • Use TF.keras.Sequential > keras functional api > keras model subclassing > ...

  • Use model.fit > model.train_on_batch > manual GradientTapes.

  • Use eager-style code.

  • Use tensorflow_datasets and tf.data where possible.

Notebook code style examples

  • Notebooks are for people. Write code optimized for clarity.

  • Demonstrate small parts before combining them into something more complex. Like below:

In [ ]:
# Build the model
model = tf.keras.Sequential(
    [
        tf.keras.layers.Dense(10, activation="relu", input_shape=(None, 5)),
        tf.keras.layers.Dense(3),
    ]
)
In [ ]:
# Run the model on a single batch of data, and inspect the output.
result = model(tf.constant(np.random.randn(10, 5), dtype=tf.float32)).numpy()

print("min:", result.min())
print("max:", result.max())
print("mean:", result.mean())
print("shape:", result.shape)
In [ ]:
# Compile the model for training
model.compile(
    optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.categorical_crossentropy
)
  • Keep examples quick. Use small datasets, or small slices of datasets. You don't need to train to convergence, train until it's obvious it's making progress.

  • For a large example, don't try to fit all the code in the notebook. Add python files to tensorflow examples, and in the notebook run: ! pip3 install git+https://github.com/tensorflow/examples

Cleaning up

To clean up all Google Cloud resources used in this project, you can delete the Google Cloud project you used for the tutorial.

Otherwise, you can delete the individual resources you created in this tutorial:

{TODO: Include commands to delete individual resources below}

In [ ]:
# Warning: Setting this to true will delete everything in your bucket
delete_bucket = False

# Delete endpoint resource
! gcloud ai endpoints delete $ENDPOINT_NAME --quiet --region $REGION_NAME

# Delete model resource
! gcloud ai models delete $MODEL_NAME --quiet

# Delete Cloud Storage objects that were created
! gsutil -m rm -r $JOB_DIR

if delete_bucket and "BUCKET_URI" in globals():
    ! gsutil -m rm -r $BUCKET_URI