Vertex AI API를 사용한 모델 배포

이 페이지에서는 Vertex AI API를 사용하여 엔드포인트에 모델을 배포하는 방법을 설명합니다.

소개

이 모델을 사용하여 온라인 예측을 제공하려면 먼저 엔드포인트에 모델을 배포해야 합니다. 모델을 배포하면 지연 시간이 짧은 온라인 예측을 제공할 수 있도록 물리적 리소스를 모델과 연결합니다. 배포되지 않은 모델은 동일한 짧은 지연 시간 요구사항이 없는 일괄 예측을 제공할 수 있습니다.

엔드포인트 1개에 모델을 2개 이상 배포할 수 있고 2개 이상의 엔드포인트에 모델 1개를 배포할 수 있습니다. 모델 배포 옵션 및 사용 사례에 대한 자세한 내용은 모델 배포 정보를 참조하세요.

엔드포인트에 동영상 모델을 배포할 수 없습니다. 동영상 모델은 온라인 예측을 제공하지 않습니다.

Google Cloud Console을 사용하여 모델을 배포하는 데 도움이 필요하면 Google Cloud Console을 사용하여 모델 배포를 참조하세요.

모델 배포

Vertex AI API를 사용하여 모델을 배포하는 경우 다음 단계를 완료합니다.

  1. 필요한 경우 엔드포인트를 만듭니다.
  2. 엔드포인트 ID를 가져옵니다.
  3. 모델을 엔드포인트에 배포합니다.

엔드포인트 만들기

기존 엔드포인트에 모델을 배포하는 경우 이 단계를 건너뛸 수 있습니다.

gcloud

다음 예시에서는 gcloud ai endpoints create 명령어를 사용합니다.

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

다음을 바꿉니다.

  • LOCATION: Vertex AI를 사용하는 리전
  • ENDPOINT_NAME: 엔드포인트의 표시 이름

Google Cloud CLI 도구가 엔드포인트를 만드는 데 몇 초 정도 걸릴 수 있습니다.

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 리전입니다.
  • PROJECT: 프로젝트 ID
  • ENDPOINT_NAME: 엔드포인트의 표시 이름
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints

JSON 요청 본문:

{
  "display_name": "ENDPOINT_NAME"
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/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가 포함될 때까지 작업 상태를 폴링할 수 있습니다.

Java

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.


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용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI 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 \
  --filter=display_name=ENDPOINT_NAME

다음을 바꿉니다.

  • LOCATION: Vertex AI를 사용하는 리전
  • ENDPOINT_NAME: 엔드포인트의 표시 이름

ENDPOINT_ID 열에 표시되는 번호를 확인합니다. 다음 단계에서 이 ID를 사용합니다.

REST 및 명령줄

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 리전입니다.
  • PROJECT: 프로젝트 ID
  • ENDPOINT_NAME: 엔드포인트의 표시 이름
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호

HTTP 메서드 및 URL:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints?filter=display_name=ENDPOINT_NAME

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "endpoints": [
    {
      "name": "projects/PROJECT_NUMBER/locations/us-central1/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 명령어를 사용합니다.

다음 예시는 GPU를 사용하지 않고 ModelEndpoint에 배포하여 여러 DeployedModel 리소스 간에 트래픽을 분할하지 않고 예측 제공 속도를 높입니다.

아래의 명령어 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • LOCATION: Vertex AI를 사용하는 리전
  • MODEL_ID: 배포할 모델의 ID입니다.
  • DEPLOYED_MODEL_NAME: DeployedModel의 이름입니다. DeployedModelModel 표시 이름도 사용할 수 있습니다.
  • MACHINE_TYPE: (선택사항) 이 배포의 각 노드에 사용할 머신 리소스. 기본값은 n1-standard-2입니다. 머신 유형 자세히 알아보기
  • MIN_REPLICA_COUNT: 이 배포의 최소 노드 수. 예측 로드 시 필요에 따라 최대 노드 수까지 노드 수를 늘리거나 줄일 수 있지만 절대 이 수 미만이 되지 않습니다. 이 값은 1보다 크거나 같아야 합니다. --min-replica-count 플래그가 생략된 경우 기본값은 1입니다.
  • 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 \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE \
  --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 `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME `
  --machine-type=MACHINE_TYPE `
  --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 ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME ^
  --machine-type=MACHINE_TYPE ^
  --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 \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE \
  --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 `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE `
  --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 ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE ^
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80
 

GPU 지정

필요에 따라 DeployedModel의 각 노드에서 GPU를 사용하여 예측을 신속하게 제공할 수 있습니다. GPU는 특정 유형의 머신러닝 모델에만 유용합니다. GPU를 사용하는 경우와 각 머신 유형에서 작동하는 GPU 구성을 알아봅니다.

--accelerator 플래그를 사용하여 사용할 GPU 종류와 각 복제본에 사용할 GPU 수를 지정합니다. 예를 들어 각 노드에서 NVIDIA Tesla T4 GPU 2개를 사용하려면 다음 명령어를 실행합니다.

gcloud ai endpoints deploy-model 명령어를 실행합니다.

Linux, macOS 또는 Cloud Shell

gcloud ai endpoints deploy-model ENDPOINT_ID\
  --region=LOCATION \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE \
  --accelerator=count=2,type=nvidia-tesla-t4 \
  --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 `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME `
  --machine-type=MACHINE_TYPE `
  --accelerator=count=2,type=nvidia-tesla-t4 `
  --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 ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME ^
  --machine-type=MACHINE_TYPE ^
  --accelerator=count=2,type=nvidia-tesla-t4 ^
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=100
 

GPU를 사용하는 경우 DeployedModel은 예측 트래픽에 따라 자동으로 확장되지 않습니다. 대신 항상 정확히 --min-replica-count 플래그로 지정한 노드 수로 실행됩니다.

REST 및 명령줄

모델 배포

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: Vertex AI를 사용하는 리전
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • MODEL_ID: 배포할 모델의 ID입니다.
  • DEPLOYED_MODEL_NAME: DeployedModel의 이름입니다. DeployedModelModel 표시 이름도 사용할 수 있습니다.
  • MACHINE_TYPE: (선택사항) 이 배포의 각 노드에 사용할 머신 리소스. 기본값은 n1-standard-2입니다. 머신 유형 자세히 알아보기
  • ACCELERATOR_TYPE: 머신에 연결할 가속기 유형입니다. ACCELERATOR_COUNT가 지정되지 않았거나 0인 경우 선택사항입니다. GPU가 아닌 이미지를 사용하는 AutoML 모델 또는 커스텀 학습 모델에 사용하지 않는 것이 좋습니다. 자세히 알아보기
  • ACCELERATOR_COUNT: 사용할 각 복제본의 가속기 수입니다. 선택사항. GPU가 아닌 이미지를 사용하는 AutoML 모델 또는 커스텀 학습 모델의 경우 0이거나 지정되지 않은 상태여야 합니다.
  • 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 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/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용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.

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

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI 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

예측 로깅의 기본 설정을 변경하는 방법을 알아보세요.

AutoML 이미지

아래에서 언어 또는 환경에 대한 탭을 선택하세요.

gcloud

다음 예시에서는 gcloud ai endpoints deploy-model 명령어를 사용합니다.

다음 예시에서는 여러 DeployedModel 리소스 간에 트래픽을 분할하지 않고 ModelEndpoint에 배포합니다.

아래의 명령어 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • LOCATION: Vertex AI를 사용하는 리전
  • MODEL_ID: 배포할 모델의 ID입니다.
  • DEPLOYED_MODEL_NAME: DeployedModel의 이름입니다. DeployedModelModel 표시 이름도 사용할 수 있습니다.
  • 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 \
  --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 `
  --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 ^
  --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 \
  --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 `
  --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 ^
  --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: Vertex AI를 사용하는 리전
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • MODEL_ID: 배포할 모델의 ID입니다.
  • DEPLOYED_MODEL_NAME: DeployedModel의 이름입니다. DeployedModelModel 표시 이름도 사용할 수 있습니다.
  • MIN_REPLICA_COUNT: 이 배포의 최소 노드 수. 예측 로드 시 필요에 따라 최대 노드 수까지 노드 수를 늘리거나 줄일 수 있지만 절대 이 수 미만이 되지 않습니다.
  • MAX_REPLICA_COUNT: 이 배포의 최대 노드 수. 예측 로드 시 필요에 따라 노드 수를 늘리거나 줄일 수 있지만 최댓값을 절대 초과하지 않습니다.
  • TRAFFIC_SPLIT_THIS_MODEL: 이 작업과 함께 배포되는 모델로 라우팅될 이 엔드포인트에 대한 예측 트래픽 비율입니다. 기본값은 100입니다. 모든 트래픽 비율의 합은 100이 되어야 합니다. 트래픽 분할에 대해 자세히 알아보기
  • DEPLOYED_MODEL_ID_N: 선택사항. 다른 모델이 이 엔드포인트에 배포된 경우 모든 비율의 합이 100이 되도록 트래픽 분할 비율을 업데이트해야 합니다.
  • TRAFFIC_SPLIT_MODEL_N: 배포된 모델 ID 키의 트래픽 분할 비율 값입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:deployModel

JSON 요청 본문:

{
  "deployedModel": {
    "model": "projects/PROJECT/locations/us-central1/models/MODEL_ID",
    "displayName": "DEPLOYED_MODEL_NAME",
    "automaticResources": {
       "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용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.AutomaticResources;
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;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeployModelSample {

  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 deployedModelDisplayName = "YOUR_DEPLOYED_MODEL_DISPLAY_NAME";
    String endpointId = "YOUR_ENDPOINT_NAME";
    String modelId = "YOUR_MODEL_ID";
    deployModelSample(project, deployedModelDisplayName, endpointId, modelId);
  }

  static void deployModelSample(
      String project, String deployedModelDisplayName, String endpointId, String modelId)
      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";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);
      // 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);
      ModelName modelName = ModelName.of(project, location, modelId);
      AutomaticResources automaticResourcesInput =
          AutomaticResources.newBuilder().setMinReplicaCount(1).setMaxReplicaCount(1).build();
      DeployedModel deployedModelInput =
          DeployedModel.newBuilder()
              .setModel(modelName.toString())
              .setDisplayName(deployedModelDisplayName)
              .setAutomaticResources(automaticResourcesInput)
              .build();

      OperationFuture<DeployModelResponse, DeployModelOperationMetadata> deployModelResponseFuture =
          endpointServiceClient.deployModelAsync(endpointName, deployedModelInput, trafficSplit);
      System.out.format(
          "Operation name: %s\n", deployModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      DeployModelResponse deployModelResponse = deployModelResponseFuture.get(20, TimeUnit.MINUTES);

      System.out.println("Deploy Model Response");
      DeployedModel deployedModel = deployModelResponse.getDeployedModel();
      System.out.println("\tDeployed Model");
      System.out.format("\t\tid: %s\n", deployedModel.getId());
      System.out.format("\t\tmodel: %s\n", deployedModel.getModel());
      System.out.format("\t\tDisplay Name: %s\n", deployedModel.getDisplayName());
      System.out.format("\t\tCreate Time: %s\n", deployedModel.getCreateTime());

      DedicatedResources dedicatedResources = deployedModel.getDedicatedResources();
      System.out.println("\t\tDedicated Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", dedicatedResources.getMinReplicaCount());

      MachineSpec machineSpec = dedicatedResources.getMachineSpec();
      System.out.println("\t\t\tMachine Spec");
      System.out.format("\t\t\t\tMachine Type: %s\n", machineSpec.getMachineType());
      System.out.format("\t\t\t\tAccelerator Type: %s\n", machineSpec.getAcceleratorType());
      System.out.format("\t\t\t\tAccelerator Count: %s\n", machineSpec.getAcceleratorCount());

      AutomaticResources automaticResources = deployedModel.getAutomaticResources();
      System.out.println("\t\tAutomatic Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", automaticResources.getMinReplicaCount());
      System.out.format("\t\t\tMax Replica Count: %s\n", automaticResources.getMaxReplicaCount());
    }
  }
}

Node.js

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

// const modelId = "YOUR_MODEL_ID";
// const endpointId = 'YOUR_ENDPOINT_ID';
// const deployedModelDisplayName = 'YOUR_DEPLOYED_MODEL_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

const modelName = `projects/${project}/locations/${location}/models/${modelId}`;
const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
// 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 deployModel() {
  // Configure the parent resource
  // 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
  const trafficSplit = {0: 100};
  const deployedModel = {
    // format: 'projects/{project}/locations/{location}/models/{model}'
    model: modelName,
    displayName: deployedModelDisplayName,
    // AutoML Vision models require `automatic_resources` field
    // Other model types may require `dedicated_resources` field instead
    automaticResources: {minReplicaCount: 1, maxReplicaCount: 1},
  };
  const request = {
    endpoint,
    deployedModel,
    trafficSplit,
  };

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

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

  console.log('Deploy model response');
  const modelDeployed = result.deployedModel;
  console.log('\tDeployed model');
  if (!modelDeployed) {
    console.log('\t\tId : {}');
    console.log('\t\tModel : {}');
    console.log('\t\tDisplay name : {}');
    console.log('\t\tCreate time : {}');

    console.log('\t\tDedicated resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMachine spec {}');
    console.log('\t\t\t\tMachine type : {}');
    console.log('\t\t\t\tAccelerator type : {}');
    console.log('\t\t\t\tAccelerator count : {}');

    console.log('\t\tAutomatic resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMax replica count : {}');
  } else {
    console.log(`\t\tId : ${modelDeployed.id}`);
    console.log(`\t\tModel : ${modelDeployed.model}`);
    console.log(`\t\tDisplay name : ${modelDeployed.displayName}`);
    console.log(`\t\tCreate time : ${modelDeployed.createTime}`);

    const dedicatedResources = modelDeployed.dedicatedResources;
    console.log('\t\tDedicated resources');
    if (!dedicatedResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMachine spec {}');
      console.log('\t\t\t\tMachine type : {}');
      console.log('\t\t\t\tAccelerator type : {}');
      console.log('\t\t\t\tAccelerator count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${dedicatedResources.minReplicaCount}`
      );
      const machineSpec = dedicatedResources.machineSpec;
      console.log('\t\t\tMachine spec');
      console.log(`\t\t\t\tMachine type : ${machineSpec.machineType}`);
      console.log(
        `\t\t\t\tAccelerator type : ${machineSpec.acceleratorType}`
      );
      console.log(
        `\t\t\t\tAccelerator count : ${machineSpec.acceleratorCount}`
      );
    }

    const automaticResources = modelDeployed.automaticResources;
    console.log('\t\tAutomatic resources');
    if (!automaticResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMax replica count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${automaticResources.minReplicaCount}`
      );
      console.log(
        `\t\t\tMax replica count : \
          ${automaticResources.maxReplicaCount}`
      );
    }
  }
}
deployModel();

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def deploy_model_with_automatic_resources_sample(
    project,
    location,
    model_name: 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,
    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)

    model.deploy(
        endpoint=endpoint,
        deployed_model_display_name=deployed_model_display_name,
        traffic_percentage=traffic_percentage,
        traffic_split=traffic_split,
        min_replica_count=min_replica_count,
        max_replica_count=max_replica_count,
        metadata=metadata,
        sync=sync,
    )

    model.wait()

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

예측 로깅의 기본 설정을 변경하는 방법을 알아보세요.

AutoML 테이블 형식

아래에서 언어 또는 환경에 대한 탭을 선택하세요.

gcloud

다음 예시에서는 gcloud ai endpoints deploy-model 명령어를 사용합니다.

다음 예시는 GPU를 사용하지 않고 ModelEndpoint에 배포하여 여러 DeployedModel 리소스 간에 트래픽을 분할하지 않고 예측 제공 속도를 높입니다.

아래의 명령어 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • LOCATION: Vertex AI를 사용하는 리전
  • MODEL_ID: 배포할 모델의 ID입니다.
  • DEPLOYED_MODEL_NAME: DeployedModel의 이름입니다. DeployedModelModel 표시 이름도 사용할 수 있습니다.
  • MACHINE_TYPE: (선택사항) 이 배포의 각 노드에 사용할 머신 리소스. 기본값은 n1-standard-2입니다. 머신 유형 자세히 알아보기
  • MIN_REPLICA_COUNT: 이 배포의 최소 노드 수. 예측 로드 시 필요에 따라 최대 노드 수까지 노드 수를 늘리거나 줄일 수 있지만 절대 이 수 미만이 되지 않습니다. 이 값은 1보다 크거나 같아야 합니다. --min-replica-count 플래그가 생략된 경우 기본값은 1입니다.
  • 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 \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE \
  --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 `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME `
  --machine-type=MACHINE_TYPE `
  --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 ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME ^
  --machine-type=MACHINE_TYPE ^
  --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 \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE \
  --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 `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE `
  --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 ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME \
  --machine-type=MACHINE_TYPE ^
  --min-replica-count=MIN_REPLICA_COUNT ^
  --max-replica-count=MAX_REPLICA_COUNT ^
  --traffic-split=0=20,OLD_DEPLOYED_MODEL_ID=80
 

REST 및 명령줄

모델 배포

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: Vertex AI를 사용하는 리전
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • MODEL_ID: 배포할 모델의 ID입니다.
  • DEPLOYED_MODEL_NAME: DeployedModel의 이름입니다. DeployedModelModel 표시 이름도 사용할 수 있습니다.
  • MACHINE_TYPE: (선택사항) 이 배포의 각 노드에 사용할 머신 리소스. 기본값은 n1-standard-2입니다. 머신 유형 자세히 알아보기
  • ACCELERATOR_TYPE: 머신에 연결할 가속기 유형입니다. ACCELERATOR_COUNT가 지정되지 않았거나 0인 경우 선택사항입니다. GPU가 아닌 이미지를 사용하는 AutoML 모델 또는 커스텀 학습 모델에 사용하지 않는 것이 좋습니다. 자세히 알아보기
  • ACCELERATOR_COUNT: 사용할 각 복제본의 가속기 수입니다. 선택사항. GPU가 아닌 이미지를 사용하는 AutoML 모델 또는 커스텀 학습 모델의 경우 0이거나 지정되지 않은 상태여야 합니다.
  • 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 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/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용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.

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

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI 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

예측 로깅의 기본 설정을 변경하는 방법을 알아보세요.

AutoML 텍스트

아래에서 언어 또는 환경에 대한 탭을 선택하세요.

gcloud

다음 예시에서는 gcloud ai endpoints deploy-model 명령어를 사용합니다.

다음 예시에서는 여러 DeployedModel 리소스 간에 트래픽을 분할하지 않고 ModelEndpoint에 배포합니다.

아래의 명령어 데이터를 사용하기 전에 다음을 바꿉니다.

  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • LOCATION: Vertex AI를 사용하는 리전
  • MODEL_ID: 배포할 모델의 ID입니다.
  • DEPLOYED_MODEL_NAME: DeployedModel의 이름입니다. DeployedModelModel 표시 이름도 사용할 수 있습니다.
  • 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 \
  --model=MODEL_ID \
  --display-name=DEPLOYED_MODEL_NAME \
  --traffic-split=0=100

Windows(PowerShell)

gcloud ai endpoints deploy-model ENDPOINT_ID`
  --region=LOCATION `
  --model=MODEL_ID `
  --display-name=DEPLOYED_MODEL_NAME `
  --traffic-split=0=100

Windows(cmd.exe)

gcloud ai endpoints deploy-model ENDPOINT_ID^
  --region=LOCATION ^
  --model=MODEL_ID ^
  --display-name=DEPLOYED_MODEL_NAME ^
  --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 \
  --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 `
  --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 ^
  --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: Vertex AI를 사용하는 리전
  • PROJECT: 프로젝트 ID
  • ENDPOINT_ID: 엔드포인트의 ID입니다.
  • MODEL_ID: 배포할 모델의 ID입니다.
  • DEPLOYED_MODEL_NAME: DeployedModel의 이름입니다. DeployedModelModel 표시 이름도 사용할 수 있습니다.
  • TRAFFIC_SPLIT_THIS_MODEL: 이 작업과 함께 배포되는 모델로 라우팅될 이 엔드포인트에 대한 예측 트래픽 비율입니다. 기본값은 100입니다. 모든 트래픽 비율의 합은 100이 되어야 합니다. 트래픽 분할에 대해 자세히 알아보기
  • DEPLOYED_MODEL_ID_N: 선택사항. 다른 모델이 이 엔드포인트에 배포된 경우 모든 비율의 합이 100이 되도록 트래픽 분할 비율을 업데이트해야 합니다.
  • TRAFFIC_SPLIT_MODEL_N: 배포된 모델 ID 키의 트래픽 분할 비율 값입니다.
  • PROJECT_NUMBER: 프로젝트의 프로젝트 번호

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/LOCATION/endpoints/ENDPOINT_ID:deployModel

JSON 요청 본문:

{
  "deployedModel": {
    "model": "projects/PROJECT/locations/us-central1/models/MODEL_ID",
    "displayName": "DEPLOYED_MODEL_NAME",
    "automaticResources": {
     }
  },
  "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용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Java API 참조 문서를 참조하세요.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.AutomaticResources;
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;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeployModelSample {

  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 deployedModelDisplayName = "YOUR_DEPLOYED_MODEL_DISPLAY_NAME";
    String endpointId = "YOUR_ENDPOINT_NAME";
    String modelId = "YOUR_MODEL_ID";
    deployModelSample(project, deployedModelDisplayName, endpointId, modelId);
  }

  static void deployModelSample(
      String project, String deployedModelDisplayName, String endpointId, String modelId)
      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";
      EndpointName endpointName = EndpointName.of(project, location, endpointId);
      // 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);
      ModelName modelName = ModelName.of(project, location, modelId);
      AutomaticResources automaticResourcesInput =
          AutomaticResources.newBuilder().setMinReplicaCount(1).setMaxReplicaCount(1).build();
      DeployedModel deployedModelInput =
          DeployedModel.newBuilder()
              .setModel(modelName.toString())
              .setDisplayName(deployedModelDisplayName)
              .setAutomaticResources(automaticResourcesInput)
              .build();

      OperationFuture<DeployModelResponse, DeployModelOperationMetadata> deployModelResponseFuture =
          endpointServiceClient.deployModelAsync(endpointName, deployedModelInput, trafficSplit);
      System.out.format(
          "Operation name: %s\n", deployModelResponseFuture.getInitialFuture().get().getName());
      System.out.println("Waiting for operation to finish...");
      DeployModelResponse deployModelResponse = deployModelResponseFuture.get(20, TimeUnit.MINUTES);

      System.out.println("Deploy Model Response");
      DeployedModel deployedModel = deployModelResponse.getDeployedModel();
      System.out.println("\tDeployed Model");
      System.out.format("\t\tid: %s\n", deployedModel.getId());
      System.out.format("\t\tmodel: %s\n", deployedModel.getModel());
      System.out.format("\t\tDisplay Name: %s\n", deployedModel.getDisplayName());
      System.out.format("\t\tCreate Time: %s\n", deployedModel.getCreateTime());

      DedicatedResources dedicatedResources = deployedModel.getDedicatedResources();
      System.out.println("\t\tDedicated Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", dedicatedResources.getMinReplicaCount());

      MachineSpec machineSpec = dedicatedResources.getMachineSpec();
      System.out.println("\t\t\tMachine Spec");
      System.out.format("\t\t\t\tMachine Type: %s\n", machineSpec.getMachineType());
      System.out.format("\t\t\t\tAccelerator Type: %s\n", machineSpec.getAcceleratorType());
      System.out.format("\t\t\t\tAccelerator Count: %s\n", machineSpec.getAcceleratorCount());

      AutomaticResources automaticResources = deployedModel.getAutomaticResources();
      System.out.println("\t\tAutomatic Resources");
      System.out.format("\t\t\tMin Replica Count: %s\n", automaticResources.getMinReplicaCount());
      System.out.format("\t\t\tMax Replica Count: %s\n", automaticResources.getMaxReplicaCount());
    }
  }
}

Node.js

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Node.js API 참조 문서를 참조하세요.

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

// const modelId = "YOUR_MODEL_ID";
// const endpointId = 'YOUR_ENDPOINT_ID';
// const deployedModelDisplayName = 'YOUR_DEPLOYED_MODEL_DISPLAY_NAME';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

const modelName = `projects/${project}/locations/${location}/models/${modelId}`;
const endpoint = `projects/${project}/locations/${location}/endpoints/${endpointId}`;
// 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 deployModel() {
  // Configure the parent resource
  // 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
  const trafficSplit = {0: 100};
  const deployedModel = {
    // format: 'projects/{project}/locations/{location}/models/{model}'
    model: modelName,
    displayName: deployedModelDisplayName,
    // AutoML Vision models require `automatic_resources` field
    // Other model types may require `dedicated_resources` field instead
    automaticResources: {minReplicaCount: 1, maxReplicaCount: 1},
  };
  const request = {
    endpoint,
    deployedModel,
    trafficSplit,
  };

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

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

  console.log('Deploy model response');
  const modelDeployed = result.deployedModel;
  console.log('\tDeployed model');
  if (!modelDeployed) {
    console.log('\t\tId : {}');
    console.log('\t\tModel : {}');
    console.log('\t\tDisplay name : {}');
    console.log('\t\tCreate time : {}');

    console.log('\t\tDedicated resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMachine spec {}');
    console.log('\t\t\t\tMachine type : {}');
    console.log('\t\t\t\tAccelerator type : {}');
    console.log('\t\t\t\tAccelerator count : {}');

    console.log('\t\tAutomatic resources');
    console.log('\t\t\tMin replica count : {}');
    console.log('\t\t\tMax replica count : {}');
  } else {
    console.log(`\t\tId : ${modelDeployed.id}`);
    console.log(`\t\tModel : ${modelDeployed.model}`);
    console.log(`\t\tDisplay name : ${modelDeployed.displayName}`);
    console.log(`\t\tCreate time : ${modelDeployed.createTime}`);

    const dedicatedResources = modelDeployed.dedicatedResources;
    console.log('\t\tDedicated resources');
    if (!dedicatedResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMachine spec {}');
      console.log('\t\t\t\tMachine type : {}');
      console.log('\t\t\t\tAccelerator type : {}');
      console.log('\t\t\t\tAccelerator count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${dedicatedResources.minReplicaCount}`
      );
      const machineSpec = dedicatedResources.machineSpec;
      console.log('\t\t\tMachine spec');
      console.log(`\t\t\t\tMachine type : ${machineSpec.machineType}`);
      console.log(
        `\t\t\t\tAccelerator type : ${machineSpec.acceleratorType}`
      );
      console.log(
        `\t\t\t\tAccelerator count : ${machineSpec.acceleratorCount}`
      );
    }

    const automaticResources = modelDeployed.automaticResources;
    console.log('\t\tAutomatic resources');
    if (!automaticResources) {
      console.log('\t\t\tMin replica count : {}');
      console.log('\t\t\tMax replica count : {}');
    } else {
      console.log(
        `\t\t\tMin replica count : \
          ${automaticResources.minReplicaCount}`
      );
      console.log(
        `\t\t\tMax replica count : \
          ${automaticResources.maxReplicaCount}`
      );
    }
  }
}
deployModel();

Python

Vertex AI용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vertex AI 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vertex AI Python API 참조 문서를 참조하세요.

def deploy_model_with_automatic_resources_sample(
    project,
    location,
    model_name: 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,
    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)

    model.deploy(
        endpoint=endpoint,
        deployed_model_display_name=deployed_model_display_name,
        traffic_percentage=traffic_percentage,
        traffic_split=traffic_split,
        min_replica_count=min_replica_count,
        max_replica_count=max_replica_count,
        metadata=metadata,
        sync=sync,
    )

    model.wait()

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

작업 상태 가져오기

일부 요청은 완료하는 데 시간이 걸리는 장기 실행 작업을 시작합니다. 이러한 요청은 작업 상태를 보거나 작업을 취소하는 데 사용할 수 있는 작업 이름을 반환합니다. Vertex AI는 장기 실행 작업을 호출하는 도우미 메서드를 제공합니다. 자세한 내용은 장기 실행 작업 다루기를 참조하세요.

다음 단계