ייצוא מודלים של AutoML Edge

בדף הזה מוסבר איך להשתמש בפלטפורמת הסוכנים של Gemini Enterprise כדי לייצא את מודלי AutoML Edge של תמונות ל-Cloud Storage.

מידע על ייצוא של מודלים טבלאיים זמין במאמר ייצוא של מודל טבלאי של AutoML.

מבוא

אחרי שמאמנים מודל AutoML Edge, אפשר לייצא אותו בפורמטים שונים, בהתאם לאופן שבו רוצים להשתמש בו. קובצי המודל המיוצאים נשמרים בקטגוריה של Cloud Storage, ואפשר להשתמש בהם לחיזוי בסביבה שתבחרו.

אי אפשר להשתמש במודל 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 , בקטע Agent Platform, עוברים לדף Models.

    כניסה לדף Models

  2. לוחצים על מספר הגרסה של מודל AutoML Edge שרוצים לייצא כדי לפתוח את דף הפרטים שלו.
  3. לוחצים על ייצוא.
  4. בחלון הצדדי Export model, מציינים את המיקום ב-Cloud Storage לאחסון פלט הייצוא של מודל Edge.
  5. לוחצים על ייצוא.
  6. לוחצים על סיום כדי לסגור את חלון הצד ייצוא מודל.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION: המיקום של הפרויקט.
  • PROJECT: [מזהה הפרויקט](/resource-manager/docs/creating-managing-projects#identifiers). .
  • MODEL_ID: מספר המזהה של מודל AutoML Edge שאומן ומיוצא.
  • EXPORT_FORMAT: סוג מודל ה-Edge שמייצאים. האפשרויות של היעד הזה הן:
    • tflite (TF Lite) – ייצוא המודל כחבילת TF Lite כדי להריץ את המודל במכשירים ניידים או במכשירים עם יכולות עיבוד נתונים מקומיות.
    • edgetpu-tflite (Edge TPU TF Lite) – ייצוא המודל כחבילת TF Lite כדי להפעיל אותו במכשירי Edge TPU.
    • tf-saved-model (קונטיינר) – ייצוא המודל כמודל TF שמור להרצה בקונטיינר ב-Docker.
    • core-ml (Core ML) – ייצוא קובץ ‎ .mlmodel להרצת המודל במכשירי iOS ו-macOS.
    • tf-js (Tensorflow.js) – מייצאים את המודל כחבילת TensorFlow.js כדי להפעיל את המודל בדפדפן וב-Node.js.
  • OUTPUT_BUCKET: הנתיב לספריית הקטגוריות של Cloud Storage שבה רוצים לאחסן את קובצי המודל של Edge.
  • ה-method של ה-HTTP וכתובת ה-URL:

    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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Agent Platform Java API.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Agent Platform Node.js API.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של 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 , בקטע Agent Platform, עוברים לדף Models.

    כניסה לדף Models

  2. לוחצים על מספר הגרסה של מודל AutoML Edge שרוצים לייצא כדי לפתוח את דף הפרטים שלו.
  3. לוחצים על ייצוא.
  4. בחלון הצדדי Export model, מציינים את המיקום ב-Cloud Storage לאחסון פלט הייצוא של מודל Edge.
  5. לוחצים על ייצוא.
  6. לוחצים על סיום כדי לסגור את חלון הצד ייצוא מודל.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION: המיקום של הפרויקט.
  • PROJECT: [מזהה הפרויקט](/resource-manager/docs/creating-managing-projects#identifiers). .
  • MODEL_ID: מספר המזהה של מודל AutoML Edge שאומן ומיוצא.
  • EXPORT_FORMAT: סוג מודל ה-Edge שמייצאים. האפשרויות של היעד הזה הן:
    • tflite (TF Lite) – ייצוא המודל כחבילת TF Lite כדי להריץ את המודל במכשירים ניידים או במכשירים עם יכולות עיבוד נתונים מקומיות.
    • edgetpu-tflite (Edge TPU TF Lite) – ייצוא המודל כחבילת TF Lite כדי להפעיל אותו במכשירי Edge TPU.
    • tf-saved-model (קונטיינר) – ייצוא המודל כמודל TF שמור להרצה בקונטיינר ב-Docker.
    • core-ml (Core ML) – ייצוא קובץ ‎ .mlmodel להרצת המודל במכשירי iOS ו-macOS.
    • tf-js (Tensorflow.js) – מייצאים את המודל כחבילת TensorFlow.js כדי להפעיל את המודל בדפדפן וב-Node.js.
  • OUTPUT_BUCKET: הנתיב לספריית הקטגוריות של Cloud Storage שבה רוצים לאחסן את קובצי המודל של Edge.
  • ה-method של ה-HTTP וכתובת ה-URL:

    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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Agent Platform Java API.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Agent Platform Node.js API.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של 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 , בקטע Agent Platform, עוברים לדף Models.

    כניסה לדף Models

  2. לוחצים על מספר הגרסה של מודל AutoML Edge שרוצים לייצא כדי לפתוח את דף הפרטים שלו.
  3. בוחרים בכרטיסייה Deploy & Test כדי לראות את פורמטי הייצוא הזמינים.
  4. בוחרים את פורמט המודל הרצוי לייצוא בקטע Use your edge-optimized model (שימוש במודל שעבר אופטימיזציה לשימוש במכשיר).
  5. בחלון הצדדי Export model, מציינים את המיקום ב-Cloud Storage לאחסון פלט הייצוא של מודל Edge.
  6. לוחצים על ייצוא.
  7. לוחצים על סיום כדי לסגור את חלון הצד ייצוא מודל.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION: המיקום של הפרויקט.
  • PROJECT: .
  • MODEL_ID: מספר המזהה של מודל AutoML Edge שאומן ומיוצא.
  • EXPORT_FORMAT: סוג מודל ה-Edge שמייצאים. האפשרויות של היעד הזה הן:
    • tflite (TF Lite) – ייצוא המודל כחבילת TF Lite כדי להריץ את המודל במכשירים ניידים או במכשירים עם יכולות עיבוד נתונים מקומיות.
    • tf-saved-model (קונטיינר) – ייצוא המודל כמודל TF שמור להרצה בקונטיינר ב-Docker.
    • tf-js (Tensorflow.js) – מייצאים את המודל כחבילת TensorFlow.js כדי להפעיל את המודל בדפדפן וב-Node.js.
  • OUTPUT_BUCKET: הנתיב לספריית הקטגוריות של Cloud Storage שבה רוצים לאחסן את קובצי המודל של Edge.
  • ה-method של ה-HTTP וכתובת ה-URL:

    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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Agent Platform Java API.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Agent Platform Node.js API.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של 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:המזהה של פעולת היעד. המזהה הזה בדרך כלל מופיע בתגובה לבקשה המקורית.

ה-method של ה-HTTP וכתובת ה-URL:

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"
            }
          ]
        }
      ]
    }