匯出 AutoML Edge 模型

本頁說明如何使用 Vertex AI 將圖像 AutoML Edge 模型匯出至 Cloud Storage。

如要瞭解如何匯出表格型模型,請參閱「匯出 AutoML 表格型模型」。

簡介

訓練 AutoML Edge 模型後,您可以視使用方式,以不同格式匯出模型。匯出的模型檔案會儲存在 Cloud Storage 值區中,並可用於所選環境的預測作業。

您無法在 Vertex AI 中使用 Edge 模型提供預測;您必須將 Edge 模型部署至外部裝置,才能取得預測結果。

匯出模型

使用下列程式碼範例找出 AutoML Edge 模型、指定輸出檔案儲存位置,然後傳送匯出模型要求。

圖片

選取下方分頁標籤,瞭解如何達成目標:

分類

訓練完成的 AutoML Edge 圖片分類模型可以匯出為下列格式:

  • TF Lite - 將模型匯出為 TF Lite 套件,以在邊緣或行動裝置上執行模型。
  • Edge TPU TF Lite - 將模型匯出為 TF Lite 套件,即可在 Edge TPU 裝置上執行模型。
  • 容器 - 將模型匯出為 TF Saved Model,以便在 Docker 容器上執行。
  • Core ML - 匯出 .mlmodel 檔案,以在 iOS 和 macOS 裝置上執行模型。
  • Tensorflow.js - 將模型匯出為 TensorFlow.js 套件,以在瀏覽器或 Node.js 中執行模型。

請選取下方分頁,查看適用於您語言或環境的說明:

控制台

  1. 在 Google Cloud 控制台的 Vertex AI 專區中,前往「Models」頁面。

    前往「模型」頁面

  2. 按一下要匯出的 AutoML Edge 模型版本號碼,開啟詳細資料頁面。
  3. 按一下 [匯出]
  4. 在「匯出模型」側邊視窗中,指定 Cloud Storage 中的位置,以儲存 Edge 模型匯出輸出內容。
  5. 按一下 [匯出]
  6. 按一下「完成」,關閉「匯出模型」側邊視窗。

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:專案位置。
  • PROJECT:您的專案 ID
  • MODEL_ID:要匯出的已訓練 AutoML Edge 模型 ID 編號。
  • EXPORT_FORMAT:要匯出的 Edge 模型類型。這個目標的選項包括:
    • tflite (TF Lite) - 將模型匯出為 TF Lite 套件,以在邊緣或行動裝置上執行模型。
    • edgetpu-tflite (Edge TPU TF Lite) - 將模型匯出為 TF Lite 套件,以在 Edge TPU 裝置上執行模型。
    • tf-saved-model (容器) - 將模型匯出為 TF Saved Model,以在 Docker 容器上執行。
    • core-ml (Core ML) - 匯出 .mlmodel 檔案,以在 iOS 和 macOS 裝置上執行模型。
    • tf-js (Tensorflow.js) - 將模型匯出為 TensorFlow.js 套件,以在瀏覽器或 Node.js 中執行模型。
  • OUTPUT_BUCKET:要儲存 Edge 模型檔案的 Cloud Storage bucket 目錄路徑。
  • HTTP 方法和網址:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export

    JSON 要求內文:

    {
      "outputConfig": {
        "exportFormatId": "EXPORT_FORMAT",
        "artifactDestination": {
          "outputUriPrefix": "gs://OUTPUT_BUCKET/"
        }
      }
    }
    

    如要傳送要求,請選擇以下其中一個選項:

    curl

    將要求內文儲存在名為 request.json 的檔案中,然後執行下列指令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export"

    PowerShell

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export" | Select-Object -Expand Content

    回覆內容會包含規格資訊和 OPERATION_ID

    您可以取得匯出作業的狀態,查看作業何時完成。

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vertex AI 快速入門導覽課程」中的 Java 設定操作說明進行操作。詳情請參閱 Vertex AI Java API 參考說明文件

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


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.ExportModelOperationMetadata;
import com.google.cloud.aiplatform.v1.ExportModelRequest;
import com.google.cloud.aiplatform.v1.ExportModelResponse;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExportModelSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String gcsDestinationOutputUriPrefix = "gs://YOUR_GCS_SOURCE_BUCKET/path_to_your_destination/";
    String exportFormat = "YOUR_EXPORT_FORMAT";
    exportModelSample(project, modelId, gcsDestinationOutputUriPrefix, exportFormat);
  }

  static void exportModelSample(
      String project, String modelId, String gcsDestinationOutputUriPrefix, String exportFormat)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";
      GcsDestination.Builder gcsDestination = GcsDestination.newBuilder();
      gcsDestination.setOutputUriPrefix(gcsDestinationOutputUriPrefix);

      ModelName modelName = ModelName.of(project, location, modelId);
      ExportModelRequest.OutputConfig outputConfig =
          ExportModelRequest.OutputConfig.newBuilder()
              .setExportFormatId(exportFormat)
              .setArtifactDestination(gcsDestination)
              .build();

      OperationFuture<ExportModelResponse, ExportModelOperationMetadata> exportModelResponseFuture =
          modelServiceClient.exportModelAsync(modelName, outputConfig);
      System.out.format(
          "Operation name: %s\n", exportModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      ExportModelResponse exportModelResponse =
          exportModelResponseFuture.get(300, TimeUnit.SECONDS);

      System.out.format("Export Model Response: %s\n", exportModelResponse);
    }
  }
}

Node.js

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vertex AI 快速入門導覽課程」中的 Node.js 設定操作說明進行操作。詳情請參閱 Vertex AI Node.js API 參考說明文件

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

/**
 * TODO(developer): Uncomment these variables before running the sample.\
   (Not necessary if passing values as arguments)
 */

// const modelId = 'YOUR_MODEL_ID';
// const gcsDestinationOutputUriPrefix ='YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const exportFormat = 'YOUR_EXPORT_FORMAT';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Model Service Client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);

async function exportModel() {
  // Configure the name resources
  const name = `projects/${project}/locations/${location}/models/${modelId}`;
  // Configure the outputConfig resources
  const outputConfig = {
    exportFormatId: exportFormat,
    gcsDestination: {
      outputUriPrefix: gcsDestinationOutputUriPrefix,
    },
  };
  const request = {
    name,
    outputConfig,
  };

  // Export Model request
  const [response] = await modelServiceClient.exportModel(request);
  console.log(`Long running operation : ${response.name}`);

  // Wait for operation to complete
  await response.promise();
  const result = response.result;

  console.log(`Export model response : ${JSON.stringify(result)}`);
}
exportModel();

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件

from google.cloud import aiplatform


def export_model_sample(
    project: str,
    model_id: str,
    gcs_destination_output_uri_prefix: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
    timeout: int = 300,
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
    output_config = {
        "artifact_destination": {
            "output_uri_prefix": gcs_destination_output_uri_prefix
        },
        # For information about export formats: https://cloud.google.com/ai-platform-unified/docs/export/export-edge-model#aiplatform_export_model_sample-drest
        "export_format_id": "tf-saved-model",
    }
    name = client.model_path(project=project, location=location, model=model_id)
    response = client.export_model(name=name, output_config=output_config)
    print("Long running operation:", response.operation.name)
    print("output_info:", response.metadata.output_info)
    export_model_response = response.result(timeout=timeout)
    print("export_model_response:", export_model_response)

分類

訓練完成的 AutoML Edge 圖片分類模型可以匯出為下列格式:

  • TF Lite - 將模型匯出為 TF Lite 套件,以在邊緣或行動裝置上執行模型。
  • Edge TPU TF Lite - 將模型匯出為 TF Lite 套件,即可在 Edge TPU 裝置上執行模型。
  • 容器 - 將模型匯出為 TF Saved Model,以便在 Docker 容器上執行。
  • Core ML - 匯出 .mlmodel 檔案,以在 iOS 和 macOS 裝置上執行模型。
  • Tensorflow.js - 將模型匯出為 TensorFlow.js 套件,以在瀏覽器或 Node.js 中執行模型。

請選取下方分頁,查看適用於您語言或環境的說明:

控制台

  1. 在 Google Cloud 控制台的 Vertex AI 專區中,前往「Models」頁面。

    前往「模型」頁面

  2. 按一下要匯出的 AutoML Edge 模型版本號碼,開啟詳細資料頁面。
  3. 按一下 [匯出]
  4. 在「匯出模型」側邊視窗中,指定 Cloud Storage 中的位置,以儲存 Edge 模型匯出輸出內容。
  5. 按一下 [匯出]
  6. 按一下「完成」,關閉「匯出模型」側邊視窗。

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:專案位置。
  • PROJECT:您的專案 ID
  • MODEL_ID:要匯出的已訓練 AutoML Edge 模型 ID 編號。
  • EXPORT_FORMAT:要匯出的 Edge 模型類型。這個目標的選項包括:
    • tflite (TF Lite) - 將模型匯出為 TF Lite 套件,以在邊緣或行動裝置上執行模型。
    • edgetpu-tflite (Edge TPU TF Lite) - 將模型匯出為 TF Lite 套件,以在 Edge TPU 裝置上執行模型。
    • tf-saved-model (容器) - 將模型匯出為 TF Saved Model,以在 Docker 容器上執行。
    • core-ml (Core ML) - 匯出 .mlmodel 檔案,以在 iOS 和 macOS 裝置上執行模型。
    • tf-js (Tensorflow.js) - 將模型匯出為 TensorFlow.js 套件,以在瀏覽器或 Node.js 中執行模型。
  • OUTPUT_BUCKET:要儲存 Edge 模型檔案的 Cloud Storage bucket 目錄路徑。
  • HTTP 方法和網址:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export

    JSON 要求內文:

    {
      "outputConfig": {
        "exportFormatId": "EXPORT_FORMAT",
        "artifactDestination": {
          "outputUriPrefix": "gs://OUTPUT_BUCKET/"
        }
      }
    }
    

    如要傳送要求,請選擇以下其中一個選項:

    curl

    將要求內文儲存在名為 request.json 的檔案中,然後執行下列指令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export"

    PowerShell

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export" | Select-Object -Expand Content

    回覆內容會包含規格資訊和 OPERATION_ID

    您可以取得匯出作業的狀態,查看作業何時完成。

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vertex AI 快速入門導覽課程」中的 Java 設定操作說明進行操作。詳情請參閱 Vertex AI Java API 參考說明文件

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


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.ExportModelOperationMetadata;
import com.google.cloud.aiplatform.v1.ExportModelRequest;
import com.google.cloud.aiplatform.v1.ExportModelResponse;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExportModelSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String gcsDestinationOutputUriPrefix = "gs://YOUR_GCS_SOURCE_BUCKET/path_to_your_destination/";
    String exportFormat = "YOUR_EXPORT_FORMAT";
    exportModelSample(project, modelId, gcsDestinationOutputUriPrefix, exportFormat);
  }

  static void exportModelSample(
      String project, String modelId, String gcsDestinationOutputUriPrefix, String exportFormat)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";
      GcsDestination.Builder gcsDestination = GcsDestination.newBuilder();
      gcsDestination.setOutputUriPrefix(gcsDestinationOutputUriPrefix);

      ModelName modelName = ModelName.of(project, location, modelId);
      ExportModelRequest.OutputConfig outputConfig =
          ExportModelRequest.OutputConfig.newBuilder()
              .setExportFormatId(exportFormat)
              .setArtifactDestination(gcsDestination)
              .build();

      OperationFuture<ExportModelResponse, ExportModelOperationMetadata> exportModelResponseFuture =
          modelServiceClient.exportModelAsync(modelName, outputConfig);
      System.out.format(
          "Operation name: %s\n", exportModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      ExportModelResponse exportModelResponse =
          exportModelResponseFuture.get(300, TimeUnit.SECONDS);

      System.out.format("Export Model Response: %s\n", exportModelResponse);
    }
  }
}

Node.js

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vertex AI 快速入門導覽課程」中的 Node.js 設定操作說明進行操作。詳情請參閱 Vertex AI Node.js API 參考說明文件

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

/**
 * TODO(developer): Uncomment these variables before running the sample.\
   (Not necessary if passing values as arguments)
 */

// const modelId = 'YOUR_MODEL_ID';
// const gcsDestinationOutputUriPrefix ='YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const exportFormat = 'YOUR_EXPORT_FORMAT';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Model Service Client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);

async function exportModel() {
  // Configure the name resources
  const name = `projects/${project}/locations/${location}/models/${modelId}`;
  // Configure the outputConfig resources
  const outputConfig = {
    exportFormatId: exportFormat,
    gcsDestination: {
      outputUriPrefix: gcsDestinationOutputUriPrefix,
    },
  };
  const request = {
    name,
    outputConfig,
  };

  // Export Model request
  const [response] = await modelServiceClient.exportModel(request);
  console.log(`Long running operation : ${response.name}`);

  // Wait for operation to complete
  await response.promise();
  const result = response.result;

  console.log(`Export model response : ${JSON.stringify(result)}`);
}
exportModel();

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件

from google.cloud import aiplatform


def export_model_sample(
    project: str,
    model_id: str,
    gcs_destination_output_uri_prefix: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
    timeout: int = 300,
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
    output_config = {
        "artifact_destination": {
            "output_uri_prefix": gcs_destination_output_uri_prefix
        },
        # For information about export formats: https://cloud.google.com/ai-platform-unified/docs/export/export-edge-model#aiplatform_export_model_sample-drest
        "export_format_id": "tf-saved-model",
    }
    name = client.model_path(project=project, location=location, model=model_id)
    response = client.export_model(name=name, output_config=output_config)
    print("Long running operation:", response.operation.name)
    print("output_info:", response.metadata.output_info)
    export_model_response = response.result(timeout=timeout)
    print("export_model_response:", export_model_response)

物件偵測

訓練完成的 AutoML Edge 圖片物件偵測模型可以匯出為下列格式:

  • TF Lite - 將模型匯出為 TF Lite 套件,以在邊緣或行動裝置上執行模型。
  • 容器 - 將模型匯出為 TF Saved Model,以便在 Docker 容器上執行。
  • Tensorflow.js - 將模型匯出為 TensorFlow.js 套件,以在瀏覽器或 Node.js 中執行模型。

請選取下方分頁,查看適用於您語言或環境的說明:

控制台

  1. 在 Google Cloud 控制台的 Vertex AI 專區中,前往「Models」頁面。

    前往「模型」頁面

  2. 按一下要匯出的 AutoML Edge 模型版本號碼,開啟詳細資料頁面。
  3. 選取「Deploy & Test」(部署及測試) 分頁標籤,即可查看可用的匯出格式。
  4. 從「使用邊緣最佳化模型」部分選取所需的匯出模型格式。
  5. 在「匯出模型」側邊視窗中,指定 Cloud Storage 中的位置,以儲存 Edge 模型匯出輸出內容。
  6. 按一下 [匯出]
  7. 按一下「完成」,關閉「匯出模型」側邊視窗。

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:專案位置。
  • PROJECT:。
  • MODEL_ID:要匯出的已訓練 AutoML Edge 模型 ID 編號。
  • EXPORT_FORMAT:要匯出的 Edge 模型類型。這個目標的選項包括:
    • tflite (TF Lite) - 將模型匯出為 TF Lite 套件,以在邊緣或行動裝置上執行模型。
    • tf-saved-model (容器) - 將模型匯出為 TF Saved Model,以在 Docker 容器上執行。
    • tf-js (Tensorflow.js) - 將模型匯出為 TensorFlow.js 套件,以在瀏覽器或 Node.js 中執行模型。
  • OUTPUT_BUCKET:要儲存 Edge 模型檔案的 Cloud Storage bucket 目錄路徑。
  • HTTP 方法和網址:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export

    JSON 要求內文:

    {
      "outputConfig": {
        "exportFormatId": "EXPORT_FORMAT",
        "artifactDestination": {
          "outputUriPrefix": "gs://OUTPUT_BUCKET/"
        }
      }
    }
    

    如要傳送要求,請選擇以下其中一個選項:

    curl

    將要求內文儲存在名為 request.json 的檔案中,然後執行下列指令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export"

    PowerShell

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/models/MODEL_ID:export" | Select-Object -Expand Content

    回覆內容會包含規格資訊和 OPERATION_ID

    您可以取得匯出作業的狀態,查看作業何時完成。

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vertex AI 快速入門導覽課程」中的 Java 設定操作說明進行操作。詳情請參閱 Vertex AI Java API 參考說明文件

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


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.ExportModelOperationMetadata;
import com.google.cloud.aiplatform.v1.ExportModelRequest;
import com.google.cloud.aiplatform.v1.ExportModelResponse;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExportModelSample {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String gcsDestinationOutputUriPrefix = "gs://YOUR_GCS_SOURCE_BUCKET/path_to_your_destination/";
    String exportFormat = "YOUR_EXPORT_FORMAT";
    exportModelSample(project, modelId, gcsDestinationOutputUriPrefix, exportFormat);
  }

  static void exportModelSample(
      String project, String modelId, String gcsDestinationOutputUriPrefix, String exportFormat)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    ModelServiceSettings modelServiceSettings =
        ModelServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
      String location = "us-central1";
      GcsDestination.Builder gcsDestination = GcsDestination.newBuilder();
      gcsDestination.setOutputUriPrefix(gcsDestinationOutputUriPrefix);

      ModelName modelName = ModelName.of(project, location, modelId);
      ExportModelRequest.OutputConfig outputConfig =
          ExportModelRequest.OutputConfig.newBuilder()
              .setExportFormatId(exportFormat)
              .setArtifactDestination(gcsDestination)
              .build();

      OperationFuture<ExportModelResponse, ExportModelOperationMetadata> exportModelResponseFuture =
          modelServiceClient.exportModelAsync(modelName, outputConfig);
      System.out.format(
          "Operation name: %s\n", exportModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      ExportModelResponse exportModelResponse =
          exportModelResponseFuture.get(300, TimeUnit.SECONDS);

      System.out.format("Export Model Response: %s\n", exportModelResponse);
    }
  }
}

Node.js

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vertex AI 快速入門導覽課程」中的 Node.js 設定操作說明進行操作。詳情請參閱 Vertex AI Node.js API 參考說明文件

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

/**
 * TODO(developer): Uncomment these variables before running the sample.\
   (Not necessary if passing values as arguments)
 */

// const modelId = 'YOUR_MODEL_ID';
// const gcsDestinationOutputUriPrefix ='YOUR_GCS_DEST_OUTPUT_URI_PREFIX';
//    eg. "gs://<your-gcs-bucket>/destination_path"
// const exportFormat = 'YOUR_EXPORT_FORMAT';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

// Imports the Google Cloud Model Service Client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);

async function exportModel() {
  // Configure the name resources
  const name = `projects/${project}/locations/${location}/models/${modelId}`;
  // Configure the outputConfig resources
  const outputConfig = {
    exportFormatId: exportFormat,
    gcsDestination: {
      outputUriPrefix: gcsDestinationOutputUriPrefix,
    },
  };
  const request = {
    name,
    outputConfig,
  };

  // Export Model request
  const [response] = await modelServiceClient.exportModel(request);
  console.log(`Long running operation : ${response.name}`);

  // Wait for operation to complete
  await response.promise();
  const result = response.result;

  console.log(`Export model response : ${JSON.stringify(result)}`);
}
exportModel();

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件

from google.cloud import aiplatform


def export_model_sample(
    project: str,
    model_id: str,
    gcs_destination_output_uri_prefix: str,
    location: str = "us-central1",
    api_endpoint: str = "us-central1-aiplatform.googleapis.com",
    timeout: int = 300,
):
    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
    output_config = {
        "artifact_destination": {
            "output_uri_prefix": gcs_destination_output_uri_prefix
        },
        # For information about export formats: https://cloud.google.com/ai-platform-unified/docs/export/export-edge-model#aiplatform_export_model_sample-drest
        "export_format_id": "tf-saved-model",
    }
    name = client.model_path(project=project, location=location, model=model_id)
    response = client.export_model(name=name, output_config=output_config)
    print("Long running operation:", response.operation.name)
    print("output_info:", response.metadata.output_info)
    export_model_response = response.result(timeout=timeout)
    print("export_model_response:", export_model_response)

取得作業狀態

圖片

請使用下列程式碼取得匯出作業的狀態。所有目標的程式碼都相同:

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:專案位置。
  • PROJECT:。
  • OPERATION_ID:目標作業的 ID。這個 ID 通常會包含在原始要求的回應中。

HTTP 方法和網址:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/operations/OPERATION_ID

如要傳送要求,請選擇以下其中一個選項:

curl

執行下列指令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/operations/OPERATION_ID"

PowerShell

執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/operations/OPERATION_ID" | Select-Object -Expand Content
完成作業後,畫面會顯示類似以下的輸出:
{
  "name": "projects/PROJECT/locations/LOCATION/models/MODEL_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.ExportModelOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-10-12T20:53:40.130785Z",
      "updateTime": "2020-10-12T20:53:40.793983Z"
    },
    "outputInfo": {
      "artifactOutputUri": "gs://OUTPUT_BUCKET/model-MODEL_ID/EXPORT_FORMAT/YYYY-MM-DDThh:mm:ss.sssZ"
    }
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.ExportModelResponse"
  }
}

輸出檔案

圖片

選取下方分頁標籤,查看對應的型號格式:

TF Lite

要求中指定的 OUTPUT_BUCKET 會決定輸出檔案的儲存位置。輸出檔案的儲存目錄格式如下:

  • gs://OUTPUT_BUCKET/model-MODEL_ID/tflite/YYYY-MM-DDThh:mm:ss.sssZ/

檔案:

  1. model.tflite:內含模型版本的檔案,可供 TensorFlow Lite 使用。

Edge TPU

要求中指定的 OUTPUT_BUCKET 會決定輸出檔案的儲存位置。輸出檔案的儲存目錄格式如下:

  • gs://OUTPUT_BUCKET/model-MODEL_ID/edgetpu-tflite/YYYY-MM-DDThh:mm:ss.sssZ/

檔案:

  1. edgetpu_model.tflite:包含 TensorFlow Lite 模型版本的檔案,已透過 Edge TPU 編譯器處理,可與 Edge TPU 相容。

容器

要求中指定的 OUTPUT_BUCKET 會決定輸出檔案的儲存位置。輸出檔案的儲存目錄格式如下:

  • gs://OUTPUT_BUCKET/model-MODEL_ID/tf-saved-model/YYYY-MM-DDThh:mm:ss.sssZ/

檔案:

  1. saved_model.pb:包含圖表定義和模型權重的通訊協定緩衝區檔案。

Core ML

要求中指定的 OUTPUT_BUCKET 會決定輸出檔案的儲存位置。輸出檔案的儲存目錄格式如下:

  • gs://OUTPUT_BUCKET/model-MODEL_ID/core-ml/YYYY-MM-DDThh:mm:ss.sssZ/

檔案:

  1. dict.txt:標籤檔案。標籤檔案 dict.txt 中的每一行都代表模型傳回的預測標籤,順序與要求時相同。

    範例 dict.txt

    roses
    daisy
    tulips
    dandelion
    sunflowers
    
  2. model.mlmodel:指定 Core ML 模型的檔案。

Tensorflow.js

要求中指定的 OUTPUT_BUCKET 會決定輸出檔案的儲存位置。輸出檔案的儲存目錄格式如下:

  • gs://OUTPUT_BUCKET/model-MODEL_ID/tf-js/YYYY-MM-DDThh:mm:ss.sssZ/

檔案:

  1. dict.txt:標籤檔案。標籤檔案 dict.txt 中的每一行都代表模型傳回的預測標籤,順序與要求時相同。

    範例 dict.txt

    roses
    daisy
    tulips
    dandelion
    sunflowers
    
  2. group1-shard1of3.bin:二進位檔案。
  3. group1-shard2of3.bin:二進位檔案。
  4. group1-shard3of3.bin:二進位檔案。
  5. model.json:模型的 JSON 檔案表示法。

    範例 model.json (為求清楚而縮短)

    {
      "format": "graph-model",
      "generatedBy": "2.4.0",
      "convertedBy": "TensorFlow.js Converter v1.7.0",
      "userDefinedMetadata": {
        "signature": {
          "inputs": {
            "image:0": {
              "name": "image:0",
              "dtype": "DT_FLOAT",
              "tensorShape": {
                "dim": [
                  {
                    "size": "1"
                  },
                  {
                    "size": "224"
                  },
                  {
                    "size": "224"
                  },
                  {
                    "size": "3"
                  }
                ]
              }
            }
          },
          "outputs": {
            "scores:0": {
              "name": "scores:0",
              "dtype": "DT_FLOAT",
              "tensorShape": {
                "dim": [
                  {
                    "size": "1"
                  },
                  {
                    "size": "5"
                  }
                ]
              }
            }
          }
        }
      },
      "modelTopology": {
        "node": [
          {
            "name": "image",
            "op": "Placeholder",
            "attr": {
              "dtype": {
                "type": "DT_FLOAT"
              },
              "shape": {
                "shape": {
                  "dim": [
                    {
                      "size": "1"
                    },
                    {
                      "size": "224"
                    },
                    {
                      "size": "224"
                    },
                    {
                      "size": "3"
                    }
                  ]
                }
              }
            }
          },
          {
            "name": "mnas_v4_a_1/feature_network/feature_extractor/Mean/reduction_indices",
            "op": "Const",
            "attr": {
              "value": {
                "tensor": {
                  "dtype": "DT_INT32",
                  "tensorShape": {
                    "dim": [
                      {
                        "size": "2"
                      }
                    ]
                  }
                }
              },
              "dtype": {
                "type": "DT_INT32"
              }
            }
          },
          ...
          {
            "name": "scores",
            "op": "Identity",
            "input": [
              "Softmax"
            ],
            "attr": {
              "T": {
                "type": "DT_FLOAT"
              }
            }
          }
        ],
        "library": {},
        "versions": {}
      },
      "weightsManifest": [
        {
          "paths": [
            "group1-shard1of3.bin",
            "group1-shard2of3.bin",
            "group1-shard3of3.bin"
          ],
          "weights": [
            {
              "name": "mnas_v4_a_1/feature_network/feature_extractor/Mean/reduction_indices",
              "shape": [
                2
              ],
              "dtype": "int32"
            },
            {
              "name": "mnas_v4_a/output/fc/tf_layer/kernel",
              "shape": [
                1280,
                5
              ],
              "dtype": "float32"
            },
            ...
            {
              "name": "mnas_v4_a_1/feature_network/lead_cell_17/op_0/conv2d_0/Conv2D_weights",
              "shape": [
                1,
                1,
                320,
                1280
              ],
              "dtype": "float32"
            },
            {
              "name": "mnas_v4_a_1/feature_network/cell_14/op_0/expand_0/Conv2D_bn_offset",
              "shape": [
                1152
              ],
              "dtype": "float32"
            }
          ]
        }
      ]
    }