将模型部署到端点

您必须先将模型部署到端点,然后才能使用该模型执行在线预测。部署模型会将物理资源与模型相关联,以便以低延迟方式执行在线预测。

您可以将多个模型部署到一个端点,也可以将一个模型部署到多个端点。如需详细了解部署模型的选项和用例,请参阅下文的将多个模型部署到同一端点的原因

将模型部署到端点

请使用以下方法之一部署模型:

Google Cloud 控制台

  1. 在 Google Cloud 控制台的 Vertex AI 部分中,转到模型页面。

    转到“模型”页面

  2. 点击要部署的模型的名称和版本 ID 以打开其详情页面。

  3. 选择部署和测试标签页。

    如果模型已部署到任何端点,部署模型 (Deploy your model) 部分中会列出这些端点。

  4. 点击部署到端点

  5. 如需将模型部署到新的端点,请选择 创建新端点并为新端点提供名称。如需将模型部署到现有端点,请选择 添加到现有端点,然后从下拉列表中选择端点。

    您可以将多个模型添加到一个端点,也可以将一个模型添加到多个端点。

  6. 如果您将模型部署到已部署有一个或多个模型的现有端点,则必须为要部署的模型和已部署模型更新流量分配比例,以使所有百分比的总和为 100%。

  7. 如果您要将模型部署到新端点,请接受 100 的流量分配比例值。否则,请为端点上所有模型调整流量拆分值,使它们的总和为 100。

  8. 输入要为模型提供的计算节点数下限

    这是此模型始终可用的节点数。

    您需要为使用的节点(无论是处理预测负载还是备用[最少]节点)付费,即使没有预测流量也是如此。请参阅价格页面

    在需要处理预测流量时计算节点的数量可能会增加,但绝不会超出节点数上限。

  9. 如需使用自动扩缩功能,请输入希望 Vertex AI 扩容到的计算节点数上限

  10. 选择机器类型

    较大的机器资源将提高预测性能和增加费用。比较可用的机器类型

  11. 选择加速器类型加速器数量

    如果您在导入或创建模型时启用了加速器使用,则会显示此选项。

    对于加速器数量,请参阅 GPU 表,查看每个 CPU 机器类型的有效 GPU 数量。加速器数量指的是每个节点的加速器数量,而不是部署中的加速器总数。

  12. 如果要使用自定义服务账号进行部署,请在服务账号下拉框中选择服务账号。

  13. 了解如何更改预测日志记录的默认设置

  14. 为模型点击完成,当所有流量分配百分比均正确无误时,点击继续

    随即将显示在其中部署模型的区域。此区域必须是您在其中创建模型的区域。

  15. 点击部署,将模型部署到端点。

API

使用 Vertex AI API 部署模型时,请完成以下步骤:

  1. Create 端点(如果需要)。
  2. Get 端点 ID。
  3. 将模型 Deploy 到端点。

创建端点

如果要将模型部署到现有端点,您可以跳过此步骤。

gcloud

以下示例使用 gcloud ai endpoints create 命令

gcloud ai endpoints create \
  --region=LOCATION_ID \
  --display-name=ENDPOINT_NAME

替换以下内容:

  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • ENDPOINT_NAME:端点的显示名称。

Google Cloud CLI 工具可能需要几秒钟才能创建端点。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION_ID:您的区域。
  • PROJECT_ID:您的项目 ID
  • ENDPOINT_NAME:端点的显示名称。

HTTP 方法和网址:

POST http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints

请求 JSON 正文:

{
  "display_name": "ENDPOINT_NAME"
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/endpoints/ENDPOINT_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.CreateEndpointOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-11-05T17:45:42.812656Z",
      "updateTime": "2020-11-05T17:45:42.812656Z"
    }
  }
}
您可以轮询操作状态,直到响应包含 "done": true

Terraform

以下示例使用 google_vertex_ai_endpoint Terraform 资源创建端点。

如需了解如何应用或移除 Terraform 配置,请参阅基本 Terraform 命令

# Endpoint name must be unique for the project
resource "random_id" "endpoint_id" {
  byte_length = 4
}

resource "google_vertex_ai_endpoint" "default" {
  name         = substr(random_id.endpoint_id.dec, 0, 10)
  display_name = "sample-endpoint"
  description  = "A sample Vertex AI endpoint"
  location     = "us-central1"
  labels = {
    label-one = "value-one"
  }
}

Java

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Java 设置说明执行操作。如需了解详情,请参阅 Vertex AI Java API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.CreateEndpointOperationMetadata;
import com.google.cloud.aiplatform.v1.Endpoint;
import com.google.cloud.aiplatform.v1.EndpointServiceClient;
import com.google.cloud.aiplatform.v1.EndpointServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateEndpointSample {

  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 endpointDisplayName = "YOUR_ENDPOINT_DISPLAY_NAME";
    createEndpointSample(project, endpointDisplayName);
  }

  static void createEndpointSample(String project, String endpointDisplayName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    EndpointServiceSettings endpointServiceSettings =
        EndpointServiceSettings.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 (EndpointServiceClient endpointServiceClient =
        EndpointServiceClient.create(endpointServiceSettings)) {
      String location = "us-central1";
      LocationName locationName = LocationName.of(project, location);
      Endpoint endpoint = Endpoint.newBuilder().setDisplayName(endpointDisplayName).build();

      OperationFuture<Endpoint, CreateEndpointOperationMetadata> endpointFuture =
          endpointServiceClient.createEndpointAsync(locationName, endpoint);
      System.out.format("Operation name: %s\n", endpointFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      Endpoint endpointResponse = endpointFuture.get(300, TimeUnit.SECONDS);

      System.out.println("Create Endpoint Response");
      System.out.format("Name: %s\n", endpointResponse.getName());
      System.out.format("Display Name: %s\n", endpointResponse.getDisplayName());
      System.out.format("Description: %s\n", endpointResponse.getDescription());
      System.out.format("Labels: %s\n", endpointResponse.getLabelsMap());
      System.out.format("Create Time: %s\n", endpointResponse.getCreateTime());
      System.out.format("Update Time: %s\n", endpointResponse.getUpdateTime());
    }
  }
}

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 endpointDisplayName = 'YOUR_ENDPOINT_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

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

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

// Instantiates a client
const endpointServiceClient = new EndpointServiceClient(clientOptions);

async function createEndpoint() {
  // Configure the parent resource
  const parent = `projects/${project}/locations/${location}`;
  const endpoint = {
    displayName: endpointDisplayName,
  };
  const request = {
    parent,
    endpoint,
  };

  // Get and print out a list of all the endpoints for this resource
  const [response] = await endpointServiceClient.createEndpoint(request);
  console.log(`Long running operation : ${response.name}`);

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

  console.log('Create endpoint response');
  console.log(`\tName : ${result.name}`);
  console.log(`\tDisplay name : ${result.displayName}`);
  console.log(`\tDescription : ${result.description}`);
  console.log(`\tLabels : ${JSON.stringify(result.labels)}`);
  console.log(`\tCreate time : ${JSON.stringify(result.createTime)}`);
  console.log(`\tUpdate time : ${JSON.stringify(result.updateTime)}`);
}
createEndpoint();

Python

如需了解如何安装或更新 Python 版 Vertex AI SDK,请参阅安装 Python 版 Vertex AI SDK。如需了解详情,请参阅 Python API 参考文档

def create_endpoint_sample(
    project: str,
    display_name: str,
    location: str,
):
    aiplatform.init(project=project, location=location)

    endpoint = aiplatform.Endpoint.create(
        display_name=display_name,
        project=project,
        location=location,
    )

    print(endpoint.display_name)
    print(endpoint.resource_name)
    return endpoint

检索端点 ID

您需要端点 ID 才能部署模型。

gcloud

以下示例使用 gcloud ai endpoints list 命令

gcloud ai endpoints list \
  --region=LOCATION_ID \
  --filter=display_name=ENDPOINT_NAME

替换以下内容:

  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • ENDPOINT_NAME:端点的显示名称。

请注意 ENDPOINT_ID 列中显示的数字。请在以下步骤中使用此 ID。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • PROJECT_ID:您的项目 ID
  • ENDPOINT_NAME:端点的显示名称。

HTTP 方法和网址:

GET http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints?filter=display_name=ENDPOINT_NAME

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "endpoints": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/endpoints/ENDPOINT_ID",
      "displayName": "ENDPOINT_NAME",
      "etag": "AMEw9yPz5pf4PwBHbRWOGh0PcAxUdjbdX2Jm3QO_amguy3DbZGP5Oi_YUKRywIE-BtLx",
      "createTime": "2020-04-17T18:31:11.585169Z",
      "updateTime": "2020-04-17T18:35:08.568959Z"
    }
  ]
}
请记下 ENDPOINT_ID

部署模型

在下面选择您的语言或环境对应的标签页:

gcloud

以下示例使用 gcloud ai endpoints deploy-model 命令

以下示例将 Model 部署到 Endpoint,但不使用 GPU 来加快预测服务速度,而且未在多个 DeployedModel 资源之间拆分流量:

在使用下面的命令数据之前,请先进行以下替换:

  • ENDPOINT_ID:端点的 ID。
  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • MODEL_ID:要部署的模型的 ID。
  • DEPLOYED_MODEL_NAMEDeployedModel 的名称。您还可以将 Model 的显示名用于 DeployedModel
  • MIN_REPLICA_COUNT:此部署的最小节点数。 节点数可根据预测负载的需要而增加或减少,直至达到节点数上限并且绝不会少于此节点数。
  • MAX_REPLICA_COUNT:此部署的节点数上限。 节点数可根据预测负载的需要而增加或减少,直至达到此节点数并且绝不会少于节点数下限。如果您省略 --max-replica-count 标志,则节点数上限将设置为 --min-replica-count 的值。

执行 gcloud ai endpoints deploy-model 命令:

Linux、macOS 或 Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION_ID \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT \
  --max-replica-count=MAX_REPLICA_COUNT \
  --traffic-split=0=100

Windows (PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION_ID `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME `
  --min-replica-count=MIN_REPLICA_COUNT `
  --max-replica-count=MAX_REPLICA_COUNT `
  --traffic-split=0=100

Windows (cmd.exe)

gcloud ai endpoints deploy-model ENDPOINT_ID^
  --region=LOCATION_ID ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME ^
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=100
 

拆分流量

上述示例中的 --traffic-split=0=100 标志会将 Endpoint 接收的 100% 预测流量发送到新 DeployedModel(使用临时 ID 0 表示)。如果您的 Endpoint 已有其他 DeployedModel 资源,那么您可以在新 DeployedModel 和旧资源之间拆分流量。例如,如需将 20% 的流量发送到新 DeployedModel,将 80% 发送到旧版本,请运行以下命令。

在使用下面的命令数据之前,请先进行以下替换:

  • OLD_DEPLOYED_MODEL_ID:现有 DeployedModel 的 ID。

执行 gcloud ai endpoints deploy-model 命令:

Linux、macOS 或 Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION_ID \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT \
  --max-replica-count=MAX_REPLICA_COUNT \
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80

Windows (PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION_ID `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT `
  --max-replica-count=MAX_REPLICA_COUNT `
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80

Windows (cmd.exe)

gcloud ai endpoints deploy-model ENDPOINT_ID^
  --region=LOCATION_ID ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME \
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80
 

REST

部署此模型。

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION_ID:您在其中使用 Vertex AI 的区域。
  • PROJECT_ID:您的项目 ID
  • ENDPOINT_ID:端点的 ID。
  • MODEL_ID:要部署的模型的 ID。
  • DEPLOYED_MODEL_NAMEDeployedModel 的名称。您还可以将 Model 的显示名用于 DeployedModel
  • MACHINE_TYPE:可选。用于此部署的每个节点的机器资源。其默认设置为 n1-standard-2详细了解机器类型。
  • ACCELERATOR_TYPE:要挂接到机器的加速器类型。如果未指定 ACCELERATOR_COUNT 或为零,则可选。建议不要用于使用非 GPU 映像的 AutoML 模型或自定义训练模型。了解详情
  • ACCELERATOR_COUNT:每个副本要使用的加速器数量。可选。对于使用非 GPU 映像的 AutoML 模型或自定义模型,应该为零或未指定。
  • MIN_REPLICA_COUNT:此部署的最小节点数。 节点数可根据预测负载的需要而增加或减少,直至达到节点数上限并且绝不会少于此节点数。此值必须大于或等于 1。
  • MAX_REPLICA_COUNT:此部署的节点数上限。 节点数可根据预测负载的需要而增加或减少,直至达到此节点数并且绝不会少于节点数下限。
  • TRAFFIC_SPLIT_THIS_MODEL:流向此端点的要路由到使用此操作部署的模型的预测流量百分比。默认值为 100。所有流量百分比之和必须为 100。详细了解流量拆分
  • DEPLOYED_MODEL_ID_N:可选。如果将其他模型部署到此端点,您必须更新其流量拆分百分比,以便所有百分比之和等于 100。
  • TRAFFIC_SPLIT_MODEL_N:已部署模型 ID 密钥的流量拆分百分比值。
  • PROJECT_NUMBER:自动生成的项目编号

HTTP 方法和网址:

POST http://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/endpoints/ENDPOINT_ID:deployModel

请求 JSON 正文:

{
  "deployedModel": {
    "model": "projects/PROJECT/locations/us-central1/models/MODEL_ID",
    "displayName": "DEPLOYED_MODEL_NAME",
    "dedicatedResources": {
       "machineSpec": {
         "machineType": "MACHINE_TYPE",
         "acceleratorType": "ACCELERATOR_TYPE",
         "acceleratorCount": "ACCELERATOR_COUNT"
       },
       "minReplicaCount": MIN_REPLICA_COUNT,
       "maxReplicaCount": MAX_REPLICA_COUNT
     },
  },
  "trafficSplit": {
    "0": TRAFFIC_SPLIT_THIS_MODEL,
    "DEPLOYED_MODEL_ID_1": TRAFFIC_SPLIT_MODEL_1,
    "DEPLOYED_MODEL_ID_2": TRAFFIC_SPLIT_MODEL_2
  },
}

如需发送您的请求,请展开以下选项之一:

您应会收到如下所示的 JSON 响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/endpoints/ENDPOINT_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.DeployModelOperationMetadata",
    "genericMetadata": {
      "createTime": "2020-10-19T17:53:16.502088Z",
      "updateTime": "2020-10-19T17:53:16.502088Z"
    }
  }
}

Java

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Java 设置说明执行操作。如需了解详情,请参阅 Vertex AI Java API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.DedicatedResources;
import com.google.cloud.aiplatform.v1.DeployModelOperationMetadata;
import com.google.cloud.aiplatform.v1.DeployModelResponse;
import com.google.cloud.aiplatform.v1.DeployedModel;
import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.EndpointServiceClient;
import com.google.cloud.aiplatform.v1.EndpointServiceSettings;
import com.google.cloud.aiplatform.v1.MachineSpec;
import com.google.cloud.aiplatform.v1.ModelName;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class DeployModelCustomTrainedModelSample {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String endpointId = "ENDPOINT_ID";
    String modelName = "MODEL_NAME";
    String deployedModelDisplayName = "DEPLOYED_MODEL_DISPLAY_NAME";
    deployModelCustomTrainedModelSample(project, endpointId, modelName, deployedModelDisplayName);
  }

  static void deployModelCustomTrainedModelSample(
      String project, String endpointId, String model, String deployedModelDisplayName)
      throws IOException, ExecutionException, InterruptedException {
    EndpointServiceSettings settings =
        EndpointServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // 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 (EndpointServiceClient client = EndpointServiceClient.create(settings)) {
      MachineSpec machineSpec = MachineSpec.newBuilder().setMachineType("n1-standard-2").build();
      DedicatedResources dedicatedResources =
          DedicatedResources.newBuilder().setMinReplicaCount(1).setMachineSpec(machineSpec).build();

      String modelName = ModelName.of(project, location, model).toString();
      DeployedModel deployedModel =
          DeployedModel.newBuilder()
              .setModel(modelName)
              .setDisplayName(deployedModelDisplayName)
              // `dedicated_resources` must be used for non-AutoML models
              .setDedicatedResources(dedicatedResources)
              .build();
      // key '0' assigns traffic for the newly deployed model
      // Traffic percentage values must add up to 100
      // Leave dictionary empty if endpoint should not accept any traffic
      Map<String, Integer> trafficSplit = new HashMap<>();
      trafficSplit.put("0", 100);
      EndpointName endpoint = EndpointName.of(project, location, endpointId);
      OperationFuture<DeployModelResponse, DeployModelOperationMetadata> response =
          client.deployModelAsync(endpoint, deployedModel, trafficSplit);

      // You can use OperationFuture.getInitialFuture to get a future representing the initial
      // response to the request, which contains information while the operation is in progress.
      System.out.format("Operation name: %s\n", response.getInitialFuture().get().getName());

      // OperationFuture.get() will block until the operation is finished.
      DeployModelResponse deployModelResponse = response.get();
      System.out.format("deployModelResponse: %s\n", deployModelResponse);
    }
  }
}

Python

如需了解如何安装或更新 Python 版 Vertex AI SDK,请参阅安装 Python 版 Vertex AI SDK。如需了解详情,请参阅 Python API 参考文档

def deploy_model_with_dedicated_resources_sample(
    project,
    location,
    model_name: str,
    machine_type: str,
    endpoint: Optional[aiplatform.Endpoint] = None,
    deployed_model_display_name: Optional[str] = None,
    traffic_percentage: Optional[int] = 0,
    traffic_split: Optional[Dict[str, int]] = None,
    min_replica_count: int = 1,
    max_replica_count: int = 1,
    accelerator_type: Optional[str] = None,
    accelerator_count: Optional[int] = None,
    explanation_metadata: Optional[explain.ExplanationMetadata] = None,
    explanation_parameters: Optional[explain.ExplanationParameters] = None,
    metadata: Optional[Sequence[Tuple[str, str]]] = (),
    sync: bool = True,
):
    """
    model_name: A fully-qualified model resource name or model ID.
          Example: "projects/123/locations/us-central1/models/456" or
          "456" when project and location are initialized or passed.
    """

    aiplatform.init(project=project, location=location)

    model = aiplatform.Model(model_name=model_name)

    # The explanation_metadata and explanation_parameters should only be
    # provided for a custom trained model and not an AutoML model.
    model.deploy(
        endpoint=endpoint,
        deployed_model_display_name=deployed_model_display_name,
        traffic_percentage=traffic_percentage,
        traffic_split=traffic_split,
        machine_type=machine_type,
        min_replica_count=min_replica_count,
        max_replica_count=max_replica_count,
        accelerator_type=accelerator_type,
        accelerator_count=accelerator_count,
        explanation_metadata=explanation_metadata,
        explanation_parameters=explanation_parameters,
        metadata=metadata,
        sync=sync,
    )

    model.wait()

    print(model.display_name)
    print(model.resource_name)
    return model

Node.js

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Node.js 设置说明执行操作。如需了解详情,请参阅 Vertex AI Node.js API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

const automl = require('@google-cloud/automl');
const client = new automl.v1beta1.AutoMlClient();

/**
 * Demonstrates using the AutoML client to create a model.
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = '[PROJECT_ID]' e.g., "my-gcloud-project";
// const computeRegion = '[REGION_NAME]' e.g., "us-central1";
// const datasetId = '[DATASET_ID]' e.g., "TBL2246891593778855936";
// const tableId = '[TABLE_ID]' e.g., "1991013247762825216";
// const columnId = '[COLUMN_ID]' e.g., "773141392279994368";
// const modelName = '[MODEL_NAME]' e.g., "testModel";
// const trainBudget = '[TRAIN_BUDGET]' e.g., "1000",
// `Train budget in milli node hours`;

// A resource that represents Google Cloud Platform location.
const projectLocation = client.locationPath(projectId, computeRegion);

// Get the full path of the column.
const columnSpecId = client.columnSpecPath(
  projectId,
  computeRegion,
  datasetId,
  tableId,
  columnId
);

// Set target column to train the model.
const targetColumnSpec = {name: columnSpecId};

// Set tables model metadata.
const tablesModelMetadata = {
  targetColumnSpec: targetColumnSpec,
  trainBudgetMilliNodeHours: trainBudget,
};

// Set datasetId, model name and model metadata for the dataset.
const myModel = {
  datasetId: datasetId,
  displayName: modelName,
  tablesModelMetadata: tablesModelMetadata,
};

// Create a model with the model metadata in the region.
client
  .createModel({parent: projectLocation, model: myModel})
  .then(responses => {
    const initialApiResponse = responses[1];
    console.log(`Training operation name: ${initialApiResponse.name}`);
    console.log('Training started...');
  })
  .catch(err => {
    console.error(err);
  });

了解如何更改预测日志记录的默认设置

获取操作状态

某些请求会启动需要一些时间才能完成的长时间运行的操作。这些请求会返回操作名称,您可以使用该名称查看操作状态或取消操作。Vertex AI 提供辅助方法来调用长时间运行的操作。如需了解详情,请参阅使用长时间运行的操作

限制

  • 如果您启用了 VPC Service Controls,则已部署模型的容器将无法访问互联网。

配置模型部署

在模型部署期间,您要针对如何运行在线预测做出以下重要决策:

已创建的资源 在创建资源时指定的设置
端点 运行预测的位置
模型 要使用的容器 (ModelContainerSpec)
DeployedModel 用于在线预测的机器

在初始创建模型或端点后,您将无法更新上面列出的设置,也无法在在线预测请求中替换这些设置。如果需要更改这些设置,您必须重新部署模型。

部署模型时发生的情况

将模型部署到端点,即会将物理(机器)资源与该模型相关联,以便通过模型进行在线预测。在线预测要求低延时。提前为模型提供资源可缩短延迟时间。

模型的训练类型(AutoML 或自定义)和 (AutoML) 数据类型决定了模型可用的物理资源类型。部署模型后,您可以 mutate 其中一些资源,而无需创建新部署。

端点资源提供用于请求预测的服务端点(网址)。例如:

http://us-central1-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:predict

将多个模型部署到同一端点的原因

将两个模型部署到同一端点后,您可以逐步替换其中一个模型。例如,假设您正在使用某个模型,然后找到一种方法可通过新训练数据来提高该模型的准确率。但是,您不希望将应用更新为指向新的端点网址,也不希望应用发生突然的变化。您可以将新模型添加到同一端点,处理一小部分流量,然后逐渐增加新模型的流量分配比例,直到新模型处理所有流量。

由于资源与模型(而非端点)关联,您可以将不同类型的模型部署到同一端点。但是,最佳做法是将某个特定类型的模型(例如,AutoML 文本、AutoML 表格、自定义训练)部署到一个端点。此配置更易于管理。

将一个模型部署到多个端点的原因

您可能需要针对不同的应用环境(例如测试和生产)部署具有不同资源的模型。您可能还需要为预测请求支持不同的 SLO。也许您的某一个应用的性能需求明显高于其他应用。在这种情况下,您可以将该模型部署到具有更多机器资源的高性能端点。如需优化费用,您还可以将模型部署到具有较少机器资源的低性能端点。

扩缩行为

将用于在线预测的 Model 部署为 DeployedModel 时,您可以将预测节点配置为自动扩缩。为此,请将 dedicatedResources.maxReplicaCount 设置为大于 dedicatedResources.minReplicaCount 的值。

配置 DeployedModel 时,您必须将 dedicatedResources.minReplicaCount 至少设置为 1。换句话说,您不能将 DeployedModel 配置为在未使用时缩减为 0 个预测节点。

目标使用率和配置

默认情况下,如果您部署没有专用 GPU 资源的模型,则 Vertex AI 会自动增加或减少副本的数量,以使 CPU 使用率与默认的 60% 目标值匹配。

默认情况下,如果您部署具有专用 GPU 资源的模型(如果 machineSpec.accelerator_count 大于 0),则 Vertex AI 会自动增加或减少副本数,以使 CPU 或 GPU 使用率(以较高者为准)与默认的 60% 目标值匹配。因此,如果预测吞吐量导致高 GPU 使用率,但未导致高 CPU 使用率,则 Vertex AI 会扩容,且 CPU 利用率非常低(这将会显示在监控中)。反之,如果自定义容器未充分利用 GPU,但有一个不相关的进程,使 CPU 利用率超过 60%,则 Vertex AI 会扩容,即使可能不需要实现 QPS 和延迟时间目标也是如此。

您可以通过指定 autoscalingMetricSpecs 来替换默认阈值指标和目标。 请注意,如果部署配置为仅根据 CPU 使用率进行扩缩,则即使 GPU 使用率较高,部署也不会扩容。

管理资源使用率

您可以监控端点以跟踪 CPU 和加速器使用率、请求数、延迟时间以及当前和目标副本数等指标。此信息可帮助您了解端点的资源使用率和扩缩行为。

请注意,每个副本只运行一个容器。这意味着,如果预测容器无法充分利用所选的计算资源(例如多核机器的单线程代码,或在执行预测期间调用其他服务的自定义模型),则节点可能不会扩容。

例如,如果您使用的是 FastAPI 或具有可配置数量的工作器或线程的任何模型服务器,则在很多情况下,有多个工作器可以提高资源利用率,从而提高服务自动扩缩副本数的能力。

通常,建议最开始每个核心有一个工作器或线程。如果您发现 CPU 利用率较低,尤其是在负载较高时,或者模型因 CPU 利用率较低而未扩容,则增加工作器数量。另一方面,如果您发现利用率过高,且延迟时间在负载时高于预期,请尝试使用较少的工作器。 如果您已经在只使用单个工作器,请尝试使用更小的机器类型。

扩缩行为和延迟

Vertex AI 每 15 秒使用一次前 5 分钟时段内的数据调整副本数。在每个 15 秒的周期内,系统都会测量一次服务器使用率,并根据以下公式生成目标副本数:

target # of replicas = Ceil(current # of replicas * (current utilization / target utilization))

例如,如果您当前有两个副本且使用率为 100%,则目标值为 4:

4 = Ceil(3.33) = Ceil(2 * (100% / 60%))

再举一例,如果您当前有 10 个副本且使用率下降到 1%,则目标值为 1:

1 = Ceil(.167) = Ceil(10 * (1% / 60%))

在每个 15 秒周期结束时,系统都会调整副本数,以匹配上一个 5 分钟时段内的最高目标值。请注意,由于选择了最高目标值,因此如果 5 分钟的时间段内出现使用率高峰,则即使总体使用率非常低,端点也不会缩容。另一方面,如果系统需要纵向扩容,则会在 15 秒内进行扩容,因为选择的是最高目标值而不是平均值。

请注意,即使在 Vertex AI 调整副本的数量后,启动或关闭副本也需要一些时间。因此,在端点可以根据流量做出调整之前,会有额外的延迟。造成延迟的主要因素包括:

  • 预配和启动 Compute Engine 虚拟机的时间
  • 从注册数据库下载容器的时间
  • 从存储空间加载模型的时间

如需了解模型的实际扩缩行为,最佳方法是运行负载测试并优化对您的模型和用例至关重要的特征。如果自动扩缩器为应用扩容的速度不够快,请预配足够的 min_replicas 以处理预期的基准流量。

更新扩缩配置

如果您在部署模型时指定了 DedicatedResourcesAutomaticResources,您可以通过调用 mutateDeployedModel 来更新扩缩配置,而无需重新部署模型。

例如,以下请求会更新 max_replicaautoscaling_metric_specs,并停用容器日志记录。

{
  "deployedModel": {
    "id": "2464520679043629056",
    "dedicatedResources": {
      "maxReplicaCount": 9,
      "autoscalingMetricSpecs": [
        {
          "metricName": "aiplatform.googleapis.com/prediction/online/cpu/utilization",
          "target": 50
        }
      ]
    },
    "disableContainerLogging": true
  },
  "update_mask": {
    "paths": [
      "dedicated_resources.max_replica_count",
      "dedicated_resources.autoscaling_metric_specs",
      "disable_container_logging"
    ]
  }
}

使用说明:

  • 您不能更改机器类型或从 DedicatedResources 更改为 AutomaticResources,或反之亦然。您只能更改以下扩缩配置字段:min_replicamax_replicaAutoscalingMetricSpec(仅限 DedicatedResources)。
  • 您必须在 updateMask 中列出要更新的每个字段。不公开列出的字段会被忽略。
  • DeployedModel 必须处于 DEPLOYED 状态。每个已部署的模型最多只能有一个活跃的变更操作。
  • mutateDeployedModel 还可让您启用或停用容器日志记录。如需了解详情,请参阅在线预测日志记录

后续步骤