使用 ONNX 格式的 PyTorch 模型進行預測


Open Neural Network Exchange (ONNX) 提供統一格式,可用來表示任何機器學習架構。BigQuery ML 支援 ONNX,可讓您:

  • 使用您偏好的框架訓練模型。
  • 將模型轉換為 ONNX 模型格式。
  • 將 ONNX 模型匯入 BigQuery,並使用 BigQuery ML 進行預測。

本教學課程將說明如何將使用 PyTorch 訓練的 ONNX 模型匯入 BigQuery 資料集,並使用這些模型預測 SQL 查詢。

目標

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

您可以使用 Pricing Calculator 根據預測用量產生預估費用。 新 Google Cloud 使用者可能符合申請免費試用的資格。

完成本文件所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱「清除所用資源」。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  4. Make sure that billing is enabled for your Google Cloud project.

  5. Enable the BigQuery, BigQuery Connection, and Cloud Storage APIs.

    Enable the APIs

  6. 請確認您具備必要權限,才能執行本文所述的任務。
  7. 必要的角色

    如果您建立新專案,就會成為專案擁有者,並獲得完成本教學課程所需的所有必要身分和存取權管理 (IAM) 權限。

    如果您使用的是現有專案,請執行下列操作。

    Make sure that you have the following role or roles on the project:

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      前往「身分與存取權管理」頁面
    2. 選取專案。
    3. 按一下 「授予存取權」
    4. 在「New principals」(新增主體) 欄位中輸入使用者 ID。 通常是 Google 帳戶的電子郵件地址。

    5. 在「請選擇角色」清單中,選取角色。
    6. 如要授予其他角色,請按一下 「Add another role」(新增其他角色),然後新增其他角色。
    7. 按一下 [Save]
    8. 如要進一步瞭解 BigQuery 中的 IAM 權限,請參閱「IAM 權限」。

選用步驟:訓練模型並轉換為 ONNX 格式

以下程式碼範例說明如何將預先訓練的分類模型匯入 PyTorch,以及如何將產生的模型轉換為 ONNX 格式。本教學課程使用儲存在 gs://cloud-samples-data/bigquery/ml/onnx/resnet18.onnx 的預先建構範例模型。如果您使用的是範例模型,則不必完成這些步驟。

建立用於圖片分類的 PyTorch 視覺模型

請使用下列程式碼範例,匯入可接受 BigQuery ML ML.DECODE_IMAGEML.RESIZE_IMAGE 函式傳回的解碼圖片資料的 PyTorch 預先訓練 resnet18 模型。

import torch
import torch.nn as nn

# Define model input format to match the output format of
# ML.DECODE_IMAGE function: [height, width, channels]
dummy_input = torch.randn(1, 224, 224, 3, device="cpu")

# Load a pretrained pytorch model for image classification
model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True)

# Reshape input format from [batch_size, height, width, channels]
# to [batch_size, channels, height, width]
class ReshapeLayer(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        x = x.permute(0, 3, 1, 2)  # reorder dimensions
        return x

class ArgMaxLayer(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
       return torch.argmax(x, dim=1)

final_model = nn.Sequential(
    ReshapeLayer(),
    model,
    nn.Softmax(),
    ArgMaxLayer()
)

將模型轉換為 ONNX 格式

請使用以下範例,使用 torch.onnx 匯出 PyTorch 視覺模型。匯出的 ONNX 檔案名稱為 resnet18.onnx

torch.onnx.export(final_model,            # model being run
                  dummy_input,            # model input
                  "resnet18.onnx",        # where to save the model
                  opset_version=10,       # the ONNX version to export the model to
                  input_names = ['input'],         # the model's input names
                  output_names = ['class_label'])  # the model's output names

將 ONNX 模型上傳至 Cloud Storage

儲存模型後,請執行下列操作:

建立資料集

建立 BigQuery 資料集來儲存機器學習模型。

控制台

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」頁面

  2. 在「Explorer」窗格中,按一下專案名稱。

  3. 依序點選 「View actions」(查看動作) >「Create dataset」(建立資料集)

    「建立資料集」選單選項。

  4. 在「Create dataset」頁面上執行下列操作:

    • 在「Dataset ID」(資料集 ID) 中輸入 bqml_tutorial

    • 在「位置類型」中選取「多區域」,然後選取「美國 (多個美國區域)」

    • 保留其餘預設設定,然後點選「Create dataset」(建立資料集)

bq

如要建立新的資料集,請使用 bq mk 指令搭配 --location 旗標。如需可能參數的完整清單,請參閱 bq mk --dataset 指令參考資料。

  1. 建立名為 bqml_tutorial 的資料集,並將資料位置設為 US,說明為 BigQuery ML tutorial dataset

    bq --location=US mk -d \
     --description "BigQuery ML tutorial dataset." \
     bqml_tutorial

    這個指令採用 -d 捷徑,而不是使用 --dataset 旗標。如果您省略 -d--dataset,該指令預設會建立資料集。

  2. 確認資料集已建立:

    bq ls

API

請呼叫 datasets.insert 方法,搭配已定義的資料集資源

{
  "datasetReference": {
     "datasetId": "bqml_tutorial"
  }
}

BigQuery DataFrames

在嘗試這個範例之前,請先參閱 BigQuery 快速入門:使用 BigQuery DataFrames,按照 BigQuery DataFrames 設定說明進行操作。詳情請參閱 BigQuery DataFrames 參考資料說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定 ADC」。

import google.cloud.bigquery

bqclient = google.cloud.bigquery.Client()
bqclient.create_dataset("bqml_tutorial", exists_ok=True)

將 ONNX 模型匯入 BigQuery

以下步驟說明如何使用 CREATE MODEL 陳述式,將 ONNX 模型範例從 Cloud Storage 匯入資料集。

控制台

  1. 前往 Google Cloud 控制台的「BigQuery Studio」頁面。

    前往 BigQuery Studio

  2. 在查詢編輯器中輸入以下 CREATE MODEL 陳述式。

    CREATE OR REPLACE MODEL `bqml_tutorial.imported_onnx_model`
     OPTIONS (MODEL_TYPE='ONNX',
      MODEL_PATH='BUCKET_PATH')

    請將 BUCKET_PATH 改成上傳至 Cloud Storage 的模型路徑。如果您使用的是範例模型,請將 BUCKET_PATH 替換為下列值:gs://cloud-samples-data/bigquery/ml/onnx/resnet18.onnx

    作業完成後,您會看到類似以下的訊息:Successfully created model named imported_onnx_model

    新模型會顯示在「資源」面板中。模型會以模型圖示來表示:「Resources」面板中的模型圖示。 如果您在「資源」面板中選取新模型,模型相關資訊會顯示在「查詢編輯器」旁邊。

    `imported_onnx_model` 的資訊面板。

bq

  1. 輸入下列 CREATE MODEL 陳述式,即可從 Cloud Storage 匯入 ONNX 模型。

    bq query --use_legacy_sql=false \
    "CREATE OR REPLACE MODEL
      `bqml_tutorial.imported_onnx_model`
    OPTIONS
      (MODEL_TYPE='ONNX',
       MODEL_PATH='BUCKET_PATH')"

    請將 BUCKET_PATH 改成上傳至 Cloud Storage 的模型路徑。如果您使用的是範例模型,請將 BUCKET_PATH 替換為以下值:gs://cloud-samples-data/bigquery/ml/onnx/resnet18.onnx

  2. 匯入模型後,請確認模型是否顯示在資料集中。

    bq ls bqml_tutorial

    輸出結果會與下列內容相似:

    tableId               Type
    --------------------- -------
    imported_onnx_model  MODEL

如要進一步瞭解如何將 ONNX 模型匯入 BigQuery,包括格式和儲存空間需求,請參閱「匯入 ONNX 模型的 CREATE MODEL 陳述式」。

在 BigQuery 中建立物件資料表,以便分析圖片資料

物件資料表是位於 Cloud Storage 中的非結構化資料物件上,唯讀的資料表。物件資料表可讓您分析 BigQuery 中的非結構化資料。

在本教學課程中,您將使用 ML.PREDICT 函式,針對儲存在 Cloud Storage 值區的輸入圖片輸出預測類別標籤。

建立物件資料表時,您必須執行下列操作:

  • 建立 Cloud Storage 值區,並上傳金魚圖片。
  • 建立用於存取物件資料表的 Cloud 資源連線。
  • 將存取權授予資源連線的服務帳戶。

建立值區並上傳圖片

請按照下列步驟建立 Cloud Storage 值區,並上傳金魚的圖片。

控制台

  1. 在 Google Cloud 控制台,前往 Cloud Storage「Buckets」頁面。

    前往「Buckets」(值區) 頁面

  2. 按一下 「Create」(建立)

  3. 在「Create a bucket」(建立值區) 頁面中輸入值區資訊。

    1. 在「開始使用」部分執行下列操作:

      1. 在方塊中輸入 bqml_images

      2. 按一下「繼續」

    2. 在「Choose where to store your data」(選擇資料的儲存位置) 專區中執行下列操作:

      1. 在「位置類型」中,選取「多區域」

      2. 從位置類型選單中選取「美國 (多個美國區域)」

      3. 按一下「繼續」

    3. 在「Choose a storage class for your data」(為資料選擇儲存空間級別) 專區中:

      1. 選取「Set a default class」(設定預設類別)

      2. 選取「標準」

      3. 按一下「繼續」

    4. 在其餘部分,請保留預設值。

  4. 按一下 [建立]。

指令列

輸入下列 gcloud storage buckets create 指令:

gcloud storage buckets create gs://bqml_images --location=us

如果要求成功,指令會傳回以下訊息:

Creating gs://bqml_images/...

將圖片上傳至 Cloud Storage 值區

建立值區後,請下載金魚的圖片,然後上傳至 Cloud Storage 值區。

如要上傳圖片,請完成下列步驟:

控制台

  1. 在 Google Cloud 控制台,前往 Cloud Storage「Buckets」頁面。

    前往「Buckets」(值區) 頁面

  2. 在 bucket 清單中,點按「bqml_images

  3. 在值區的「物件」分頁中,執行下列任一操作:

    • 將檔案從桌面或檔案管理員拖曳到 Google Cloud 主控台的主要窗格。

    • 依序點選「上傳」>「上傳檔案」,在出現的對話方塊中選取要上傳的圖片檔案,然後按一下「開啟」

指令列

輸入下列 gcloud storage cp 指令:

gcloud storage cp OBJECT_LOCATION gs://bqml_images/IMAGE_NAME

更改下列內容:

  • OBJECT_LOCATION:圖片檔案的本機路徑。例如:Desktop/goldfish.jpg
  • IMAGE_NAME:圖片名稱。例如:goldfish.jpg

如果成功,回應會與下列內容類似:

Completed files 1/1 | 164.3kiB/164.3kiB

建立 BigQuery Cloud 資源連線

您必須擁有 Cloud 資源連線,才能連線至稍後在本教學課程中建立的物件資料表

您可以透過雲端資源連結,查詢儲存在 BigQuery 外部的資料,例如儲存在 Cloud Storage 或 Spanner 等 Google Cloud 服務,或 AWS 或 Azure 等第三方來源的資料。這些外部連結會使用 BigQuery Connection API。

請按照下列步驟建立 Cloud 資源連線。

主控台

  1. 前往「BigQuery Studio」頁面。

    前往 BigQuery Studio

  2. 在「Explorer」窗格中,按一下 「Add data」

    「Add data」對話方塊隨即開啟。

  3. 在「Filter By」窗格中的「Data Source Type」部分,選取「Databases」

    或者,您也可以在「Search for data sources」欄位中輸入 Vertex AI

  4. 在「精選資料來源」部分,按一下「Vertex AI」

  5. 按一下「Vertex AI 模型:BigQuery 聯盟」解決方案資訊卡。

  6. 在「連線類型」清單中,選取「Vertex AI 遠端模型、遠端函式和 BigLake (Cloud 資源)」

  7. 在「連線 ID」欄位中輸入 bqml_tutorial

  8. 確認已選取「Multi-region - US」(多區域 - 美國)

  9. 點選「建立連線」

  10. 按一下視窗底部的「前往連線」。或者,您也可以在「Explorer」窗格中展開「External connections」,然後按一下 us.bqml_tutorial

  11. 在「連線資訊」窗格中,複製服務帳戶 ID,您需要這個 ID 才能設定連線的權限。建立連線資源時,BigQuery 會建立專屬的系統服務帳戶,並將該帳戶與連線建立關聯。

bq

  1. 建立連線:

    bq mk --connection --location=US --project_id=PROJECT_ID \
        --connection_type=CLOUD_RESOURCE bqml_tutorial

    PROJECT_ID 替換為您的Google Cloud 專案 ID。--project_id 參數會覆寫預設專案。

    建立連線資源時,BigQuery 會建立專屬的系統服務帳戶,並將該帳戶與連線建立關聯。

    疑難排解:如果您收到下列連線錯誤,請更新 Google Cloud SDK

    Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
    
  2. 擷取並複製服務帳戶 ID,以便在後續步驟中使用:

    bq show --connection PROJECT_ID.us.bqml_tutorial

    輸出結果會與下列內容相似:

    name                          properties
    1234.REGION.CONNECTION_ID {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.iam.gserviceaccount.com"}
    

設定連線存取權

將 Storage 物件管理員角色授予 Cloud 資源連線的服務帳戶。您必須在建立遠端模型端點的專案中授予這個角色。

如要授予角色,請按照下列步驟操作:

  1. 前往「IAM & Admin」(IAM 與管理) 頁面。

    前往「IAM & Admin」(IAM 與管理)

  2. 按一下 「授予存取權」

  3. 在「新增主體」欄位中,輸入先前複製的雲端資源連線服務帳戶 ID。

  4. 在「請選擇角色」欄位中,依序選取「Cloud Storage」和「Storage 物件管理員」

  5. 按一下 [儲存]

建立物件資料表

請按照下列步驟,使用上傳至 Cloud Storage 的金魚圖片,建立名為 goldfish_image_table 的物件資料表。

控制台

  1. 前往「BigQuery Studio」頁面。

    前往 BigQuery Studio

  2. 在查詢編輯器中輸入以下查詢,即可建立物件資料表。

    CREATE EXTERNAL TABLE `bqml_tutorial.goldfish_image_table`
    WITH CONNECTION `us.bqml_tutorial`
    OPTIONS(
    object_metadata = 'SIMPLE',
    uris = ['gs://bqml_images/IMAGE_NAME'],
    max_staleness = INTERVAL 1 DAY,
    metadata_cache_mode = 'AUTOMATIC');

    IMAGE_NAME 替換為圖片檔案名稱,例如 goldfish.jpg

    作業完成後,您會看到類似 This statement created a new table named goldfish_image_table 的訊息。

bq

  1. 輸入下列 CREATE EXTERNAL TABLE 陳述式,即可建立物件資料表。

    bq query --use_legacy_sql=false \
    "CREATE EXTERNAL TABLE `bqml_tutorial.goldfish_image_table`
    WITH CONNECTION `us.bqml_tutorial`
    OPTIONS(
    object_metadata = 'SIMPLE',
    uris = ['gs://bqml_images/IMAGE_NAME'],
    max_staleness = INTERVAL 1 DAY,
    metadata_cache_mode = 'AUTOMATIC')"

    IMAGE_NAME 替換為圖片檔案名稱,例如 goldfish.jpg

  2. 建立物件資料表後,請確認物件資料表是否顯示在資料集中。

    bq ls bqml_tutorial

    輸出結果會與下列內容相似:

    tableId               Type
    --------------------- --------
    goldfish_image_table  EXTERNAL

詳情請參閱「建立物件資料表」。

使用匯入的 ONNX 模型進行預測

您可以使用包含 ML.PREDICT 函式的以下查詢,根據輸入物件表 goldfish_image_table 中的圖像資料進行預測。這項查詢會根據 ImageNet 標籤字典,輸出輸入圖片的預測類別標籤。

在查詢中,需要使用 ML.DECODE_IMAGE 函式解碼圖片資料,以便 ML.PREDICT 進行解讀。系統會呼叫 ML.RESIZE_IMAGE 函式,將圖片重新調整大小,以符合模型輸入的大小 (224 x 224)。

如要進一步瞭解如何在圖片物件資料表上執行推論,請參閱「在圖片物件資料表上執行推論」。

如要根據圖像資料進行預測,請按照下列步驟操作:

控制台

  1. 前往「BigQuery Studio」頁面。

    前往 BigQuery Studio

  2. 在查詢編輯器中輸入以下 ML.PREDICT 查詢。

     SELECT
       class_label
     FROM
       ML.PREDICT(MODEL bqml_tutorial.imported_onnx_model,
         (
         SELECT
           ML.RESIZE_IMAGE(ML.DECODE_IMAGE(DATA),
             224,
             224,
             FALSE) AS input
         FROM
           bqml_tutorial.goldfish_image_table))
     

    查詢結果如下所示:

    ML.PREDICT 查詢的結果

bq

輸入下列 bq query 指令:

bq query --use_legacy_sql=false \
'SELECT
  class_label
FROM
  ML.PREDICT(MODEL `bqml_tutorial.imported_onnx_model`,
    (
    SELECT
      ML.RESIZE_IMAGE(ML.DECODE_IMAGE(DATA),
        224,
        224,
        FALSE) AS input
    FROM
      bqml_tutorial.goldfish_image_table))'

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

刪除專案

控制台

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

gcloud

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

刪除個別資源

如要移除本教學課程中使用的個別資源,請執行下列操作:

  1. 刪除匯入的模型

  2. (選用) 刪除資料集

  3. 刪除 Cloud 資源連線

  4. 刪除 Cloud Storage 值區

後續步驟