이 페이지에서는 GKE 추론 게이트웨이를 배포하는 방법을 설명합니다.
이 페이지는 GKE 인프라를 관리하는 네트워킹 전문가와 AI 워크로드를 관리하는 플랫폼 관리자를 대상으로 합니다.
이 페이지를 읽기 전에 다음 사항을 숙지해야 합니다.
- GKE 추론 게이트웨이 정보
- GKE의 AI/ML 조정
- 생성형 AI 용어집
- Google Cloud의 부하 분산, 특히 부하 분산기가 GKE와 상호작용하는 방식
- GKE 서비스 확장 프로그램 자세한 내용은 GKE 게이트웨이 컨트롤러 문서를 참고하세요.
- 서비스 확장 프로그램을 사용하여 GKE 게이트웨이 트래픽 맞춤설정
GKE 추론 게이트웨이는 생성형 AI 애플리케이션의 게재를 최적화하도록 Google Kubernetes Engine (GKE) 게이트웨이를 개선합니다. GKE 추론 게이트웨이를 사용하면 GKE에서 생성형 AI 워크로드의 게재를 최적화할 수 있습니다. AI 워크로드를 효율적으로 관리하고 확장하며 지연 시간과 같은 워크로드별 성능 목표를 지원하고 리소스 사용률, 관측 가능성, AI 안전성을 개선합니다.
시작하기 전에
시작하기 전에 다음 태스크를 수행했는지 확인합니다.
- Google Kubernetes Engine API를 사용 설정합니다. Google Kubernetes Engine API 사용 설정
- 이 태스크에 Google Cloud CLI를 사용하려면 gcloud CLI를 설치한 후 초기화하세요. 이전에 gcloud CLI를 설치한 경우
gcloud components update
를 실행하여 최신 버전을 가져옵니다.
필요한 경우 Compute Engine API, Network Services API, Model Armor API를 사용 설정합니다.
API 액세스 사용 설정으로 이동하여 안내를 따릅니다.
GKE Gateway Controller 요구사항
- GKE 버전 1.32.3
- Google Cloud CLI 버전 407.0.0 이상
- Gateway API는 VPC 기반 클러스터에서만 지원됩니다.
- 프록시 전용 서브넷을 사용 설정해야 합니다.
- 클러스터에
HttpLoadBalancing
부가기능이 사용 설정되어 있어야 합니다. - Istio를 사용하는 경우 Istio를 다음 버전 중 하나로 업그레이드해야 합니다.
- 1.15.2 이상
- 1.14.5 이상
- 1.13.9 이상
- 공유 VPC를 사용하는 경우 호스트 프로젝트에서 서비스 프로젝트에 대해 GKE 서비스 계정에
Compute Network User
역할을 할당해야 합니다.
제한 및 한도
다음과 같은 제한사항이 적용됩니다.
- 멀티 클러스터 게이트웨이는 지원되지 않습니다.
- GKE 추론 게이트웨이는
gke-l7-regional-external-managed
및gke-l7-rilb
GatewayClass 리소스에서만 지원됩니다. - 리전 간 내부 애플리케이션 부하 분산기는 지원되지 않습니다.
GKE 추론 게이트웨이 구성
GKE 추론 게이트웨이를 구성하려면 다음 예를 참고하세요. 한 팀이 vLLM
및 Llama3
모델을 실행하고 두 가지 고유한 LoRA 미세 조정 어댑터인 'food-review' 및 'cad-fabricator'를 적극적으로 실험합니다.
GKE 추론 게이트웨이를 구성하기 위한 개략적인 워크플로는 다음과 같습니다.
- 환경 준비: 필요한 인프라와 구성요소를 설정합니다.
- 추론 풀 만들기:
InferencePool
커스텀 리소스를 사용하여 모델 서버 풀을 정의합니다. - 모델 서빙 목표 지정:
InferenceModel
커스텀 리소스를 사용하여 모델 목표를 지정합니다. - 게이트웨이 만들기: Gateway API를 사용하여 추론 서비스를 노출합니다.
HTTPRoute
만들기: HTTP 트래픽이 추론 서비스로 라우팅되는 방식을 정의합니다.- 추론 요청 전송: 배포된 모델에 요청합니다.
개발 환경 준비
Helm을 설치합니다.
GKE 클러스터를 만듭니다.
- 버전 1.31 이상으로 GKE Autopilot 또는 Standard 클러스터를 만듭니다. 자세한 내용은 GKE 클러스터 만들기를 참고하세요.
- 원하는 컴퓨팅 계열 및 가속기로 노드를 구성합니다.
- 선택한 가속기, 모델, 성능 요구사항에 따라 사전 구성되고 테스트된 배포 매니페스트에 GKE 추론 빠른 시작 레시피로 권장사항 추론 실행을 사용하세요.
GKE 클러스터에
InferencePool
및InferenceModel
커스텀 리소스 정의 (CRD)를 설치하려면 다음 명령어를 실행합니다.kubectl apply -f https://github.com/kubernetes-sigs/gateway-api-inference-extension/releases/download/v0.3.0/manifests.yaml
VERSION
를 설치하려는 CRD 버전으로 바꿉니다 (예:v0.3.0
).v1.32.2-gke.1182001보다 이전 버전의 GKE를 사용 중이며 GKE 추론 게이트웨이와 함께 모델 아머를 사용하려면 트래픽 및 라우팅 확장 프로그램 CRD를 설치해야 합니다.
kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/gke-gateway-api/refs/heads/main/config/crd/networking.gke.io_gcptrafficextensions.yaml kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/gke-gateway-api/refs/heads/main/config/crd/networking.gke.io_gcproutingextensions.yaml
측정항목을 스크래핑할 수 있는 승인을 설정하려면
inference-gateway-sa-metrics-reader-secret
보안 비밀을 만듭니다.kubectl apply -f - <<EOF --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: inference-gateway-metrics-reader rules: - nonResourceURLs: - /metrics verbs: - get --- apiVersion: v1 kind: ServiceAccount metadata: name: inference-gateway-sa-metrics-reader namespace: default --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: inference-gateway-sa-metrics-reader-role-binding namespace: default subjects: - kind: ServiceAccount name: inference-gateway-sa-metrics-reader namespace: default roleRef: kind: ClusterRole name: inference-gateway-metrics-reader apiGroup: rbac.authorization.k8s.io --- apiVersion: v1 kind: Secret metadata: name: inference-gateway-sa-metrics-reader-secret namespace: default annotations: kubernetes.io/service-account.name: inference-gateway-sa-metrics-reader type: kubernetes.io/service-account-token --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: inference-gateway-sa-metrics-reader-secret-read rules: - resources: - secrets apiGroups: [""] verbs: ["get", "list", "watch"] resourceNames: ["inference-gateway-sa-metrics-reader-secret"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: gmp-system:collector:inference-gateway-sa-metrics-reader-secret-read namespace: default roleRef: name: inference-gateway-sa-metrics-reader-secret-read kind: ClusterRole apiGroup: rbac.authorization.k8s.io subjects: - name: collector namespace: gmp-system kind: ServiceAccount EOF
모델 서버 및 모델 배포 만들기
이 섹션에서는 모델 서버와 모델을 배포하는 방법을 보여줍니다. 이 예에서는 Llama3
모델과 함께 vLLM
모델 서버를 사용합니다. 배포 라벨은 app:vllm-llama3-8b-instruct
입니다. 이 배포에서는 Hugging Face의 food-review
및 cad-fabricator
라는 두 개의 LoRA 어댑터도 사용합니다.
이 예시를 자체 모델 서버 컨테이너와 모델, 제공 포트, 배포 이름으로 조정할 수 있습니다. 배포에서 LoRA 어댑터를 구성하거나 기본 모델을 배포할 수도 있습니다. 다음 단계에서는 필요한 Kubernetes 리소스를 만드는 방법을 설명합니다.
Hugging Face 토큰을 저장할 Kubernetes 보안 비밀을 만듭니다. 이 토큰은 LoRA 어댑터에 액세스하는 데 사용됩니다.
kubectl create secret generic hf-token --from-literal=token=HF_TOKEN
HF_TOKEN
을 Hugging Face 토큰으로 바꿉니다.nvidia-h100-80gb
가속기 유형에 배포하려면 다음 매니페스트를vllm-llama3-8b-instruct.yaml
로 저장합니다. 이 매니페스트는 모델 및 모델 서버가 포함된 Kubernetes 배포를 정의합니다.apiVersion: apps/v1 kind: Deployment metadata: name: vllm-llama3-8b-instruct spec: replicas: 3 selector: matchLabels: app: vllm-llama3-8b-instruct template: metadata: labels: app: vllm-llama3-8b-instruct spec: containers: - name: vllm image: "vllm/vllm-openai:latest" imagePullPolicy: Always command: ["python3", "-m", "vllm.entrypoints.openai.api_server"] args: - "--model" - "meta-llama/Llama-3.1-8B-Instruct" - "--tensor-parallel-size" - "1" - "--port" - "8000" - "--enable-lora" - "--max-loras" - "2" - "--max-cpu-loras" - "12" env: # Enabling LoRA support temporarily disables automatic v1, we want to force it on # until 0.8.3 vLLM is released. - name: PORT value: "8000" - name: HUGGING_FACE_HUB_TOKEN valueFrom: secretKeyRef: name: hf-token key: token - name: VLLM_ALLOW_RUNTIME_LORA_UPDATING value: "true" ports: - containerPort: 8000 name: http protocol: TCP lifecycle: preStop: # vLLM stops accepting connections when it receives SIGTERM, so we need to sleep # to give upstream gateways a chance to take us out of rotation. The time we wait # is dependent on the time it takes for all upstreams to completely remove us from # rotation. Older or simpler load balancers might take upwards of 30s, but we expect # our deployment to run behind a modern gateway like Envoy which is designed to # probe for readiness aggressively. sleep: # Upstream gateway probers for health should be set on a low period, such as 5s, # and the shorter we can tighten that bound the faster that we release # accelerators during controlled shutdowns. However, we should expect variance, # as load balancers may have internal delays, and we don't want to drop requests # normally, so we're often aiming to set this value to a p99 propagation latency # of readiness -> load balancer taking backend out of rotation, not the average. # # This value is generally stable and must often be experimentally determined on # for a given load balancer and health check period. We set the value here to # the highest value we observe on a supported load balancer, and we recommend # tuning this value down and verifying no requests are dropped. # # If this value is updated, be sure to update terminationGracePeriodSeconds. # seconds: 30 # # IMPORTANT: preStop.sleep is beta as of Kubernetes 1.30 - for older versions # replace with this exec action. #exec: # command: # - /usr/bin/sleep # - 30 livenessProbe: httpGet: path: /health port: http scheme: HTTP # vLLM's health check is simple, so we can more aggressively probe it. Liveness # check endpoints should always be suitable for aggressive probing. periodSeconds: 1 successThreshold: 1 # vLLM has a very simple health implementation, which means that any failure is # likely significant. However, any liveness triggered restart requires the very # large core model to be reloaded, and so we should bias towards ensuring the # server is definitely unhealthy vs immediately restarting. Use 5 attempts as # evidence of a serious problem. failureThreshold: 5 timeoutSeconds: 1 readinessProbe: httpGet: path: /health port: http scheme: HTTP # vLLM's health check is simple, so we can more aggressively probe it. Readiness # check endpoints should always be suitable for aggressive probing, but may be # slightly more expensive than readiness probes. periodSeconds: 1 successThreshold: 1 # vLLM has a very simple health implementation, which means that any failure is # likely significant, failureThreshold: 1 timeoutSeconds: 1 # We set a startup probe so that we don't begin directing traffic or checking # liveness to this instance until the model is loaded. startupProbe: # Failure threshold is when we believe startup will not happen at all, and is set # to the maximum possible time we believe loading a model will take. In our # default configuration we are downloading a model from HuggingFace, which may # take a long time, then the model must load into the accelerator. We choose # 10 minutes as a reasonable maximum startup time before giving up and attempting # to restart the pod. # # IMPORTANT: If the core model takes more than 10 minutes to load, pods will crash # loop forever. Be sure to set this appropriately. failureThreshold: 3600 # Set delay to start low so that if the base model changes to something smaller # or an optimization is deployed, we don't wait unnecessarily. initialDelaySeconds: 2 # As a startup probe, this stops running and so we can more aggressively probe # even a moderately complex startup - this is a very important workload. periodSeconds: 1 httpGet: # vLLM does not start the OpenAI server (and hence make /health available) # until models are loaded. This may not be true for all model servers. path: /health port: http scheme: HTTP resources: limits: nvidia.com/gpu: 1 requests: nvidia.com/gpu: 1 volumeMounts: - mountPath: /data name: data - mountPath: /dev/shm name: shm - name: adapters mountPath: "/adapters" initContainers: - name: lora-adapter-syncer tty: true stdin: true image: us-central1-docker.pkg.dev/k8s-staging-images/gateway-api-inference-extension/lora-syncer:main restartPolicy: Always imagePullPolicy: Always env: - name: DYNAMIC_LORA_ROLLOUT_CONFIG value: "/config/configmap.yaml" volumeMounts: # DO NOT USE subPath, dynamic configmap updates don't work on subPaths - name: config-volume mountPath: /config restartPolicy: Always # vLLM allows VLLM_PORT to be specified as an environment variable, but a user might # create a 'vllm' service in their namespace. That auto-injects VLLM_PORT in docker # compatible form as `tcp://<IP>:<PORT>` instead of the numeric value vLLM accepts # causing CrashLoopBackoff. Set service environment injection off by default. enableServiceLinks: false # Generally, the termination grace period needs to last longer than the slowest request # we expect to serve plus any extra time spent waiting for load balancers to take the # model server out of rotation. # # An easy starting point is the p99 or max request latency measured for your workload, # although LLM request latencies vary significantly if clients send longer inputs or # trigger longer outputs. Since steady state p99 will be higher than the latency # to drain a server, you may wish to slightly this value either experimentally or # via the calculation below. # # For most models you can derive an upper bound for the maximum drain latency as # follows: # # 1. Identify the maximum context length the model was trained on, or the maximum # allowed length of output tokens configured on vLLM (llama2-7b was trained to # 4k context length, while llama3-8b was trained to 128k). # 2. Output tokens are the more compute intensive to calculate and the accelerator # will have a maximum concurrency (batch size) - the time per output token at # maximum batch with no prompt tokens being processed is the slowest an output # token can be generated (for this model it would be about 100ms TPOT at a max # batch size around 50) # 3. Calculate the worst case request duration if a request starts immediately # before the server stops accepting new connections - generally when it receives # SIGTERM (for this model that is about 4096 / 10 ~ 40s) # 4. If there are any requests generating prompt tokens that will delay when those # output tokens start, and prompt token generation is roughly 6x faster than # compute-bound output token generation, so add 20% to the time from above (40s + # 16s ~ 55s) # # Thus we think it will take us at worst about 55s to complete the longest possible # request the model is likely to receive at maximum concurrency (highest latency) # once requests stop being sent. # # NOTE: This number will be lower than steady state p99 latency since we stop receiving # new requests which require continuous prompt token computation. # NOTE: The max timeout for backend connections from gateway to model servers should # be configured based on steady state p99 latency, not drain p99 latency # # 5. Add the time the pod takes in its preStop hook to allow the load balancers have # stopped sending us new requests (55s + 30s ~ 85s) # # Because termination grace period controls when the Kubelet forcibly terminates a # stuck or hung process (a possibility due to a GPU crash), there is operational safety # in keeping the value roughly proportional to the time to finish serving. There is also # value in adding a bit of extra time to deal with unexpectedly long workloads. # # 6. Add a 50% safety buffer to this time since the operational impact should be low # (85s * 1.5 ~ 130s) # # One additional source of drain latency is that some workloads may run close to # saturation and have queued requests on each server. Since traffic in excess of the # max sustainable QPS will result in timeouts as the queues grow, we assume that failure # to drain in time due to excess queues at the time of shutdown is an expected failure # mode of server overload. If your workload occasionally experiences high queue depths # due to periodic traffic, consider increasing the safety margin above to account for # time to drain queued requests. terminationGracePeriodSeconds: 130 nodeSelector: cloud.google.com/gke-accelerator: "nvidia-h100-80gb" volumes: - name: data emptyDir: {} - name: shm emptyDir: medium: Memory - name: adapters emptyDir: {} - name: config-volume configMap: name: vllm-llama3-8b-adapters --- apiVersion: v1 kind: ConfigMap metadata: name: vllm-llama3-8b-adapters data: configmap.yaml: | vLLMLoRAConfig: name: vllm-llama3.1-8b-instruct port: 8000 defaultBaseModel: meta-llama/Llama-3.1-8B-Instruct ensureExist: models: - id: food-review source: Kawon/llama3.1-food-finetune_v14_r8 - id: cad-fabricator source: redcathode/fabricator --- kind: HealthCheckPolicy apiVersion: networking.gke.io/v1 metadata: name: health-check-policy namespace: default spec: targetRef: group: "inference.networking.x-k8s.io" kind: InferencePool name: vllm-llama3-8b-instruct default: config: type: HTTP httpHealthCheck: requestPath: /health port: 8000
샘플 매니페스트를 클러스터에 적용합니다.
kubectl apply -f vllm-llama3-8b-instruct.yaml
매니페스트를 적용한 후 다음과 같은 주요 필드와 매개변수를 고려하세요.
replicas
: 배포의 포드 수를 지정합니다.image
: 모델 서버의 Docker 이미지를 지정합니다.command
: 컨테이너가 시작될 때 실행할 명령어를 지정합니다.args
: 명령어에 전달할 인수를 지정합니다.env
: 컨테이너의 환경 변수를 지정합니다.ports
: 컨테이너에서 노출되는 포트를 지정합니다.resources
: GPU와 같은 컨테이너의 리소스 요청 및 제한을 지정합니다.volumeMounts
: 볼륨이 컨테이너에 마운트되는 방식을 지정합니다.initContainers
: 애플리케이션 컨테이너 전에 실행되는 컨테이너를 지정합니다.restartPolicy
: 포드의 다시 시작 정책을 지정합니다.terminationGracePeriodSeconds
: 포드 종료의 유예 기간을 지정합니다.volumes
: 포드에서 사용하는 볼륨을 지정합니다.
이러한 필드는 특정 요구사항에 맞게 수정할 수 있습니다.
추론 풀 만들기
InferencePool
Kubernetes 커스텀 리소스는 공통 기본 대규모 언어 모델 (LLM) 및 컴퓨팅 구성이 있는 Pod 그룹을 정의합니다. selector
필드는 이 풀에 속하는 포드를 지정합니다. 이 선택기의 라벨은 모델 서버 Pod에 적용된 라벨과 정확하게 일치해야 합니다. targetPort
필드는 모델 서버가 포드 내에서 사용하는 포트를 정의합니다.
extensionRef
필드는 추론 풀에 추가 기능을 제공하는 확장 프로그램 서비스를 참조합니다. InferencePool
를 사용하면 GKE 추론 게이트웨이가 트래픽을 모델 서버 포드로 라우팅할 수 있습니다.
InferencePool
를 만들기 전에 InferencePool
가 선택하는 포드가 이미 실행 중인지 확인합니다.
Helm을 사용하여 InferencePool
를 만들려면 다음 단계를 따르세요.
helm install vllm-llama3-8b-instruct \
--set inferencePool.modelServers.matchLabels.app=vllm-llama3-8b-instruct \
--set provider.name=gke \
--version v0.3.0 \
oci://registry.k8s.io/gateway-api-inference-extension/charts/inferencepool
배포에 맞게 다음 필드를 변경합니다.
inferencePool.modelServers.matchLabels.app
: 모델 서버 Pod를 선택하는 데 사용되는 라벨의 키입니다.
Helm 설치는 관찰성에 필요한 제한 시간 정책, 엔드포인트 선택 도구, 포드를 자동으로 설치합니다.
이렇게 하면 포드 내의 모델 엔드포인트 서비스를 참조하는 InferencePool
객체(vllm-llama3-8b-instruct
)가 생성됩니다. 또한 이 생성된 InferencePool
에 app:vllm-llama3-8b-instruct-epp
라는 엔드포인트 선택 도구의 배포도 만듭니다.
모델 게재 목표 지정
InferenceModel
맞춤 리소스는 LoRA 조정 모델 지원 및 제공 중요성을 포함하여 제공할 특정 모델을 정의합니다. InferenceModel
리소스를 만들어 InferencePool
에서 제공할 모델을 정의해야 합니다. 이러한 InferenceModel
리소스는 기본 모델 또는 InferencePool
의 모델 서버에서 지원하는 LoRA 어댑터를 참조할 수 있습니다.
modelName
필드는 기본 모델 또는 LoRA 어댑터의 이름을 지정합니다. Criticality
필드는 모델의 게재 중요도를 지정합니다. poolRef
필드는 이 모델이 제공되는 InferencePool
를 지정합니다.
InferenceModel
를 만들려면 다음 단계를 따르세요.
다음 샘플 매니페스트를
inferencemodel.yaml
로 저장합니다.apiVersion: inference.networking.x-k8s.io/v1alpha2 kind: InferenceModel metadata: name: inferencemodel-sample spec: modelName: MODEL_NAME criticality: VALUE poolRef: name: INFERENCE_POOL_NAME
다음을 바꿉니다.
MODEL_NAME
: 기본 모델 또는 LoRA 어댑터의 이름입니다. 예를 들면food-review
입니다.VALUE
: 선택한 게재 중요도입니다.Critical
,Standard
또는Sheddable
중에서 선택합니다. 예를 들면Standard
입니다.INFERENCE_POOL_NAME
: 이전 단계에서 만든InferencePool
의 이름입니다. 예를 들면vllm-llama3-8b-instruct
입니다.
샘플 매니페스트를 클러스터에 적용합니다.
kubectl apply -f inferencemodel.yaml
다음 예에서는 vllm-llama3-8b-instruct
InferencePool
에서 Standard
서비스 중요도로 food-review
LoRA 모델을 구성하는 InferenceModel
객체를 만듭니다. InferenceModel
객체는 Critical
우선순위 수준으로 제공되도록 기본 모델을 구성합니다.
apiVersion: inference.networking.x-k8s.io/v1alpha2
kind: InferenceModel
metadata:
name: food-review
spec:
modelName: food-review
criticality: Standard
poolRef:
name: vllm-llama3-8b-instruct
targetModels:
- name: food-review
weight: 100
---
apiVersion: inference.networking.x-k8s.io/v1alpha2
kind: InferenceModel
metadata:
name: llama3-base-model
spec:
modelName: meta-llama/Llama-3.1-8B-Instruct
criticality: Critical
poolRef:
name: vllm-llama3-8b-instruct
게이트웨이 만들기
게이트웨이 리소스는 Kubernetes 클러스터로의 외부 트래픽 진입점입니다. 수신 연결을 수락하는 리스너를 정의합니다.
GKE 추론 게이트웨이는 다음 게이트웨이 클래스와 함께 작동합니다.
gke-l7-rilb
: 리전 내부 애플리케이션 부하 분산기에 사용합니다.gke-l7-regional-external-managed
자세한 내용은 게이트웨이 클래스 문서를 참고하세요.
게이트웨이를 만들려면 다음 단계를 따르세요.
다음 샘플 매니페스트를
gateway.yaml
로 저장합니다.apiVersion: gateway.networking.k8s.io/v1 kind: Gateway metadata: name: GATEWAY_NAME spec: gatewayClassName: GATEWAY_CLASS listeners: - protocol: HTTP port: 80 name: http
GATEWAY_NAME
을 게이트웨이 리소스의 고유한 이름 (예:inference-gateway
)으로 바꾸고GATEWAY_CLASS
을 사용하려는 게이트웨이 클래스 (예:gke-l7-regional-external-managed
)로 바꿉니다.매니페스트를 클러스터에 적용합니다.
kubectl apply -f gateway.yaml
참고: HTTPS로 게이트웨이를 보호하기 위해 TLS를 구성하는 방법에 관한 자세한 내용은 GKE 문서의 TLS 구성을 참고하세요.
HTTPRoute
만들기
HTTPRoute
리소스는 GKE 게이트웨이가 수신 HTTP 요청을 백엔드 서비스(이 컨텍스트에서는 InferencePool
)로 라우팅하는 방법을 정의합니다. HTTPRoute
리소스는 일치 규칙 (예: 헤더 또는 경로)과 트래픽을 전달해야 하는 백엔드를 지정합니다.
HTTPRoute
를 만들려면 다음 샘플 매니페스트를httproute.yaml
로 저장합니다.apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: HTTPROUTE_NAME spec: parentRefs: - name: GATEWAY_NAME rules: - matches: - path: type: PathPrefix value: PATH_PREFIX backendRefs: - name: INFERENCE_POOL_NAME group: inference.networking.x-k8s.io kind: InferencePool
다음을 바꿉니다.
HTTPROUTE_NAME
:HTTPRoute
리소스의 고유한 이름입니다. 예를 들면my-route
입니다.GATEWAY_NAME
: 만든Gateway
리소스의 이름입니다. 예를 들면inference-gateway
입니다.PATH_PREFIX
: 수신 요청을 일치시키는 데 사용하는 경로 접두사입니다. 예를 들어/
는 모두 일치합니다.INFERENCE_POOL_NAME
: 트래픽을 라우트하려는InferencePool
리소스의 이름입니다. 예를 들면vllm-llama3-8b-instruct
입니다.
매니페스트를 클러스터에 적용합니다.
kubectl apply -f httproute.yaml
추론 요청 보내기
GKE 추론 게이트웨이를 구성한 후에는 배포된 모델에 추론 요청을 보낼 수 있습니다. 이렇게 하면 입력 프롬프트와 지정된 매개변수를 기반으로 텍스트를 생성할 수 있습니다.
추론 요청을 보내려면 다음 단계를 따르세요.
게이트웨이 엔드포인트를 가져오려면 다음 명령어를 실행합니다.
IP=$(kubectl get gateway/GATEWAY_NAME -o jsonpath='{.status.addresses[0].value}') PORT=PORT_NUMBER # Use 80 for HTTP
다음을 바꿉니다.
GATEWAY_NAME
: 게이트웨이 리소스의 이름입니다.PORT_NUMBER
: 게이트웨이에서 구성한 포트 번호입니다.
curl
를 사용하여/v1/completions
엔드포인트에 요청을 전송하려면 다음 명령어를 실행합니다.curl -i -X POST ${IP}:${PORT}/v1/completions \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer $(gcloud auth print-access-token)' \ -d '{ "model": "MODEL_NAME", "prompt": "PROMPT_TEXT", "max_tokens": MAX_TOKENS, "temperature": "TEMPERATURE" }'
다음을 바꿉니다.
MODEL_NAME
: 사용할 모델 또는 LoRA 어댑터의 이름입니다.PROMPT_TEXT
: 모델의 입력 프롬프트입니다.MAX_TOKENS
: 응답에서 생성할 최대 토큰 수입니다.TEMPERATURE
: 출력의 무작위성을 제어합니다. 확정적인 출력에는0
값을 사용하고, 더 창의적인 출력에는 더 큰 숫자를 사용합니다.
다음 예는 GKE 추론 게이트웨이에 샘플 요청을 보내는 방법을 보여줍니다.
curl -i -X POST ${IP}:${PORT}/v1/completions -H 'Content-Type: application/json' -H 'Authorization: Bearer $(gcloud auth print-access-token)' -d '{
"model": "food-review",
"prompt": "What is the best pizza in the world?",
"max_tokens": 2048,
"temperature": "0"
}'
다음 동작에 유의하세요.
- 요청 본문: 요청 본문에는
stop
및top_p
와 같은 추가 매개변수가 포함될 수 있습니다. 전체 옵션 목록은 OpenAI API 사양을 참고하세요. - 오류 처리: 클라이언트 코드에 적절한 오류 처리를 구현하여 응답에서 발생할 수 있는 오류를 처리합니다. 예를 들어
curl
응답에서 HTTP 상태 코드를 확인합니다.200
가 아닌 상태 코드는 일반적으로 오류를 나타냅니다. - 인증 및 승인: 프로덕션 배포의 경우 인증 및 승인 메커니즘으로 API 엔드포인트를 보호합니다. 요청에 적절한 헤더 (예:
Authorization
)를 포함합니다.