Training AmoebaNet-D on Cloud TPU

This tutorial shows you how to train AmoebaNet-D on Cloud TPU. You can apply the same pattern to other TPU-optimized image classification models that use TensorFlow and the ImageNet dataset.

Disclaimer

This tutorial uses a third-party dataset. Google provides no representation, warranty, or other guarantees about the validity, or any other aspects of this dataset.

Model description

The AmoebaNet-D model is one of the image classifier architectures discovered using Evolutionary AutoML. The model is based on results from the AmoebaNet paper: Real, E., Aggarwal, A., Huang, Y. and Le, Q.V., 2018, Regularized Evolution for Image Classifier Architecture Search, arXiv preprint arXiv:1802.01548.

This model uses TPUEstimator —a high-level TensorFlow API—which is the recommended way to build and run a machine learning model on a Cloud TPU.

The API simplifies the model development process by hiding most of the low-level implementation, making it easier to switch between TPU and other platforms such as GPU or CPU.

Before you begin

Before starting this tutorial, check that your Google Cloud Platform project is correctly set up.

  1. Google アカウントにログインします。

    Google アカウントをまだお持ちでない場合は、新しいアカウントを登録します。

  2. GCP プロジェクトを選択または作成します。

    [リソースの管理] ページに移動

  3. プロジェクトに対して課金が有効になっていることを確認します。

    課金を有効にする方法について

  4. Verify that you have sufficient quota to use either TPU devices or Pods.

Set up your resources

This section provides information on setting up Cloud Storage storage, VM, and Cloud TPU resources for tutorials.

Create a Cloud Storage bucket

You need a Cloud Storage bucket to store the data you use to train your model and the training results. The ctpu up tool used in this tutorial sets up default permissions for the Cloud TPU service account. If you want finer-grain permissions, review the access level permissions.

The bucket you create must reside in the same region as your virtual machine (VM) and your Cloud TPU device or Cloud TPU slice (multiple TPU devices) do.

  1. Go to the Cloud Storage page on the GCP Console.

    Go to the Cloud Storage page

  2. Create a new bucket, specifying the following options:

    • A unique name of your choosing.
    • Default storage class: Regional
    • Location: If you want to use a Cloud TPU device, accept the default presented. If you want to use a Cloud TPU Pod slice, you must specify a region where Cloud TPU Pods are available.

Use the ctpu tool

This section demonstrates using the Cloud TPU provisioning tool (ctpu) for creating and managing Cloud TPU project resources. The resources are comprised of a virtual machine (VM) and a Cloud TPU resource that have the same name. These resources must reside in the same region/zone as the bucket you just created.

You can also set up your VM and TPU resources using gcloud commands or through the Cloud Console. For more information, see Managing VM and TPU Resource.

Run ctpu up to create resources

  1. Open a Cloud Shell window.

    Open Cloud Shell

  2. Run ctpu up specifying the flags shown for either a Cloud TPU device or Pod slice. Refer to CTPU Reference for flag options and descriptions.

  3. Set up either a Cloud TPU device or a Pod slice:

TPU Device

Set up a Cloud TPU device:

$ ctpu up 

The following configuration message appears:

ctpu will use the following configuration:

Name: [your TPU's name]
Zone: [your project's zone]
GCP Project: [your project's name]
TensorFlow Version: 1.13
VM:
  Machine Type: [your machine type]
  Disk Size: [your disk size]
  Preemptible: [true or false]
Cloud TPU:
  Size: [your TPU size]
  Preemptible: [true or false]

OK to create your Cloud TPU resources with the above configuration? [Yn]:

Press y to create your Cloud TPU resources.

TPU Pod

Set up a Cloud TPU slice on the VM and the zone you are working in:

$ ctpu up --zone=us-central1-a --tpu-size=v2-32 --disk-size-gb=300 --preemptible --machine-type n1-standard-8 

The following configuration message appears:

ctpu will use the following configuration:

Name: [your TPU's name]
Zone: [your project's zone]
GCP Project: [your project's name]
TensorFlow Version: 1.13
VM:
  Machine Type: [your machine type]
  Disk Size: [your disk size]
  Preemptible: [true or false]
Cloud TPU:
  Size: [your TPU size]
  Preemptible: [true or false]

OK to create your Cloud TPU resources with the above configuration? [Yn]:

Press y to create your Cloud TPU resources.

The ctpu up command creates a virtual machine (VM) and Cloud TPU services.

From this point on, a prefix of (vm)$ means you should run the command on the Compute Engine VM instance.

Verify your Compute Engine VM

When the ctpu up command has finished executing, verify that your shell prompt is username@tpuname, which shows you are logged into your Compute Engine VM.

Prepare the data

Set up the following environment variable, replacing YOUR-BUCKET-NAME with the name of your Cloud Storage bucket:

(vm)$ export STORAGE_BUCKET=gs://YOUR-BUCKET-NAME

The training application expects your training data to be accessible in Cloud Storage. The training application also uses your Cloud Storage bucket to store checkpoints during training.

Training dataset

ImageNet is an image database. The images in the database are organized into a hierarchy, with each node of the hierarchy depicted by hundreds and thousands of images.

This tutorial uses a demonstration version of the full ImageNet dataset, referred to as fake_imagenet. This demonstration version allows you to test the tutorial, while reducing the storage and time requirements typically associated with running a model against the full ImageNet database.

Below are the instructions for using a randomly generated fake dataset to test the model. Alternatively, you can use the full ImageNet dataset.

A DATA_DIR environment variable described below is used to specify which dataset to train on.

The fake dataset is at this location on Cloud Storage:

gs://cloud-tpu-test-datasets/fake_imagenet

Note that the fake dataset is only useful for understanding how to use a Cloud TPU and validating end-to-end performance. The accuracy numbers and saved model will not be meaningful.

(Optional) Set up TensorBoard

TensorBoard offers a suite of tools designed to present TensorFlow data visually. When used for monitoring, TensorBoard can help identify bottlenecks in processing and suggest ways to improve performance.

If you don't need to monitor the model's output at this time, you can skip the TensorBoard setup steps.

If you want to monitor the model's output and performance, follow the guide to setting up TensorBoard.

Run the AmoebaNet-D model with fake_imagenet

Run the training script for either a single Cloud TPU device or Pod as follows:

TPU Device

  1. Run the model with the following flags:

    (vm)$ python amoeba_net.py \
        --tpu=$TPU_NAME \
        --data_dir=gs://cloud-tpu-test-datasets/fake_imagenet \
        --model_dir=${STORAGE_BUCKET}/amoebanet
    
  • --tpu specifies the name of the Cloud TPU. Note that ctpu passes this name to the Compute Engine VM as an environment variable (TPU_NAME).
  • --data_dir specifies the Cloud Storage path for training input. It is set to the fake_imagenet dataset in this example.
  • --model_dir specifies the directory where checkpoints and summaries are stored during model training. If the folder is missing, the program creates one. When using a Cloud TPU, the model_dir must be a Cloud Storage path (gs://...). You can reuse an existing folder to load current checkpoint data and to store additional checkpoints.

For a single Cloud TPU device, the procedure trains the AmoebaNet-D model for 90 epochs and evaluates every fixed number of steps. Using the specified flags, the model should train in about 10 hours.

Since the training and evaluation was done on the fake_dataset, the output results do not reflect actual output that would appear if the training and evaluation was performed on a real dataset.

If you used the fake_dataset to train the model, proceed to clean up.

TPU Pod

は、
  1. Run the model with the following flags:
    (vm)$ python amoeba_net.py \
        --tpu=$TPU_NAME \
        --data_dir=gs://cloud-tpu-test-datasets/fake_imagenet \
        --model_dir=$MODEL_BUCKET \
        --num_cells=6 \
        --image_size=224 \
        --num_epochs=35 \
        --train_batch_size=4096 \
        --eval_batch_size=1000 \
        --lr=10.24 \
        --lr_decay_value=0.88 \
        --num_shards=32 \
        --lr_warmup_epochs=0.35 \
        --mode=train \
        --iterations_per_loop=1000
    

    • --tpu specifies the name of the Cloud TPU. Note that ctpu passes this name to the Compute Engine VM as an environment variable (TPU_NAME).
    • --data_dir specifies the Cloud Storage path for training input. It is set to the fake_imagenet dataset in this example.
    • --model_dir specifies the directory where checkpoints and summaries are stored during model training. If the folder is missing, the program creates one. When using a Cloud TPU, the model_dir must be a Cloud Storage path (gs://...). You can reuse an existing folder to load current checkpoint data and to store additional checkpoints.

The procedure trains AmoebaNet-D model on the fake_imagent dataset to 35 epochs. It should finish in around 4 hours.

The following table shows the recommended flag values for AmoebaNet training on different slice sizes:

v2-32

--num_cells=6 # Total number of cells
--image_size=224 # Size of image, assuming image height and width
--num_epochs=35 # Number of steps use for training
--train_batch_size=4096 # Global (not per-shard) batch size for training
---lr=10.24 # Learning rate
--lr_decay_value=0.88 # Exponential decay rate used in learning rate adjustment
--num_shards=32 # Number of shards (TPU cores)

v2-128

--num_cells=6 # Total number of cells
--image_size=224 # Size of image, assuming image height and width
--num_epochs=60 # Number of steps use for training
--train_batch_size=8192 # Global (not per-shard) batch size for training
---lr=20.48 # Learning rate
--lr_decay_value=0.91 # Exponential decay rate used in learning rate adjustment
--num_shards=128 # Number of shards (TPU cores)

v2-256

--num_cells=6 # Total number of cells
--image_size=224 # Size of image, assuming image height and width
--num_epochs=90 # Number of steps use for training
--train_batch_size=16384 # Global (not per-shard) batch size for training
---lr=40.96 # Learning rate
--lr_decay_value=0.94 # Exponential decay rate used in learning rate adjustment
--num_shards=256 # Number of shards (TPU cores)

Evaluate the trained AmoebaNet-D model

You can also evaluate the above trained model against the fake_dataset validation data.

Note: Since TPUEstimator does not support evaluating accuracy on Cloud TPU Pod slices yet, you need to create a Cloud TPU v2-8 node to run evaluation on. You can do that using the following `ctpu up` command. This will initialize a Compute Engine VM and Cloud TPU in the default zone (us-central1-b).

  1. Start by allocating and starting a new Compute Engine VM and v2-8 Cloud TPU by running ctpu up:
        (vm)$  ctpu up
        
  2. Set up the variables needed to re-run the model and navigate to the model directory:
        (vm)$ export STORAGE_BUCKET=gs://YOUR-BUCKET-NAME
        (vm)$ export MODEL_BUCKET=${STORAGE_BUCKET}/amoebanet
        (vm)$ export PYTHONPATH="$PYTHONPATH:/usr/share/tpu/models"
        (vm)$ cd /usr/share/tpu/models/official/amoeba_net/
        
  3. Run the model evaluation with the following flags:
        (vm)$ python amoeba_net.py \
        --tpu_name=$TPU_NAME \
        --data_dir=gs://cloud-tpu-test-datasets/fake_imagenet \
        --model_dir=$MODEL_BUCKET \
        --num_cells=6 \
        --image_size=224 \
        --train_batch_size=4096 \
        --eval_batch_size=1000 \
        --mode=eval \
        --iterations_per_loop=1000
        

This will generate output similar to the following:

Evaluation results: {'loss': 6.908725, 'top_1_accuracy': 0.001, 'global_step': 10955, 'top_5_accuracy': 0.005}

Since the training and evaluation was done on the fake_dataset, the output results do not reflect actual output that would appear if the training and evaluation was performed on a real dataset.

If you used the fake_dataset to train the model, proceed to clean up.

Using the full Imagenet dataset

This tutorial uses a demonstration version of the full ImageNet dataset, referred to as fake_imagenet. These demonstration versions allow you to test the tutorials, while reducing the storage and time requirements typically associated with running a model against the full ImageNet dataset. If you want to see how the model runs against the full ImageNet dataset, follow these instructions.

You need about 300GB of space available on your local machine or VM to use the full ImageNet dataset. If you use ctpu up to set up your VM, it will allocate 250GB by default. You can increase VM disk size in one of two ways:

  • Specify the --disk-size-gb flag on the ctpu up command line with the size, in GB, that you want allocated.
  • Follow the Compute Engine guide to add a disk to your VM.
    • Set When deleting instance to Delete disk to ensure that the disk is removed when you remove the VM.
    • Make a note of the path to your new disk. For example: /mnt/disks/mnt-dir.

Download and convert the ImageNet data:

  1. Sign up for an ImageNet account. Remember the username and password you used to create the account.

  2. Set up a DATA_DIR environment variable pointing to a path on your Cloud Storage bucket:

    (vm)$ export DATA_DIR=${STORAGE_BUCKET}
    
  3. Download the imagenet_to_gcs.py script from GitHub:

    $ wget https://raw.githubusercontent.com/tensorflow/tpu/master/tools/datasets/imagenet_to_gcs.py
    
  4. Set a SCRATCH_DIR variable to contain the script's working files. The variable must specify a location on your local machine or on your Compute Engine VM. For example, on your local machine:

    $ SCRATCH_DIR=./imagenet_tmp_files
    

    Or if you're processing the data on the VM:

    (vm)$ SCRATCH_DIR=/mnt/disks/mnt-dir/imagenet_tmp_files
    
  5. Run the imagenet_to_gcs.py script to download, format, and upload the ImageNet data to the bucket. Replace [USERNAME] and [PASSWORD] with the username and password you used to create your ImageNet account.

    $ pip install google-cloud-storage
    $ python imagenet_to_gcs.py \
      --project=$PROJECT \
      --gcs_output_path=$DATA_DIR \
      --local_scratch_dir=$SCRATCH_DIR \
      --imagenet_username=[USERNAME] \
      --imagenet_access_key=[PASSWORD]
    

Optionally if the raw data, in JPEG format, has already been downloaded, you can provide a direct raw_data_directory path. If a raw data directory for training or validation data is provided, it should be in the format:

The training subdirectory names (for example, n03062245) are "WordNet IDs" (wnid). The ImageNet API shows the mapping of WordNet IDs to their associated validation labels in the synset_labels.txt file. A synset in this context is a visually-similar group of images.

Note: Downloading and preprocessing the data can take 10 or more hours, depending on your network and computer speed. Do not interrupt the script.

When the script finishes processing, a message like the following appears:

2018-02-17 14:30:17.287989: Finished writing all 1281167 images in data set.

The script produces a series of directories (for both training and validation) of the form:

${DATA_DIR}/train-00000-of-01024
${DATA_DIR}/train-00001-of-01024
 ...
${DATA_DIR}/train-01023-of-01024

and

${DATA_DIR}/validation-00000-of-00128
S{DATA_DIR}/validation-00001-of-00128
 ...
${DATA_DIR}/validation-00127-of-00128

After the data has been uploaded to your Cloud bucket, run your model and set --data_dir=${DATA_DIR}.

If you used the full ImageNet dataset to train the model, proceed to clean up.

Clean up

To avoid incurring charges to your GCP account for the resources used in this topic:

  1. Disconnect from the Compute Engine VM:

    (vm)$ exit
    

    Your prompt should now be user@projectname, showing you are in the Cloud Shell.

  2. In your Cloud Shell, run ctpu delete with the --zone flag you used when you set up the Cloud TPU to delete your Compute Engine VM and your Cloud TPU:

    $ ctpu delete [optional: --zone]
    
  3. Run ctpu status to make sure you have no instances allocated to avoid unnecessary charges for TPU usage. The deletion might take several minutes. A response like the one below indicates there are no more allocated instances:

    2018/04/28 16:16:23 WARNING: Setting zone to "us-central1-b"
    No instances currently exist.
            Compute Engine VM:     --
            Cloud TPU:             --
    
  4. Run gsutil as shown, replacing YOUR-BUCKET-NAME with the name of the Cloud Storage bucket you created for this tutorial:

    $ gsutil rm -r gs://YOUR-BUCKET-NAME
    

What's next

このページは役立ちましたか?評価をお願いいたします。

フィードバックを送信...