Files
model_garden/notebooks/official/datasets/get_started_with_data_labeling.ipynb
T

35 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.

E2E ML on GCP: MLOps stage 1 : formalization: get started with Vertex AI Data Labeling

Colab logo Run in Colab GitHub logo View on GitHub Vertex AI logo Open in Vertex AI Workbench



Overview

This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 1 : data management: get started with Vertex AI Data Labeling service.

Objective

In this tutorial, you learn how to use the Vertex AI Data Labeling service/

This tutorial uses the following Google Cloud ML services:

  • Vertex AI Data Labeling
  • Vertex AI Dataset

The steps performed include:

  • Create a Specialist Pool for data labelers.
  • Create a data labeling job.
  • Submit the data labeling job.
  • List data labeling jobs.
  • Cancel a data labeling job.

Learn more about Request a Vertex AI Data Labeling job.

Dataset

The dataset used for this tutorial is the Flowers dataset from TensorFlow Datasets. The version of the dataset you use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip.

Costs

This tutorial uses billable components of Google Cloud:

  • Vertex AI
  • Cloud Storage

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

Installation

Install the following packages to execute this notebook.

In [ ]:
import os

# The Vertex AI Workbench Notebook product has specific requirements
IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") and not os.getenv("VIRTUAL_ENV")
IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(
    "/opt/deeplearning/metadata/env_version"
)

# Vertex AI Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_WORKBENCH_NOTEBOOK:
    USER_FLAG = "--user"

# Install the packages
! pip3 install --upgrade google-cloud-aiplatform \
                         google-cloud-storage $USER_FLAG -q

if os.getenv("IS_TESTING"):
    ! pip3 install --upgrade google-api-core==2.10 $USER_FLAG -q

Restart the kernel

Once you've installed the Vertex AI SDK and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.

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

GPU run-time

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 GCP project

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

  1. Select or create a GCP 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 APIs and Compute Engine APIs.

  4. Google Cloud SDK is already installed in Vertex AI Workbench Notebooks.

  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 = "[your-project-id]"  # @param {type:"string"}
In [ ]:
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
    # Get your GCP project id from gcloud
    shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
    PROJECT_ID = shell_output[0]
    print("Project ID:", PROJECT_ID)
In [ ]:
! gcloud config set project $PROJECT_ID

Region

You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.

  • Americas: us-central1
  • Europe: europe-west4
  • Asia Pacific: asia-east1

You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.

Learn more about Vertex AI regions.

In [ ]:
REGION = "[your-region]"  # @param {type: "string"}

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

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 onto the name of resources which will be created in this tutorial.

In [ ]:
from datetime import datetime

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

Email

You need an email address to send labeling job request to. This is the email address will be the manager of the data labeling specialist pool.

In this tutorial, if you don't specify an email address, the email address associated with your project ID will be used.

In [ ]:
EMAIL = "[your-email-address]"  # @param {type: "string"}
In [ ]:
if EMAIL == "[your-email-address]":
    shell_output = ! gcloud auth list 2>/dev/null
    EMAIL = shell_output[2].replace("*", "").strip()

print(EMAIL)

Authenticate your Google Cloud account

If you are using Vertex AI Workbench Notebooks, your environment is already authenticated.

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

import os
import sys

# If on Vertex AI Workbench, then don't execute this code
IS_COLAB = False
if not os.path.exists("/opt/deeplearning/metadata/env_version") and not os.getenv(
    "DL_ANACONDA_HOME"
):
    if "google.colab" in sys.modules:
        IS_COLAB = True
        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.

This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.

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

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

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

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

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

In [ ]:
! gsutil ls -al $BUCKET_URI

Set up variables

Next, set up some variables used throughout the tutorial.

Import libraries and define constants

Import Vertex AI SDK

Import the Vertex AI SDK into our Python environment.

In [ ]:
import os
import sys
import time

import google.cloud.aiplatform as aip
from google.cloud import storage
from google.cloud.aiplatform import gapic
from google.protobuf.json_format import ParseDict
from google.protobuf.struct_pb2 import Value

Initialize Vertex AI SDK for Python

Initialize the Vertex AI SDK for Python for your project and corresponding bucket.

In [ ]:
aip.init(project=PROJECT_ID, location=REGION)

Vertex AI constants

Setup up the following constants for Vertex AI:

  • API_ENDPOINT: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services.
  • PARENT: The Vertex AI location root path for dataset, model and endpoint resources.
In [ ]:
# API Endpoint
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)

# Vertex AI location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION

Schema constants

Next, setup constants for schemas related image classification datasets:

  • Data Labeling (Annotations) Schemas: Tells the managed dataset service how the data is labeled (annotated).
In [ ]:
# Image labeling task
LABELING_SCHEMA_IMAGE = "gs://google-cloud-aiplatform/schema/datalabelingjob/inputs/image_classification_1.0.0.yaml"

Create clients

The Vertex AI SDK works as a client/server model. On your side (the Python script) you create a client that sends requests and receives responses from the server (Vertex AI).

You use several clients in this tutorial, so set them all up upfront.

  • Specialist pool service for specialist pools
  • Job Service for data labeling
In [ ]:
# client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}

clients = {}
clients["job"] = gapic.JobServiceClient(client_options=client_options)

# add client for specialist pool
clients["specialist_pool"] = gapic.SpecialistPoolServiceClient(
    client_options=client_options
)

for client in clients.items():
    print(client)

Create a CSV file for examples to label

Next, you will create a CSV file for the examples you are requesting to be labeled.

In this example, the examples to label are images. For each row in the CSV file, you specify the Cloud Storage location of the image to label.

In [ ]:
test_filename = "labeling.csv"
LABELING_FILES = [
    "gs://cloud-samples-data/vision/automl_classification/flowers/daisy/100080576_f52e8ee070_n.jpg",
    "gs://cloud-samples-data/vision/automl_classification/flowers/daisy/102841525_bd6628ae3c.jpg",
]

IMPORT_FILE = BUCKET_URI + "/labeling.csv"

bucket = storage.Client(project=PROJECT_ID).bucket(BUCKET_URI.replace("gs://", ""))

# creating a blob
blob = bucket.blob(blob_name=test_filename)

# creating data variable
data = LABELING_FILES[0] + "\n" + LABELING_FILES[1] + "\n"

# uploading data variable content to bucket
blob.upload_from_string(data, content_type="text/csv")

# printing path of uploaded file
print(IMPORT_FILE)

# printing content of uploaded file
! gsutil cat $IMPORT_FILE

Create a unlabeled dataset

Next, you create a dataset for the data to be labeled.

In [ ]:
dataset = aip.ImageDataset.create("labeling_" + TIMESTAMP)
print(dataset)

Import the unlabeled data

Now, import the unlabeled data to the dataset, i.e., the examples to be labeled.

In [ ]:
dataset.import_data(
    gcs_source=[IMPORT_FILE],
    import_schema_uri=aip.schema.dataset.ioformat.image.single_label_classification,
)

Create a new data specialist pool

Your data labeling job will be sent to a data specialist pool. You may have one or more multiple specialist pools.

In this next step, you create a new specialist pool with the method create_specialist_pool(). The request includes the parameters:

  • name: The resource name of the specialist pool.
  • display_name: A human readable name for the specialist pool.
  • specialist_manager_emails: A list of the email addresses of the manager(s) for the specialist pool.

Note: You can use an existing specialist pool if one already existed.

In [ ]:
specialist_pool = {
    "name": "labeling_" + TIMESTAMP,
    "display_name": "labeling_" + TIMESTAMP,
    "specialist_manager_emails": [EMAIL],
}

request = clients["specialist_pool"].create_specialist_pool(
    parent=PARENT, specialist_pool=specialist_pool
)

result = request.result()
print(result)

specialist_name = result.name

specialist_id = specialist_name.split("/")[-1]

print(specialist_name)

Create data labeling job

Now that you have a specialist pool, you can send a data labeling request using the create_data_labeling_job() method.

Your request will consist of the following:

  • The Vertex AI Dataset with the unlabeled data.
  • Instructions for labeling.
In [ ]:
# create placeholder file for instructions for data labeling
! echo "this is instruction" >> instruction.txt | gsutil cp instruction.txt $BUCKET_URI
In [ ]:
LABLEING_SCHEMA = LABELING_SCHEMA_IMAGE
INSTRUCTION_FILE = BUCKET_URI + "/instruction.txt"

inputs = ParseDict({"annotation_specs": ["rose"]}, Value())

data_labeling_job = {
    "display_name": "labeling_" + TIMESTAMP,
    "datasets": [dataset.resource_name],
    "labeler_count": 1,
    "instruction_uri": INSTRUCTION_FILE,
    "inputs_schema_uri": LABLEING_SCHEMA,
    "inputs": inputs,
    "annotation_labels": {
        "aiplatform.googleapis.com/annotation_set_name": "data_labeling_job_specialist_pool"
    },
    "specialist_pools": [specialist_name],
}

print(data_labeling_job)

request = clients["job"].create_data_labeling_job(
    parent=PARENT, data_labeling_job=data_labeling_job
)

print(request)

labeling_task_name = request.name

print(labeling_task_name)

Get a data labeling job

You can get information on your data labeling job using the get_data_labeling_job() method, with the following parameters:

  • name: The name of the labeling task.
In [ ]:
request = clients["job"].get_data_labeling_job(name=labeling_task_name)
print(request)

Cancel a data labeling task

You can cancel a data labeling request using the cancel_data_labeling_job() method, with the following parameters:

  • name: The name of the labeling task.
In [ ]:
request = clients["job"].cancel_data_labeling_job(name=labeling_task_name)
print(request)

Wait for labeling job to be canceled

The cancel request is asyncrhonous. The code below polls on the labeling job status until the status is CANCELED.

In [ ]:
while True:
    response = clients["job"].get_data_labeling_job(name=labeling_task_name)
    if response.state == gapic.JobState.JOB_STATE_CANCELLED:
        print("Labeling job CANCELED")
        break
    else:
        print("Canceling labeling job:", response.state)
        time.sleep(60)

Cleaning up

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

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

In [ ]:
# Set this to true only if you'd like to delete your bucket
delete_bucket = False

# Delete the dataset using the Vertex AI fully qualified identifier for the dataset
dataset.delete()

# Delete the labeling job using the Vertex AI fully qualified identifier for the dataset
request = clients["job"].delete_data_labeling_job(name=labeling_task_name)

# Delete the specialist pool using the Vertex AI fully qualified identifier for the dataset
clients["specialist_pool"].delete_specialist_pool(name=specialist_name)

# Delete the bucket created
if delete_bucket or os.getenv("IS_TESTING"):
    ! gsutil rm -r $BUCKET_URI