如何使用預先建立的搜尋空間和訓練程式

本指南說明如何使用 Google 預先建構的搜尋空間和預先建構的訓練器程式碼集 (以 TF-vision 為基礎),執行 MnasNet 和 SpineNet 的 Agent Platform 神經架構搜尋工作。如需端對端範例,請參閱 MnasNet 分類筆記本和 SpineNet 物件偵測筆記本。

準備預先建構訓練器的資料

Agent Platform Neural Architecture Search 預先建構的訓練器,需要 TFRecord 格式的資料,其中包含 tf.train.Example。tf.train.Example 必須包含下列欄位:

'image/encoded': tf.FixedLenFeature(tf.string)
'image/height': tf.FixedLenFeature(tf.int64)
'image/width': tf.FixedLenFeature(tf.int64)

# For image classification only.
'image/class/label': tf.FixedLenFeature(tf.int64)

# For object detection only.
'image/object/bbox/xmin': tf.VarLenFeature(tf.float32)
'image/object/bbox/xmax': tf.VarLenFeature(tf.float32)
'image/object/bbox/ymin': tf.VarLenFeature(tf.float32)
'image/object/bbox/ymax': tf.VarLenFeature(tf.float32)
'image/object/class/label': tf.VarLenFeature(tf.int64)

請按照這裡的操作說明準備 ImageNet 資料。

如要轉換自訂資料,請使用下載的程式碼範例和公用程式隨附的剖析指令碼。如要自訂資料剖析,請修改 tf_vision/dataloaders/*_input.py 檔案。

進一步瞭解TFRecord和tf.train.Example。

定義實驗環境變數

執行實驗前,您需要定義多個環境變數,包括:

  • TRAINER_DOCKER_ID:${USER}_nas_experiment (建議格式)
  • 實驗將使用的訓練和驗證資料集 Cloud Storage 位置。例如 (CoCo 偵測):

    • gs://cloud-samples-data/ai-platform/built-in/image/coco/train*
    • gs://cloud-samples-data/ai-platform/built-in/image/coco/val*
  • 實驗輸出的 Cloud Storage 位置。建議格式:

    • gs://${USER}_nas_experiment
  • REGION:區域,應與實驗輸出 bucket 區域相同。例如:us-central1。

  • PARAM_OVERRIDE:覆寫預先建構訓練器參數的 YAML 檔案。Agent Platform Neural Architecture Search 提供一些預設設定,您可以使用:

PROJECT_ID=PROJECT_ID
TRAINER_DOCKER_ID=TRAINER_DOCKER_ID
LATENCY_CALCULATOR_DOCKER_ID=LATENCY_CALCULATOR_DOCKER_ID
GCS_ROOT_DIR=OUTPUT_DIR
REGION=REGION
PARAM_OVERRIDE=tf_vision/configs/experiments/spinenet_search_gpu.yaml
TRAINING_DATA_PATH=gs://PATH_TO_TRAINING_DATA
VALIDATION_DATA_PATH=gs://PATH_TO_VALIDATION_DATA

建議您選取或修改符合訓練需求的覆寫檔案。請考量下列事項:

  • 您可以設定 --accelerator_type,選擇使用 GPU 或 CPU。如要使用 CPU 執行幾個週期來快速測試,可以設定旗標 --accelerator_type="",並使用設定檔 tf_vision/test_files/fast_nas_detection_spinenet_search_for_testing.yaml。
  • 訓練週期數
  • 訓練執行階段
  • 學習率等超參數

如需控制訓練工作的完整參數清單,請參閱 tf_vision/configs/。以下是主要參數:

task:
  train_data:
    global_batch_size: 80
  validation_data:
    global_batch_size: 16
  init_checkpoint: null
trainer:
  train_steps: 16634
  steps_per_loop: 1386
  optimizer_config:
    learning_rate:
      cosine:
        initial_learning_rate: 0.16
        decay_steps: 16634
      type: 'cosine'
    warmup:
      type: 'linear'
      linear:
        warmup_learning_rate: 0.0067
        warmup_steps: 1386

建立 Cloud Storage bucket,供 Agent Platform Neural Architecture Search 儲存工作輸出內容 (即檢查點):

gcloud storage buckets create $GCS_ROOT_DIR

建構訓練器容器和延遲時間計算工具容器

下列指令會在 Google Cloud 中建構訓練器映像檔,並使用下列 URI:gcr.io/PROJECT_ID/TRAINER_DOCKER_ID,以便在下一個步驟用於 Agent Platform Neural Architecture Search 工作。

python3 vertex_nas_cli.py build \
--project_id=PROJECT_ID \
--trainer_docker_id=TRAINER_DOCKER_ID \
--latency_calculator_docker_id=LATENCY_CALCULATOR_DOCKER_ID \
--trainer_docker_file=tf_vision/nas_multi_trial.Dockerfile \
--latency_calculator_docker_file=tf_vision/latency_computation_using_saved_model.Dockerfile

如要變更搜尋空間和獎勵,請在 Python 檔案中更新,然後重新建構 Docker 映像檔。

在本機測試訓練器

在 Google Cloud 服務中啟動工作需要幾分鐘的時間,因此在本機測試訓練器 Docker 可能會更方便,例如驗證 TFRecord 格式。以 spinenet 搜尋空間為例,您可以在本機執行搜尋工作 (模型會隨機取樣):

# Define the local job output dir.
JOB_DIR="/tmp/iod_${search_space}"

python3 vertex_nas_cli.py search_in_local \
--project_id=PROJECT_ID \
--trainer_docker_id=TRAINER_DOCKER_ID \
--prebuilt_search_space=spinenet \
--use_prebuilt_trainer=True \
--local_output_dir=${JOB_DIR} \
--search_docker_flags \
params_override="tf_vision/test_files/fast_nas_detection_spinenet_search_for_testing.yaml" \
training_data_path=TEST_COCO_TF_RECORD \
validation_data_path=TEST_COCO_TF_RECORD \
model=retinanet

training_data_path 和 validation_data_path 是 TFRecord 的路徑。

在 Google Cloud上啟動第 1 階段搜尋,接著啟動第 2 階段訓練工作

請參閱 MnasNet 分類筆記本和 SpineNet 物件偵測筆記本,查看端對端範例。

  • 您可以設定 --max_parallel_nas_trial 和 --max_nas_trial 旗標來自訂。Agent Platform Neural Architecture Search 會同時啟動 max_parallel_nas_trial 項試驗,並在 max_nas_trial 項試驗後結束。

  • 如果設定 --target_device_latency_ms 旗標,系統會啟動另一個 latency calculator 工作,並使用 --target_device_type 旗標指定的加速器。

  • Agent Platform Neural Architecture Search 控制器會透過 FLAG --nas_params_str,為每項試驗提供新的架構候選建議。

  • 每項試驗都會根據 FLAG nas_params_str 的值建構圖表,並啟動訓練工作。每個試驗也會將其值儲存至 json 檔案 (位於 os.path.join(nas_job_dir, str(trial_id), "nas_params_str.json"))。

設有延遲時間限制的獎勵

MnasNet 分類筆記本顯示了以雲端 CPU 裝置為基礎的延遲限制搜尋範例。

如要搜尋有延遲時間限制的模型,訓練器可以將獎勵回報為準確度和延遲時間的函式。

在共用的原始碼中,獎勵的計算方式如下:

def compute_reward(target_latency, accuracy, inference_latency, weight=0.07):
  """Compute reward from accuracy and latency."""
  speed_ratio = target_latency / inference_latency
  return accuracy * (speed_ratio**weight)

您可以使用 MnasNet 論文第 3 頁中 reward 計算的其他變體。

如要瞭解如何自訂延遲時間計算函式,請參閱 tf_vision/latency_computation_using_saved_model.py。

監控 Agent Platform Neural Architecture Search 工作進度

在 Google Cloud 控制台的工作頁面中,圖表會顯示reward vs. trial number,表格則會顯示各項試驗的獎勵。您可以找出獎勵最高的試驗。

 Google Cloud 控制台的工作詳細資料頁面,顯示試驗獎勵圖表和指標表格。

繪製第 2 階段訓練曲線

完成第 2 階段訓練後,請使用 Cloud Shell 或 Google Cloud TensorBoard,將訓練曲線指向工作目錄,繪製訓練曲線:

在 TensorBoard 中以視覺化方式呈現各步驟的訓練曲線指標。

部署所選模型

如要建立 SavedModel,您可以使用 export_saved_model.py 指令碼搭配 params_override=${GCS_ROOT_DIR}/${TRIAL_ID}/params.yaml。