import os
import sys

# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
    USER_FLAG = "--user"
else:
    USER_FLAG = ""

! pip3 install -U google-cloud-aiplatform $USER_FLAG

"""
Explanation: Vertex client library: Hyperparameter tuning image classification model
<table align="left">
  <td>
    <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb">
      <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab
    </a>
  </td>
  <td>
    <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/custom/showcase_hyperparmeter_tuning_image_classification.ipynb">
      <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
      View on GitHub
    </a>
  </td>
</table>
<br/><br/><br/>
Overview
This tutorial demonstrates how to use the Vertex client library for Python to do hyperparameter tuning for a custom image classification model.
Dataset
The dataset used for this tutorial is the CIFAR10 dataset from TensorFlow Datasets. The version of the dataset you will use is built into TensorFlow. The trained model predicts which type of class an image is from ten classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck.
Objective
In this notebook, you learn how to create a hyperparameter tuning job for a custom image classification model from a Python script in a docker container using the Vertex client library. You can alternatively hyperparameter tune models using the gcloud command-line tool or online using the Google Cloud Console.
The steps performed include:

Create an Vertex hyperparameter turning job for training a custom model.
Tune the custom model.
Evaluate the study results.

Costs
This tutorial uses billable components of Google Cloud (GCP):

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 latest version of Vertex client library.
End of explanation
"""


! pip3 install -U google-cloud-storage $USER_FLAG

"""
Explanation: Install the latest GA version of google-cloud-storage library as well.
End of explanation
"""


if not os.getenv("IS_TESTING"):
    # Automatically restart kernel after installs
    import IPython

    app = IPython.Application.instance()
    app.kernel.do_shutdown(True)

"""
Explanation: Restart the kernel
Once you've installed the Vertex client library and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.
End of explanation
"""


PROJECT_ID = "[your-project-id]"  # @param {type:"string"}

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)

! gcloud config set project $PROJECT_ID

"""
Explanation: Before you begin
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.


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


Make sure that billing is enabled for your project.


Enable the Vertex APIs and Compute Engine APIs.


The Google Cloud SDK is already installed in Google Cloud Notebook.


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.
End of explanation
"""


REGION = "us-central1"  # @param {type: "string"}

"""
Explanation: 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. 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. Not all regions provide support for all Vertex services. For the latest support per region, see the Vertex locations documentation
End of explanation
"""


from datetime import datetime

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

"""
Explanation: 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.
End of explanation
"""


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

# If on Google Cloud Notebook, then don't execute this code
if not os.path.exists("/opt/deeplearning/metadata/env_version"):
    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 ''

"""
Explanation: Authenticate your Google Cloud account
If you are using Google Cloud Notebook, 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:
In the Cloud Console, go to the Create service account key page.
Click Create service account.
In the Service account name field, enter a name, and click Create.
In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex" into the filter box, and select Vertex Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin.
Click Create. A JSON file that contains your key downloads to your local environment.
Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.
End of explanation
"""


BUCKET_NAME = "gs://[your-bucket-name]"  # @param {type:"string"}

if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
    BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP

"""
Explanation: Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you submit a custom training job using the Vertex client library, you upload a Python package
containing your training code to a Cloud Storage bucket. Vertex runs
the code from this package. In this tutorial, Vertex also saves the
trained model that results from your job in the same bucket. You can then
create an Endpoint resource based on this output in order to serve
online predictions.
Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization.
End of explanation
"""


! gsutil mb -l $REGION $BUCKET_NAME

"""
Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.
End of explanation
"""


! gsutil ls -al $BUCKET_NAME

"""
Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents:
End of explanation
"""


import time

from google.cloud.aiplatform import gapic as aip
from google.protobuf import json_format
from google.protobuf.json_format import MessageToJson, ParseDict
from google.protobuf.struct_pb2 import Struct, Value

"""
Explanation: Set up variables
Next, set up some variables used throughout the tutorial.
Import libraries and define constants
Import Vertex client library
Import the Vertex client library into our Python environment.
End of explanation
"""


# API service endpoint
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)

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

if os.getenv("IS_TESTING_TRAIN_GPU"):
    TRAIN_GPU, TRAIN_NGPU = (
        aip.AcceleratorType.NVIDIA_TESLA_K80,
        int(os.getenv("IS_TESTING_TRAIN_GPU")),
    )
else:
    TRAIN_GPU, TRAIN_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)

"""
Explanation: Vertex constants
Setup up the following constants for Vertex:

API_ENDPOINT: The Vertex API service endpoint for dataset, model, job, pipeline and endpoint services.
PARENT: The Vertex location root path for dataset, model, job, pipeline and endpoint resources.
End of explanation
"""


if os.getenv("IS_TESTING_TF"):
    TF = os.getenv("IS_TESTING_TF")
else:
    TF = "2-1"

if TF[0] == "2":
    if TRAIN_GPU:
        TRAIN_VERSION = "tf-gpu.{}".format(TF)
    else:
        TRAIN_VERSION = "tf-cpu.{}".format(TF)
else:
    if TRAIN_GPU:
        TRAIN_VERSION = "tf-gpu.{}".format(TF)
    else:
        TRAIN_VERSION = "tf-cpu.{}".format(TF)

TRAIN_IMAGE = "gcr.io/cloud-aiplatform/training/{}:latest".format(TRAIN_VERSION)

print("Training:", TRAIN_IMAGE, TRAIN_GPU, TRAIN_NGPU)

"""
Explanation: Container (Docker) image
Next, we will set the Docker container images for training.


Set the variable TF to the TensorFlow version of the container image. For example, 2-1 would be version 2.1, and 1-15 would be version 1.15. The following list shows some of the pre-built images available:


TensorFlow 1.15

gcr.io/cloud-aiplatform/training/tf-cpu.1-15:latest
gcr.io/cloud-aiplatform/training/tf-gpu.1-15:latest
TensorFlow 2.1
gcr.io/cloud-aiplatform/training/tf-cpu.2-1:latest
gcr.io/cloud-aiplatform/training/tf-gpu.2-1:latest
TensorFlow 2.2
gcr.io/cloud-aiplatform/training/tf-cpu.2-2:latest
gcr.io/cloud-aiplatform/training/tf-gpu.2-2:latest
TensorFlow 2.3
gcr.io/cloud-aiplatform/training/tf-cpu.2-3:latest
gcr.io/cloud-aiplatform/training/tf-gpu.2-3:latest
TensorFlow 2.4
gcr.io/cloud-aiplatform/training/tf-cpu.2-4:latest
gcr.io/cloud-aiplatform/training/tf-gpu.2-4:latest
XGBoost
gcr.io/cloud-aiplatform/training/xgboost-cpu.1-1
Scikit-learn
gcr.io/cloud-aiplatform/training/scikit-learn-cpu.0-23:latest
Pytorch
gcr.io/cloud-aiplatform/training/pytorch-cpu.1-4:latest
gcr.io/cloud-aiplatform/training/pytorch-cpu.1-5:latest
gcr.io/cloud-aiplatform/training/pytorch-cpu.1-6:latest
gcr.io/cloud-aiplatform/training/pytorch-cpu.1-7:latest

For the latest list, see Pre-built containers for training.
End of explanation
"""


if os.getenv("IS_TESTING_TRAIN_MACHINE"):
    MACHINE_TYPE = os.getenv("IS_TESTING_TRAIN_MACHINE")
else:
    MACHINE_TYPE = "n1-standard"

VCPU = "4"
TRAIN_COMPUTE = MACHINE_TYPE + "-" + VCPU
print("Train machine type", TRAIN_COMPUTE)

"""
Explanation: Machine Type
Next, set the machine type to use for training.

Set the variable TRAIN_COMPUTE to configure  the compute resources for the VMs you will use for for training.
machine type
n1-standard: 3.75GB of memory per vCPU.
n1-highmem: 6.5GB of memory per vCPU
n1-highcpu: 0.9 GB of memory per vCPU


vCPUs: number of [2, 4, 8, 16, 32, 64, 96 ]

Note: The following is not supported for training:

standard: 2 vCPUs
highcpu: 2, 4 and 8 vCPUs

Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs.
End of explanation
"""


# client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}


def create_job_client():
    client = aip.JobServiceClient(client_options=client_options)
    return client


def create_model_client():
    client = aip.ModelServiceClient(client_options=client_options)
    return client


clients = {}
clients["job"] = create_job_client()
clients["model"] = create_model_client()

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

"""
Explanation: Tutorial
Now you are ready to start creating your own hyperparameter tuning and training of a custom image classification.
Set up clients
The Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server.
You will use different clients in this tutorial for different steps in the workflow. So set them all up upfront.

Model Service for Model resources.
Job Service for hyperparameter tuning.
End of explanation
"""


if TRAIN_GPU:
    machine_spec = {
        "machine_type": TRAIN_COMPUTE,
        "accelerator_type": TRAIN_GPU,
        "accelerator_count": TRAIN_NGPU,
    }
else:
    machine_spec = {"machine_type": TRAIN_COMPUTE, "accelerator_count": 0}

"""
Explanation: Tuning a model - Hello World
There are two ways you can hyperparameter tune and train a custom model using a container image:


Use a Google Cloud prebuilt container. If you use a prebuilt container, you will additionally specify a Python package to install into the container image. This Python package contains your code for hyperparameter tuning and training a custom model.


Use your own custom container image. If you use your own container, the container needs to contain your code for hyperparameter tuning and training a custom model.


Prepare your hyperparameter tuning job specification
Now that your clients are ready, your first step is to create a Job Specification for your hyperparameter tuning job. The job specification will consist of the following:

trial_job_spec: The specification for the custom job.
worker_pool_spec : The specification of the type of machine(s) you will use for hyperparameter tuning and how many (single or distributed)

python_package_spec : The specification of the Python package to be installed with the pre-built container.


study_spec: The specification for what to tune.

parameters: This is the specification of the hyperparameters that you will tune for the custom training job. It will contain a list of the
metrics: This is the specification on how to evaluate the result of each tuning trial.

Prepare your machine specification
Now define the machine specification for your custom hyperparameter tuning job. This tells Vertex what type of machine instance to provision for the hyperparameter tuning.
  - machine_type: The type of GCP instance to provision -- e.g., n1-standard-8.
  - accelerator_type: The type, if any, of hardware accelerator. In this tutorial if you previously set the variable TRAIN_GPU != None, you are using a GPU; otherwise you will use a CPU.
  - accelerator_count: The number of accelerators.
End of explanation
"""


DISK_TYPE = "pd-ssd"  # [ pd-ssd, pd-standard]
DISK_SIZE = 200  # GB

disk_spec = {"boot_disk_type": DISK_TYPE, "boot_disk_size_gb": DISK_SIZE}

"""
Explanation: Prepare your disk specification
(optional) Now define the disk specification for your custom hyperparameter tuning job. This tells Vertex what type and size of disk to provision in each machine instance for the hyperparameter tuning.

boot_disk_type: Either SSD or Standard. SSD is faster, and Standard is less expensive. Defaults to SSD.
boot_disk_size_gb: Size of disk in GB.
End of explanation
"""


JOB_NAME = "custom_job_" + TIMESTAMP
MODEL_DIR = "{}/{}".format(BUCKET_NAME, JOB_NAME)

if not TRAIN_NGPU or TRAIN_NGPU < 2:
    TRAIN_STRATEGY = "single"
else:
    TRAIN_STRATEGY = "mirror"

EPOCHS = 20
STEPS = 100

DIRECT = True
if DIRECT:
    CMDARGS = [
        "--model-dir=" + MODEL_DIR,
        "--epochs=" + str(EPOCHS),
        "--steps=" + str(STEPS),
        "--distribute=" + TRAIN_STRATEGY,
    ]
else:
    CMDARGS = [
        "--epochs=" + str(EPOCHS),
        "--steps=" + str(STEPS),
        "--distribute=" + TRAIN_STRATEGY,
    ]

worker_pool_spec = [
    {
        "replica_count": 1,
        "machine_spec": machine_spec,
        "disk_spec": disk_spec,
        "python_package_spec": {
            "executor_image_uri": TRAIN_IMAGE,
            "package_uris": [BUCKET_NAME + "/trainer_cifar10.tar.gz"],
            "python_module": "trainer.task",
            "args": CMDARGS,
        },
    }
]

"""
Explanation: Define the worker pool specification
Next, you define the worker pool specification for your custom hyperparameter tuning job. The worker pool specification will consist of the following:

replica_count: The number of instances to provision of this machine type.
machine_spec: The hardware specification.

disk_spec : (optional) The disk storage specification.


python_package: The Python training package to install on the VM instance(s) and which Python module to invoke, along with command line arguments for the Python module.


Let's dive deeper now into the python package specification:
-executor_image_spec: This is the docker image which is configured for your custom hyperparameter tuning job.
-package_uris: This is a list of the locations (URIs) of your python training packages to install on the provisioned instance. The locations need to be in a Cloud Storage bucket. These can be either individual python files or a zip (archive) of an entire package. In the later case, the job service will unzip (unarchive) the contents into the docker image.
-python_module: The Python module (script) to invoke for running the custom hyperparameter tuning job. In this example, you will be invoking trainer.task.py -- note that it was not neccessary to append the .py suffix.
-args: The command line arguments to pass to the corresponding Pythom module. In this example, you will be setting:
  - "--model-dir=" + MODEL_DIR : The Cloud Storage location where to store the model artifacts. There are two ways to tell the hyperparameter tuning script where to save the model artifacts:
      - direct: You pass the Cloud Storage location as a command line argument to your training script (set variable DIRECT = True), or
      - indirect: The service passes the Cloud Storage location as the environment variable AIP_MODEL_DIR to your training script (set variable DIRECT = False). In this case, you tell the service the model artifact location in the job specification.
  - "--epochs=" + EPOCHS: The number of epochs for training.
  - "--steps=" + STEPS: The number of steps (batches) per epoch.
  - "--distribute=" + TRAIN_STRATEGY" : The hyperparameter tuning distribution strategy to use for single or distributed hyperparameter tuning.
     - "single": single device.
     - "mirror": all GPU devices on a single compute instance.
     - "multi": all GPU devices on all compute instances.
End of explanation
"""


study_spec = {
    "metrics": [
        {
            "metric_id": "val_accuracy",
            "goal": aip.StudySpec.MetricSpec.GoalType.MAXIMIZE,
        }
    ],
    "parameters": [
        {
            "parameter_id": "lr",
            "discrete_value_spec": {"values": [0.001, 0.01, 0.1]},
            "scale_type": aip.StudySpec.ParameterSpec.ScaleType.UNIT_LINEAR_SCALE,
        }
    ],
    "algorithm": aip.StudySpec.Algorithm.GRID_SEARCH,
}

"""
Explanation: Create a study specification
Let's start with a simple study. You will just use a single parameter -- the learning rate. Since its just one parameter, it doesn't make much sense to do a random search. Instead, we will do a grid search over a range of values.

metrics:
metric_id: In this example, the objective metric to report back is 'val_accuracy'
goal: In this example, the hyperparameter tuning service will evaluate trials to maximize the value of the objective metric.
parameters: The specification for the hyperparameters to tune.
parameter_id: The name of the hyperparameter that will be passed to the Python package as a command line argument.
scale_type: The scale type determines the resolution the hyperparameter tuning service uses when searching over the search space.
UNIT_LINEAR_SCALE: Uses a resolution that is the same everywhere in the search space.
UNIT_LOG_SCALE: Values close to the bottom of the search space are further away.
UNIT_REVERSE_LOG_SCALE: Values close to the top of the search space are further away.
search space: This is where you will specify the search space of values for the hyperparameter to select for tuning.
integer_value_spec: Specifies an integer range of values between a min_value and max_value.
double_value_spec: Specifies a continuous range of values between a min_value and max_value.
discrete_value_spec: Specifies a list of values.
algorithm: The search method for selecting hyperparameter values per trial:
GRID_SEARCH: Combinatorically search -- which is used in this example.
RANDOM_SEARCH: Random search.
End of explanation
"""


hpt_job = {
    "display_name": JOB_NAME,
    "trial_job_spec": {"worker_pool_specs": worker_pool_spec},
    "study_spec": study_spec,
    "max_trial_count": 6,
    "parallel_trial_count": 1,
}

"""
Explanation: Assemble a hyperparameter tuning job specification
Now assemble the complete description for the custom hyperparameter tuning specification:

display_name: The human readable name you assign to this custom hyperparameter tuning job.
trial_job_spec: The specification for the custom hyperparameter tuning job.
study_spec: The specification for what to tune.
max_trial_count: The maximum number of tuning trials.
parallel_trial_count: How many trials to try in parallel; otherwise, they are done sequentially.
End of explanation
"""


# Make folder for Python hyperparameter tuning script
! rm -rf custom
! mkdir custom

# Add package information
! touch custom/README.md

setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0"
! echo "$setup_cfg" > custom/setup.cfg

setup_py = "import setuptools\n\nsetuptools.setup(\n\n    install_requires=[\n\n        'tensorflow_datasets==1.3.0',\n\n    ],\n\n    packages=setuptools.find_packages())"
! echo "$setup_py" > custom/setup.py

pkg_info = "Metadata-Version: 1.0\n\nName: CIFAR10 image classification\n\nVersion: 0.0.0\n\nSummary: Demostration hyperparameter tuning script\n\nHome-page: www.google.com\n\nAuthor: Google\n\nAuthor-email: aferlitsch@google.com\n\nLicense: Public\n\nDescription: Demo\n\nPlatform: Vertex"
! echo "$pkg_info" > custom/PKG-INFO

# Make the training subfolder
! mkdir custom/trainer
! touch custom/trainer/__init__.py

"""
Explanation: Examine the hyperparameter tuning package
Package layout
Before you start the hyperparameter tuning, you will look at how a Python package is assembled for a custom hyperparameter tuning job. When unarchived, the package contains the following directory/file layout.

PKG-INFO
README.md
setup.cfg
setup.py
trainer
__init__.py
task.py

The files setup.cfg and setup.py are the instructions for installing the package into the operating environment of the Docker image.
The file trainer/task.py is the Python script for executing the custom hyperparameter tuning job. Note, when we referred to it in the worker pool specification, we replace the directory slash with a dot (trainer.task) and dropped the file suffix (.py).
Package Assembly
In the following cells, you will assemble the training package.
End of explanation
"""


%%writefile custom/trainer/task.py
# HP Tuning hello world example

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow.python.client import device_lib
from hypertune import HyperTune
import argparse
import os
import sys
import time
tfds.disable_progress_bar()

parser = argparse.ArgumentParser()
parser.add_argument('--lr', dest='lr',
                    default=0.001, type=float,
                    help='Learning rate.')
parser.add_argument('--epochs', dest='epochs',
                    default=10, type=int,
                    help='Number of epochs.')
parser.add_argument('--steps', dest='steps',
                    default=200, type=int,
                    help='Number of steps per epoch.')
parser.add_argument('--model-dir',
                    dest='model_dir',
                    default='/tmp/saved_model',
                    type=str,
                    help='Model dir.')
parser.add_argument('--distribute', dest='distribute', type=str, default='single',
                    help='distributed training strategy')
args = parser.parse_args()

print('Python Version = {}'.format(sys.version))
print('TensorFlow Version = {}'.format(tf.__version__))
print('TF_CONFIG = {}'.format(os.environ.get('TF_CONFIG', 'Not found')))
print(device_lib.list_local_devices())

# Instantiate the HyperTune reporting object
hpt = HyperTune()

for epoch in range(1, args.epochs+1):
    # mimic metric result at the end of an epoch
    acc = args.lr * epoch
    # save the metric result to communicate back to the HPT service
    hpt.report_hyperparameter_tuning_metric(
        hyperparameter_metric_tag='val_accuracy',
        metric_value=acc,
        global_step=epoch)
    print('epoch: {}, accuracy: {}'.format(epoch, acc))
    time.sleep(1)

"""
Explanation: Task.py contents
In the next cell, you write the contents of the hyperparameter tuning script task.py. I won't go into detail, it's just there for you to browse. In summary:

Passes the hyperparameter values for a trial as a command line argument (parser.add_argument('--lr',...))
Mimics a training loop, where on each loop (epoch) the variable accuracy is set to the loop iteration * the learning rate.
Reports back the objective metric accuracy back to the hyperparameter tuning service using report_hyperparameter_tuning_metric().
End of explanation
"""


! rm -f custom.tar custom.tar.gz
! tar cvf custom.tar custom
! gzip custom.tar
! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_cifar10.tar.gz

"""
Explanation: Store hyperparameter tuning script on your Cloud Storage bucket
Next, you package the hyperparameter tuning folder into a compressed tar ball, and then store it in your Cloud Storage bucket.
End of explanation
"""


def create_hyperparameter_tuning_job(hpt_job):
    response = clients["job"].create_hyperparameter_tuning_job(
        parent=PARENT, hyperparameter_tuning_job=hpt_job
    )
    print("name:", response.name)
    print("display_name:", response.display_name)
    print("state:", response.state)
    print("create_time:", response.create_time)
    print("update_time:", response.update_time)
    return response


response = create_hyperparameter_tuning_job(hpt_job)

"""
Explanation: Reporting back the result of the trial using hypertune
For each trial, your Python script needs to report back to the hyperparameter tuning service the objective metric for which you specified as the criteria for evaluating the trial.
For this example, you will specify in the study specification that the objective metric will be reported back as val_accuracy.
You report back the value of the objective metric using HyperTune. This Python module is used to communicate key/value pairs to the hyperparameter tuning service. To setup this reporting in your Python package, you will add code for the following three steps:

Import the HyperTune module: from hypertune import HyperTune().
At the end of every epoch, write the current value of the objective function to the log as a key/value pair using hpt.report_hyperparameter_tuning_metric(). In this example, the parameters are:
hyperparameter_metric_tag: The name of the objective metric to report back. The name must be identical to the name specified in the study specification.
metric_value: The value of the objective metric to report back to the hyperparameter service.
global_step: The epoch iteration, starting at 0.

Hyperparameter Tune the model
Now start the hyperparameter tuning of your custom model on Vertex. Use this helper function create_hyperparameter_tuning_job, which takes the following parameter:
-hpt_job: The specification for the hyperparameter tuning job.
The helper function calls job client service's create_hyperparameter_tuning_job method, with the following parameters:
-parent: The Vertex location path to Dataset, Model and Endpoint resources.
-hyperparameter_tuning_job: The specification for the hyperparameter tuning job.
You will display a handful of the fields returned in response object, with the two that are of most interest are:
response.name: The Vertex fully qualified identifier assigned to this custom hyperparameter tuning job. You save this identifier for using in subsequent steps.
response.state: The current state of the custom hyperparameter tuning job.
End of explanation
"""


# The full unique ID for the hyperparameter tuning job
hpt_job_id = response.name
# The short numeric ID for the hyperparameter tuning job
hpt_job_short_id = hpt_job_id.split("/")[-1]

print(hpt_job_id)

"""
Explanation: Now get the unique identifier for the hyperparameter tuning job you created.
End of explanation
"""


def get_hyperparameter_tuning_job(name, silent=False):
    response = clients["job"].get_hyperparameter_tuning_job(name=name)
    if silent:
        return response

    print("name:", response.name)
    print("display_name:", response.display_name)
    print("state:", response.state)
    print("create_time:", response.create_time)
    print("update_time:", response.update_time)
    return response


response = get_hyperparameter_tuning_job(hpt_job_id)

"""
Explanation: Get information on a hyperparameter tuning job
Next, use this helper function get_hyperparameter_tuning_job, which takes the following parameter:

name: The Vertex fully qualified identifier for the hyperparameter tuning job.

The helper function calls the job client service's get_hyperparameter_tuning_job method, with the following parameter:

name: The Vertex fully qualified identifier for the hyperparameter tuning job.

If you recall, you got the Vertex fully qualified identifier for the hyperparameter tuning job in the response.name field when you called the create_hyperparameter_tuning_job method, and saved the identifier in the variable hpt_job_id.
End of explanation
"""


while True:
    job_response = get_hyperparameter_tuning_job(hpt_job_id, True)
    if job_response.state != aip.JobState.JOB_STATE_SUCCEEDED:
        print("Study trials have not completed:", job_response.state)
        if job_response.state == aip.JobState.JOB_STATE_FAILED:
            break
    else:
        if not DIRECT:
            MODEL_DIR = MODEL_DIR + "/model"
        print("Study trials have completed")
        break
    time.sleep(60)

"""
Explanation: Wait for tuning to complete
Hyperparameter tuning the above model may take upwards of 20 minutes time.
Once your model is done tuning, you can calculate the actual time it took to tune the model by subtracting end_time from start_time.
For your model, we will need to know the location of the saved models for each trial, which the Python script saved in your local Cloud Storage bucket at MODEL_DIR + '/&lt;trial_number&gt;/saved_model.pb'.
End of explanation
"""


best = (None, None, None, 0.0)
for trial in job_response.trials:
    print(trial)
    # Keep track of the best outcome
    if float(trial.final_measurement.metrics[0].value) > best[3]:
        try:
            best = (
                trial.id,
                float(trial.parameters[0].value),
                float(trial.parameters[1].value),
                float(trial.final_measurement.metrics[0].value),
            )
        except:
            best = (
                trial.id,
                float(trial.parameters[0].value),
                None,
                float(trial.final_measurement.metrics[0].value),
            )

"""
Explanation: Review the results of the study
Now review the results of trials.
End of explanation
"""


print("ID", best[0])
print("Learning Rate", best[1])
print("Decay", best[2])
print("Validation Accuracy", best[3])

"""
Explanation: Best trial
Now look at which trial was the best:
End of explanation
"""


BEST_MODEL_DIR = MODEL_DIR + "/" + best[0] + "/model"

"""
Explanation: Get the Best Model
If you used the method of having the service tell the tuning script where to save the model artifacts (DIRECT = False), then the model artifacts for the best model are saved at:
MODEL_DIR/&lt;best_trial_id&gt;/model
End of explanation
"""


study_spec = {
    "metrics": [
        {
            "metric_id": "val_accuracy",
            "goal": aip.StudySpec.MetricSpec.GoalType.MAXIMIZE,
        }
    ],
    "parameters": [
        {
            "parameter_id": "lr",
            "discrete_value_spec": {"values": [0.001, 0.01, 0.1]},
            "scale_type": aip.StudySpec.ParameterSpec.ScaleType.UNIT_LINEAR_SCALE,
        },
        {
            "parameter_id": "decay",
            "double_value_spec": {"min_value": 1e-6, "max_value": 1e-2},
            "scale_type": aip.StudySpec.ParameterSpec.ScaleType.UNIT_LINEAR_SCALE,
        },
    ],
    "algorithm": aip.StudySpec.Algorithm.RANDOM_SEARCH,
}

"""
Explanation: Tuning a model - CIFAR10
Now that you have seen the overall steps for hyperparameter tuning a custom training job using a Python package that mimics training a model, you will do a new hyperparameter tuning job for a custom training job for a CIFAR10 model.
For this example, you will change two parts:

Specify the CIFAR10 custom hyperparameter tuning Python package.
Specify a study specification specific to the hyperparameters used in the CIFAR10 custom hyperparameter tuning Python package.

Create a study specification
In this study, you will tune for two hyperparameters using the random search algorithm:

learning rate: The search space is a set of discrete values.
learning rate decay: The search space is a continuous range between 1e-6 and 1e-2.

The objective (goal) is to maximize the validation accuracy.
You will run a maximum of six trials.
End of explanation
"""


hpt_job = {
    "display_name": JOB_NAME,
    "trial_job_spec": {"worker_pool_specs": worker_pool_spec},
    "study_spec": study_spec,
    "max_trial_count": 6,
    "parallel_trial_count": 1,
}

"""
Explanation: Assemble a hyperparameter tuning job specification
Now assemble the complete description for the custom hyperparameter tuning specification:

display_name: The human readable name you assign to this custom hyperparameter tuning job.
trial_job_spec: The specification for the custom hyperparameter tuning job.
study_spec: The specification for what to tune.
max_trial_count: The maximum number of tuning trials.
parallel_trial_count: How many trials to try in parallel; otherwise, they are done sequentially.
End of explanation
"""


%%writefile custom/trainer/task.py
# Custom Job for CIFAR10

import tensorflow_datasets as tfds
import tensorflow as tf
from hypertune import HyperTune
import argparse
import os
import sys

# Command Line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--model-dir', dest='model_dir',
                    default=os.getenv('AIP_MODEL_DIR'), type=str, help='Model dir.')
parser.add_argument('--lr', dest='lr',
                    default=0.001, type=float,
                    help='Learning rate.')
parser.add_argument('--decay', dest='decay',
                    default=0.98, type=float,
                    help='Decay rate')
parser.add_argument('--epochs', dest='epochs',
                    default=10, type=int,
                    help='Number of epochs.')
parser.add_argument('--steps', dest='steps',
                    default=200, type=int,
                    help='Number of steps per epoch.')
parser.add_argument('--distribute', dest='distribute', type=str, default='single',
                    help='distributed training strategy')
args = parser.parse_args()


# Scaling CIFAR-10 data from (0, 255] to (0., 1.]
def scale(image, label):
    image = tf.cast(image, tf.float32)
    image /= 255.0
    return image, label


# Download the dataset
datasets = tfds.load(name='cifar10', as_supervised=True)

# Preparing dataset
BUFFER_SIZE = 10000
BATCH_SIZE = 64
train_dataset = datasets['train'].map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
test_dataset = datasets['test'].map(scale).batch(BATCH_SIZE)

# Build the Keras model
def build_and_compile_cnn_model():
  model = tf.keras.Sequential([
      tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(32, 32, 3)),
      tf.keras.layers.MaxPooling2D(),
      tf.keras.layers.Conv2D(32, 3, activation='relu'),
      tf.keras.layers.MaxPooling2D(),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(10, activation='softmax')
  ])
  model.compile(
      loss=tf.keras.losses.sparse_categorical_crossentropy,
      optimizer=tf.keras.optimizers.SGD(learning_rate=args.lr, decay=args.decay),
      metrics=['accuracy'])
  return model


model = build_and_compile_cnn_model()

# Instantiate the HyperTune reporting object
hpt = HyperTune()

# Reporting callback
class HPTCallback(tf.keras.callbacks.Callback):

    def on_epoch_end(self, epoch, logs=None):
        global hpt
        hpt.report_hyperparameter_tuning_metric(
        hyperparameter_metric_tag='val_accuracy',
        metric_value=logs['val_accuracy'],
        global_step=epoch)

# Train the model
model.fit(train_dataset, epochs=5, steps_per_epoch=10, validation_data=test_dataset.take(8),
    callbacks=[HPTCallback()])
model.save(args.model_dir)

"""
Explanation: Task.py contents
In the next cell, you write the contents of the hyperparameter tuning script task.py. I won't go into detail, it's just there for you to browse. In summary:

Parse the command line arguments for the hyperparameter settings for the current trial.
Get the directory where to save the model artifacts from the command line (--model_dir), and if not specified, then from the environment variable AIP_MODEL_DIR.


Download and preprocess the CIFAR10 dataset.
Build a CNN model.
The learning rate and decay hyperparameter values are used during the compile of the model.
A definition of a callback HPTCallback which obtains the validation accuracy at the end of each epoch (on_epoch_end()) and reports it to the hyperparameter tuning service using hpt.report_hyperparameter_tuning_metric().
Train the model with the fit() method and specify a callback which will report the validation accuracy back to the hyperparameter tuning service.
End of explanation
"""


! rm -f custom.tar custom.tar.gz
! tar cvf custom.tar custom
! gzip custom.tar
! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_cifar10.tar.gz

"""
Explanation: Store hyperparameter tuning script on your Cloud Storage bucket
Next, you package the hyperparameter tuning folder into a compressed tar ball, and then store it in your Cloud Storage bucket.
End of explanation
"""


def create_hyperparameter_tuning_job(hpt_job):
    response = clients["job"].create_hyperparameter_tuning_job(
        parent=PARENT, hyperparameter_tuning_job=hpt_job
    )
    print("name:", response.name)
    print("display_name:", response.display_name)
    print("state:", response.state)
    print("create_time:", response.create_time)
    print("update_time:", response.update_time)
    return response


response = create_hyperparameter_tuning_job(hpt_job)

"""
Explanation: Reporting back the result of the trial using hypertune
For each trial, your Python script needs to report back to the hyperparameter tuning service the objective metric for which you specified as the criteria for evaluating the trial.
For this example, you will specify in the study specification that the objective metric will be reported back as val_accuracy.
You report back the value of the objective metric using HyperTune. This Python module is used to communicate key/value pairs to the hyperparameter tuning service. To setup this reporting in your Python package, you will add code for the following three steps:

Import the HyperTune module: from hypertune import HyperTune().
At the end of every epoch, write the current value of the objective function to the log as a key/value pair using hpt.report_hyperparameter_tuning_metric(). In this example, the parameters are:
hyperparameter_metric_tag: The name of the objective metric to report back. The name must be identical to the name specified in the study specification.
metric_value: The value of the objective metric to report back to the hyperparameter service.
global_step: The epoch iteration, starting at 0.

Hyperparameter Tune the model
Now start the hyperparameter tuning of your custom model on Vertex. Use this helper function create_hyperparameter_tuning_job, which takes the following parameter:
-hpt_job: The specification for the hyperparameter tuning job.
The helper function calls job client service's create_hyperparameter_tuning_job method, with the following parameters:
-parent: The Vertex location path to Dataset, Model and Endpoint resources.
-hyperparameter_tuning_job: The specification for the hyperparameter tuning job.
You will display a handful of the fields returned in response object, with the two that are of most interest are:
response.name: The Vertex fully qualified identifier assigned to this custom hyperparameter tuning job. You save this identifier for using in subsequent steps.
response.state: The current state of the custom hyperparameter tuning job.
End of explanation
"""


# The full unique ID for the custom job
hpt_job_id = response.name
# The short numeric ID for the custom job
hpt_job_short_id = hpt_job_id.split("/")[-1]

print(hpt_job_id)

"""
Explanation: Now get the unique identifier for the custom job you created.
End of explanation
"""


def get_hyperparameter_tuning_job(name, silent=False):
    response = clients["job"].get_hyperparameter_tuning_job(name=name)
    if silent:
        return response

    print("name:", response.name)
    print("display_name:", response.display_name)
    print("state:", response.state)
    print("create_time:", response.create_time)
    print("update_time:", response.update_time)
    return response


response = get_hyperparameter_tuning_job(hpt_job_id)

"""
Explanation: Get information on a hyperparameter tuning job
Next, use this helper function get_hyperparameter_tuning_job, which takes the following parameter:

name: The Vertex fully qualified identifier for the hyperparameter tuning job.

The helper function calls the job client service's get_hyperparameter_tuning_job method, with the following parameter:

name: The Vertex fully qualified identifier for the hyperparameter tuning job.

If you recall, you got the Vertex fully qualified identifier for the hyperparameter tuning job in the response.name field when you called the create_hyperparameter_tuning_job method, and saved the identifier in the variable hpt_job_id.
End of explanation
"""


while True:
    job_response = get_hyperparameter_tuning_job(hpt_job_id, True)
    if job_response.state != aip.JobState.JOB_STATE_SUCCEEDED:
        print("Study trials have not completed:", job_response.state)
        if job_response.state == aip.JobState.JOB_STATE_FAILED:
            break
    else:
        if not DIRECT:
            MODEL_DIR = MODEL_DIR + "/model"
        print("Study trials have completed")
        break
    time.sleep(60)

"""
Explanation: Wait for tuning to complete
Hyperparameter tuning the above model may take upwards of 20 minutes time.
Once your model is done tuning, you can calculate the actual time it took to tune the model by subtracting end_time from start_time.
For your model, we will need to know the location of the saved models for each trial, which the Python script saved in your local Cloud Storage bucket at MODEL_DIR + '/&lt;trial_number&gt;/saved_model.pb'.
End of explanation
"""


best = (None, None, None, 0.0)
for trial in job_response.trials:
    print(trial)
    # Keep track of the best outcome
    if float(trial.final_measurement.metrics[0].value) > best[3]:
        try:
            best = (
                trial.id,
                float(trial.parameters[0].value),
                float(trial.parameters[1].value),
                float(trial.final_measurement.metrics[0].value),
            )
        except:
            best = (
                trial.id,
                float(trial.parameters[0].value),
                None,
                float(trial.final_measurement.metrics[0].value),
            )

"""
Explanation: Review the results of the study
Now review the results of trials.
End of explanation
"""


print("ID", best[0])
print("Learning Rate", best[1])
print("Decay", best[2])
print("Validation Accuracy", best[3])

"""
Explanation: Best trial
Now look at which trial was the best:
End of explanation
"""


BEST_MODEL_DIR = MODEL_DIR + "/" + best[0] + "/model"

"""
Explanation: Get the Best Model
If you used the method of having the service tell the tuning script where to save the model artifacts (DIRECT = False), then the model artifacts for the best model are saved at:
MODEL_DIR/&lt;best_trial_id&gt;/model
End of explanation
"""


import tensorflow as tf

model = tf.keras.models.load_model(MODEL_DIR)

"""
Explanation: Load the saved model
Your model is stored in a TensorFlow SavedModel format in a Cloud Storage bucket. Now load it from the Cloud Storage bucket, and then you can do some things, like evaluate the model, and do a prediction.
To load, you use the TF.Keras model.load_model() method passing it the Cloud Storage path where the model is saved -- specified by MODEL_DIR.
End of explanation
"""


import numpy as np
from tensorflow.keras.datasets import cifar10

(_, _), (x_test, y_test) = cifar10.load_data()
x_test = (x_test / 255.0).astype(np.float32)

print(x_test.shape, y_test.shape)

"""
Explanation: Evaluate the model
Now find out how good the model is.
Load evaluation data
You will load the CIFAR10 test (holdout) data from tf.keras.datasets, using the method load_data(). This will return the dataset as a tuple of two elements. The first element is the training data and the second is the test data. Each element is also a tuple of two elements: the image data, and the corresponding labels.
You don't need the training data, and hence why we loaded it as (_, _).
Before you can run the data through evaluation, you need to preprocess it:
x_test:
1. Normalize (rescaling) the pixel data by dividing each pixel by 255. This will replace each single byte integer pixel with a 32-bit floating point number between 0 and 1.
y_test:<br/>
2. The labels are currently scalar (sparse). If you look back at the compile() step in the trainer/task.py script, you will find that it was compiled for sparse labels. So we don't need to do anything more.
End of explanation
"""


model.evaluate(x_test, y_test)

"""
Explanation: Perform the model evaluation
Now evaluate how well the model in the custom job did.
End of explanation
"""


delete_dataset = True
delete_pipeline = True
delete_model = True
delete_endpoint = True
delete_batchjob = True
delete_customjob = True
delete_hptjob = True
delete_bucket = True

# Delete the dataset using the Vertex fully qualified identifier for the dataset
try:
    if delete_dataset and "dataset_id" in globals():
        clients["dataset"].delete_dataset(name=dataset_id)
except Exception as e:
    print(e)

# Delete the training pipeline using the Vertex fully qualified identifier for the pipeline
try:
    if delete_pipeline and "pipeline_id" in globals():
        clients["pipeline"].delete_training_pipeline(name=pipeline_id)
except Exception as e:
    print(e)

# Delete the model using the Vertex fully qualified identifier for the model
try:
    if delete_model and "model_to_deploy_id" in globals():
        clients["model"].delete_model(name=model_to_deploy_id)
except Exception as e:
    print(e)

# Delete the endpoint using the Vertex fully qualified identifier for the endpoint
try:
    if delete_endpoint and "endpoint_id" in globals():
        clients["endpoint"].delete_endpoint(name=endpoint_id)
except Exception as e:
    print(e)

# Delete the batch job using the Vertex fully qualified identifier for the batch job
try:
    if delete_batchjob and "batch_job_id" in globals():
        clients["job"].delete_batch_prediction_job(name=batch_job_id)
except Exception as e:
    print(e)

# Delete the custom job using the Vertex fully qualified identifier for the custom job
try:
    if delete_customjob and "job_id" in globals():
        clients["job"].delete_custom_job(name=job_id)
except Exception as e:
    print(e)

# Delete the hyperparameter tuning job using the Vertex fully qualified identifier for the hyperparameter tuning job
try:
    if delete_hptjob and "hpt_job_id" in globals():
        clients["job"].delete_hyperparameter_tuning_job(name=hpt_job_id)
except Exception as e:
    print(e)

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

"""
Explanation: 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:

Dataset
Pipeline
Model
Endpoint
Batch Job
Custom Job
Hyperparameter Tuning Job
Cloud Storage Bucket
End of explanation
"""


