GKE Inference Gateway をデプロイする


このページでは、GKE Inference Gateway のデプロイ方法について説明します。

このページは、GKE インフラストラクチャの管理を担当するネットワーク スペシャリストと、AI ワークロードを管理するプラットフォーム管理者を対象としています。

このページを読む前に、次のことをよく理解しておいてください。

GKE Inference Gateway は、Google Kubernetes Engine(GKE)Gateway を拡張して、生成 AI アプリケーションの提供を最適化します。GKE Inference Gateway を使用すると、GKE での生成 AI ワークロードの提供を最適化できます。これにより、AI ワークロードの効率的な管理とスケーリングが可能になり、レイテンシなどのワークロード固有のパフォーマンス目標を実現できます。また、リソース使用率、オブザーバビリティ、AI の安全性が向上します。

始める前に

作業を始める前に、次のことを確認してください。

  • Google Kubernetes Engine API を有効にする。
  • Google Kubernetes Engine API の有効化
  • このタスクに Google Cloud CLI を使用する場合は、gcloud CLI をインストールして初期化する。すでに gcloud CLI をインストールしている場合は、gcloud components update を実行して最新のバージョンを取得する。

GKE Gateway コントローラの要件

  • 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 ロールを割り当てる必要があります。

制限事項

次の制限事項があります。

  • マルチクラスタ Gateway はサポート対象外です。
  • GKE Inference Gateway は、gke-l7-regional-external-managedgke-l7-rilb の GatewayClass リソースでのみサポートされます。
  • クロスリージョン内部アプリケーション ロードバランサはサポートされていません。

GKE Inference Gateway を構成する

次のような例で GKE Inference Gateway を構成する場合について考えてみましょう。あるチームが vLLM モデルと Llama3 モデルを実行し、2 つの異なる LoRA ファインチューニング アダプタ(food-review と cad-fabricator)を積極的にテストしています。

GKE Inference Gateway を構成するワークフローの概要は次のとおりです。

  1. 環境を準備する: 必要なインフラストラクチャとコンポーネントを設定します。
  2. 推論プールを作成する: InferencePool カスタム リソースを使用して、モデルサーバーのプールを定義します。
  3. モデル サービング目標を指定する: InferenceModel カスタム リソースを使用してモデル目標を指定します。
  4. Gateway を作成する: Gateway API を使用して推論サービスを公開します。
  5. HTTPRoute を作成する: HTTP トラフィックを推論サービスにルーティングする方法を定義します。
  6. 推論リクエストを送信する: デプロイされたモデルにリクエストを送信します。

環境を準備する

  1. Helm をインストールします。

  2. GKE クラスタを作成します。

    • バージョン 1.31 以降の GKE Autopilot クラスタまたは GKE Standard クラスタを作成します。手順については、GKE クラスタを作成するをご覧ください。
    • 目的のコンピューティング ファミリーとアクセラレータを使用してノードを構成します。
    • 選択したアクセラレータ、モデル、パフォーマンスのニーズに基づいて事前に構成され、テストされているデプロイ マニフェストについては、GKE Inference Quickstart レシピでベスト プラクティス推論を実行するをご覧ください。
  3. GKE クラスタに InferencePoolInferenceModel のカスタム リソース定義(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 など)に置き換えます。

  4. v1.32.2-gke.1182001 より前の GKE バージョンを使用しているときに、GKE Inference Gateway で Model Armor を使用する場合は、トラフィックとルーティングの拡張機能 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
    
  5. 指標をスクレイピングするための認可を設定するには、inference-gateway-sa-metrics-reader-secret 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
    

モデルサーバーとモデルのデプロイメントを作成する

このセクションでは、モデルサーバーとモデルをデプロイする方法について説明します。この例では、vLLM モデルサーバーと Llama3 モデルを使用しています。Deployment に app:vllm-llama3-8b-instruct というラベルが付いています。この Deployment は、Hugging Face の food-reviewcad-fabricator という 2 つの LoRA アダプタも使用します。

この例は、独自のモデルサーバー コンテナとモデル、サービング ポート、デプロイ名に適応させることができます。また、Deployment で LoRA アダプタを構成することも、ベースモデルをデプロイすることもできます。次の手順では、必要な Kubernetes リソースを作成する方法について説明します。

  1. Hugging Face トークンを保存する Kubernetes Secret を作成します。このトークンは、LoRA アダプタにアクセスするために使用されます。

    kubectl create secret generic hf-token --from-literal=token=HF_TOKEN
    

    HF_TOKEN は、Hugging Face トークンに置き換えます。

  2. nvidia-h100-80gb アクセラレータ タイプにデプロイするには、次のマニフェストを vllm-llama3-8b-instruct.yaml として保存します。このマニフェストでは、モデルとモデルサーバーを含む Kubernetes Deployment を定義します。

    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
    
  3. マニフェストをクラスタに適用します。

    kubectl apply -f vllm-llama3-8b-instruct.yaml
    

マニフェストを適用したら、次のフィールドとパラメータについて検討します。

  • replicas: Deployment の Pod 数を指定します。
  • image: モデルサーバー用の Docker イメージを指定します。
  • command: コンテナの起動時に実行するコマンドを指定します。
  • args: コマンドに渡す引数を指定します。
  • env: コンテナの環境変数を指定します。
  • ports: コンテナで公開されるポートを指定します。
  • resources: コンテナのリソース リクエストと上限(GPU など)を指定します。
  • volumeMounts: ボリュームをコンテナにマウントする方法を指定します。
  • initContainers: アプリケーション コンテナの前に実行されるコンテナを指定します。
  • restartPolicy: Pod の再起動ポリシーを指定します。
  • terminationGracePeriodSeconds: Pod の終了の猶予期間を指定します。
  • volumes: Pod で使用されるボリュームを指定します。

これらのフィールドは、特定の要件に合わせて変更できます。

推論プールを作成する

InferencePool Kubernetes カスタム リソースは、共通のベースとなる大規模言語モデル(LLM)とコンピューティング構成を持つ Pod のグループを定義します。selector フィールドには、このプールに属する Pod を指定します。このセレクタのラベルは、モデルサーバー Pod に適用されるラベルと完全に一致している必要があります。targetPort フィールドは、モデルサーバーが Pod 内で使用するポートを定義します。extensionRef フィールドは、推論プールに追加機能を提供する拡張機能サービスを参照します。InferencePool により、GKE Inference Gateway はモデルサーバー Pod にトラフィックを転送できるようになります。

InferencePool を作成する前に、InferencePool が選択する Pod がすでに実行されていることを確認します。

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

次のフィールドを Deployment に合わせて変更します。

  • inferencePool.modelServers.matchLabels.app: モデルサーバー Pod の選択に使用されるラベルのキー。

Helm のインストールにより、タイムアウト ポリシー、エンドポイント ピッカー、オブザーバビリティに必要な Pod が自動的にインストールされます。

これにより、Pod 内のモデル エンドポイント サービスを参照する InferencePool オブジェクト vllm-llama3-8b-instruct が作成されます。また、この作成された InferencePoolapp:vllm-llama3-8b-instruct-epp という名前のエンドポイント ピッカーの Deployment も作成されます。

モデル サービングの目標を指定する

InferenceModel カスタム リソースは、LoRA チューニング済みモデルのサポートとそのサービングの重要度を含む特定のモデルを定義します。InferencePool でサービングされるモデルを定義するには、InferenceModel リソースを作成する必要があります。これらの InferenceModel リソースは、InferencePool のモデルサーバーでサポートされているベースモデルまたは LoRA アダプタを参照できます。

modelName フィールドには、ベースモデルまたは LoRA アダプタの名前を指定します。Criticality フィールドには、モデルのサービングの重要度を指定します。poolRef フィールドには、このモデルが提供される InferencePool を指定します。

InferenceModel を作成する手順は次のとおりです。

  1. 次のサンプル マニフェストを 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: 選択したサービングの重要度。CriticalStandardSheddable から選択します。例: Standard
    • INFERENCE_POOL_NAME: 前の手順で作成した InferencePool の名前。例: vllm-llama3-8b-instruct
  2. マニフェストをクラスタに適用します。

    kubectl apply -f inferencemodel.yaml
    

次の例では、サービングの重要度が Standard で、vllm-llama3-8b-instruct InferencePoolfood-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

Gateway を作成する

Gateway リソースは、Kubernetes クラスタへの外部トラフィックのエントリ ポイントです。受信接続を受け入れるリスナーを定義します。

GKE Inference Gateway は、次の Gateway クラスで動作します。

  • gke-l7-rilb: リージョン内部アプリケーション ロードバランサの場合
  • gke-l7-regional-external-managed

詳細については、Gateway クラスのドキュメントをご覧ください。

Gateway を作成するには、次の操作を行います。

  1. 次のサンプル マニフェストを 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 は、Gateway リソースの一意の名前(inference-gateway など)に置き換えます。GATEWAY_CLASS は、使用する Gateway クラス(gke-l7-regional-external-managed など)に置き換えます。

  2. マニフェストをクラスタに適用します。

    kubectl apply -f gateway.yaml
    

: HTTPS で Gateway を保護するように TLS を構成する方法については、GKE のドキュメントで TLS 構成の説明をご覧ください。

HTTPRoute を作成する

HTTPRoute リソースは、GKE Gateway が受信した HTTP リクエストをバックエンド サービスに転送する方法を定義します。このコンテキストでは、InferencePool です。HTTPRoute リソースには、一致ルール(ヘッダーやパスなど)と、トラフィックを転送するバックエンドを指定します。

  1. 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
  2. マニフェストをクラスタに適用します。

    kubectl apply -f httproute.yaml
    

推論リクエストを送信する

GKE Inference Gateway を構成したら、デプロイされたモデルに推論リクエストを送信できます。これにより、入力プロンプトと指定されたパラメータに基づいてテキストを生成できます。

推論リクエストを送信する手順は次のとおりです。

  1. Gateway エンドポイントを取得するには、次のコマンドを実行します。

    IP=$(kubectl get gateway/GATEWAY_NAME -o jsonpath='{.status.addresses[0].value}')
    PORT=PORT_NUMBER # Use 80 for HTTP
    

    次のように置き換えます。

    • GATEWAY_NAME: Gateway リソースの名前。
    • PORT_NUMBER: Gateway で構成したポート番号。
  2. 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 Inference Gateway にサンプル リクエストを送信する方法を示しています。

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

次の動作に注意してください。

  • リクエスト本文: リクエスト本文には、stoptop_p などの追加パラメータを指定できます。オプションの一覧については、OpenAI API 仕様をご覧ください。
  • エラー処理: クライアント コードに適切なエラー処理を実装して、レスポンスで発生する可能性のあるエラーを処理します。たとえば、curl レスポンスの HTTP ステータス コードを確認します。200 以外のステータス コードは通常、エラーを示します。
  • 認証と認可: 本番環境のデプロイでは、認証と認可メカニズムを使用して API エンドポイントを保護します。適切なヘッダー(Authorization など)をリクエストに含めます。

次のステップ