Esegui il deployment di GKE Inference Gateway


Questa pagina descrive come eseguire il deployment di GKE Inference Gateway.

Questa pagina è rivolta agli esperti di networking responsabili della gestione dell'infrastruttura GKE e agli amministratori della piattaforma che gestiscono i carichi di lavoro di IA.

Prima di leggere questa pagina, assicurati di conoscere quanto segue:

GKE Inference Gateway migliora Gateway di Google Kubernetes Engine (GKE) per ottimizzare la pubblicazione di applicazioni di IA generativa. GKE Inference Gateway ti consente di ottimizzare la pubblicazione dei workload di IA generativa su GKE. Offre gestione e scalabilità efficienti dei carichi di lavoro di IA, consente obiettivi di prestazioni specifici del carico di lavoro come la latenza e migliora l'utilizzo delle risorse, l'osservabilità e la sicurezza dell'IA.

Prima di iniziare

Prima di iniziare, assicurati di aver eseguito le seguenti operazioni:

  • Attiva l'API Google Kubernetes Engine.
  • Attiva l'API Google Kubernetes Engine
  • Se vuoi utilizzare Google Cloud CLI per questa attività, installa e poi inizializza gcloud CLI. Se hai già installato l'interfaccia a riga di comando gcloud, ottieni la versione più recente eseguendo gcloud components update.
  • Se necessario, abilita l'API Compute Engine, l'API Network Services e l'API Model Armor.

    Vai ad Abilita l'accesso alle API e segui le istruzioni.

Requisiti di GKE Gateway Controller

  • Versione GKE 1.32.3.
  • Google Cloud CLI versione 407.0.0 o successive.
  • L'API Gateway è supportata solo nei cluster nativi VPC.
  • Devi attivare una subnet solo proxy.
  • Nel cluster deve essere attivato il componente aggiuntivo HttpLoadBalancing.
  • Se utilizzi Istio, devi eseguire l'upgrade a una delle seguenti versioni:
    • 1.15.2 o versioni successive
    • 1.14.5 o versioni successive
    • 1.13.9 o versioni successive
  • Se utilizzi un VPC condiviso, nel progetto host devi assegnare il ruolo Compute Network User all'account di servizio GKE per il progetto di servizio.

Restrizioni e limitazioni

Si applicano le seguenti limitazioni:

  • I gateway multicluster non sono supportati.
  • GKE Inference Gateway è supportato solo per le risorse GatewayClass gke-l7-regional-external-managed e gke-l7-rilb.
  • I bilanciatori del carico delle applicazioni interni tra regioni non sono supportati.

Configura GKE Inference Gateway

Per configurare GKE Inference Gateway, considera questo esempio. Un team esegue i modelli vLLM e Llama3 ed esegue esperimenti attivi con due adattatori LoRA distinti ottimizzati: "food-review" e "cad-fabricator".

Il flusso di lavoro di alto livello per la configurazione di GKE Inference Gateway è il seguente:

  1. Prepara l'ambiente: configura l'infrastruttura e i componenti necessari.
  2. Crea un pool di inferenza: definisci un pool di server di modelli utilizzando la risorsa personalizzata InferencePool.
  3. Specifica gli scopi di pubblicazione del modello: specifica gli scopi del modello utilizzando la risorsa personalizzata InferenceModel.
  4. Crea il gateway: esponi il servizio di inferenza utilizzando l'API Gateway.
  5. Crea HTTPRoute: definisci come il traffico HTTP viene indirizzato al servizio di inferenza.
  6. Invia richieste di inferenza: invia richieste al modello di cui è stato eseguito il deployment.

prepara l'ambiente

  1. Installa Helm.

  2. Crea un cluster GKE:

  3. Per installare le definizioni delle risorse personalizzate (CRD) InferencePool e InferenceModel nel cluster GKE, esegui il seguente comando:

    kubectl apply -f https://github.com/kubernetes-sigs/gateway-api-inference-extension/releases/download/v0.3.0/manifests.yaml
    

    Sostituisci VERSION con la versione dei CRD che vuoi installare (ad esempio v0.3.0).

  4. Se utilizzi una versione di GKE precedente alla v1.32.2-gke.1182001 e vuoi utilizzare Model Armor con GKE Inference Gateway, devi installare i CRD di estensione per il traffico e il routing:

    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. Per configurare l'autorizzazione per lo scraping delle metriche, crea il segreto 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
    

Crea un server di modelli e il deployment del modello

Questa sezione mostra come eseguire il deployment di un server di modelli e di un modello. L'esempio utilizza un vLLM server di modelli con un modello Llama3. Il deployment è etichettato come app:vllm-llama3-8b-instruct. Questo deployment utilizza anche due adattatori LoRa chiamati food-review e cad-fabricator di Hugging Face.

Puoi adattare questo esempio al tuo contenitore del server del modello e al tuo modello, alla porta di servizio e al nome di deployment. Puoi anche configurare gli adattatori LoRa nel deployment o eseguire il deployment del modello di base. I passaggi riportati di seguito descrivono come creare le risorse Kubernetes necessarie.

  1. Crea un secret di Kubernetes per archiviare il token di Hugging Face. Questo token viene utilizzato per accedere agli adattatori LoRA:

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

    Sostituisci HF_TOKEN con il tuo token Hugging Face.

  2. Per eseguire il deployment su un tipo di acceleratore nvidia-h100-80gb, salva il seguente manifest come vllm-llama3-8b-instruct.yaml. Questo manifest definisce un deployment Kubernetes con il modello e il server di modelli:

    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: 600
                # 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. Applica il manifest di esempio al cluster:

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

Dopo aver applicato il manifest, tieni conto dei seguenti campi e parametri chiave:

  • replicas: specifica il numero di pod per il deployment.
  • image: specifica l'immagine Docker per il server di modelli.
  • command: specifica il comando da eseguire all'avvio del container.
  • args: specifica gli argomenti da passare al comando.
  • env: specifica le variabili di ambiente per il contenitore.
  • ports: specifica le porte esposte dal container.
  • resources: specifica le richieste e i limiti delle risorse per il contenitore, ad esempio la GPU.
  • volumeMounts: specifica la modalità di montaggio dei volumi nel container.
  • initContainers: specifica i container che vengono eseguiti prima del container dell'applicazione.
  • restartPolicy: specifica il criterio di riavvio per i pod.
  • terminationGracePeriodSeconds: specifica il periodo di tolleranza per la chiusura del pod.
  • volumes: specifica i volumi utilizzati dai pod.

Puoi modificare questi campi in base ai tuoi requisiti specifici.

Crea un pool di inferenza

La risorsa personalizzata InferencePool Kubernetes definisce un gruppo di pod con un modello linguistico di grandi dimensioni (LLM) di base e una configurazione di calcolo comuni. Il campo selector specifica i pod che appartengono a questo pool. Le etichette in questo selezionatore devono corrispondere esattamente a quelle applicate ai pod del server di modelli. Il campo targetPort definisce le porte utilizzate dal server di modelli all'interno dei pod. Il campo extensionRef fa riferimento a un servizio di estensione che fornisce funzionalità aggiuntive per il pool di inferenza. InferencePool consente a GKE Inference Gateway di indirizzare il traffico ai pod del server di modelli.

Prima di creare il InferencePool, assicurati che i pod selezionati dal InferencePool siano già in esecuzione.

Per creare un InferencePool utilizzando Helm:

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

Modifica il seguente campo in base al tuo deployment:

  • inferencePool.modelServers.matchLabels.app: la chiave dell'etichetta utilizzata per selezionare i pod del server di modelli.

L'installazione di Helm installa automaticamente il criterio di timeout, l'endpoint-picker e i pod necessari per l'osservabilità.

Viene creato un oggetto InferencePool: vllm-llama3-8b-instruct che fa riferimento ai servizi endpoint del modello all'interno dei pod. Viene anche creato un deployment del selettore di endpoint denominato app:vllm-llama3-8b-instruct-epp per questo InferencePool creato.

Specifica gli obiettivi di pubblicazione del modello

La risorsa personalizzata InferenceModel definisce un modello specifico da pubblicare che include il supporto per i modelli sintonizzati su LoRa e la relativa criticità di pubblicazione. Devi definire quali modelli vengono pubblicati su un InferencePool creando risorse InferenceModel. Queste risorse InferenceModel possono fare riferimento a modelli di base o ad adattatori LoRa supportati dai server di modelli in InferencePool.

Il campo modelName specifica il nome del modello di base o dell'adattatore LoRa. Il campo Criticality specifica la criticità della pubblicazione del modello. Il campo poolRef specifica il InferencePool su cui viene pubblicato questo modello.

Per creare un InferenceModel, svolgi i seguenti passaggi:

  1. Salva il seguente manifest di esempio come 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
    

    Sostituisci quanto segue:

    • MODEL_NAME: il nome del modello di base o dell'adattatore LoRa. Ad esempio, food-review.
    • VALUE: la criticità di pubblicazione scelta. Scegli tra Critical, Standard o Sheddable. Ad esempio, Standard.
    • INFERENCE_POOL_NAME: il nome del InferencePool creato nel passaggio precedente. Ad esempio, vllm-llama3-8b-instruct.
  2. Applica il manifest di esempio al cluster:

    kubectl apply -f inferencemodel.yaml
    

L'esempio seguente crea un oggetto InferenceModel che configura il food-review modello LoRA su vllm-llama3-8b-instruct InferencePool con un'Standard criticità del servizio. L'oggetto InferenceModel configura inoltre il modello di base da pubblicare con un livello di priorità 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

Crea il gateway

La risorsa Gateway è il punto di contatto per il traffico esterno nel tuo cluster Kubernetes. Definisce gli ascoltatori che accettano le connessioni in entrata.

GKE Inference Gateway funziona con le seguenti classi di gateway:

  • gke-l7-rilb: per i bilanciatori del carico delle applicazioni interni regionali.
  • gke-l7-regional-external-managed

Per ulteriori informazioni, consulta la documentazione relativa alle classi gateway.

Per creare un gateway:

  1. Salva il seguente manifest di esempio come 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
    

    Sostituisci GATEWAY_NAME con un nome univoco per la risorsa Gateway (ad esempio inference-gateway) e GATEWAY_CLASS con la classe Gateway che vuoi utilizzare (ad esempio gke-l7-regional-external-managed).

  2. Applica il manifest al cluster:

    kubectl apply -f gateway.yaml
    

Nota: per ulteriori informazioni sulla configurazione di TLS per proteggere il tuo gateway con HTTPS, consulta la documentazione di GKE sulla configurazione di TLS.

Crea il HTTPRoute

La risorsa HTTPRoute definisce in che modo GKE Gateway instrada le richieste HTTP in entrata ai servizi di backend, che in questo contesto sono i tuoi InferencePool. La risorsa HTTPRoute specifica le regole di corrispondenza (ad esempio intestazioni o percorsi) e il backend a cui deve essere inoltrato il traffico.

  1. Per creare un HTTPRoute, salva il seguente manifest di esempio come 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
          kind: InferencePool
    

    Sostituisci quanto segue:

    • HTTPROUTE_NAME: un nome univoco per la risorsa HTTPRoute. Ad esempio: my-route.
    • GATEWAY_NAME: il nome della risorsa Gateway che hai creato. Ad esempio: inference-gateway.
    • PATH_PREFIX: il prefisso del percorso utilizzato per abbinare le richieste in arrivo. Ad esempio, / per trovare una corrispondenza per tutti.
    • INFERENCE_POOL_NAME: il nome della risorsaInferencePool a cui vuoi indirizzare il traffico. Ad esempio: vllm-llama3-8b-instruct.
  2. Applica il manifest al cluster:

    kubectl apply -f httproute.yaml
    

Invia richiesta di inferenza

Dopo aver configurato GKE Inference Gateway, puoi inviare richieste di inferenza al modello di cui è stato eseguito il deployment. In questo modo puoi generare testo in base al prompt di input e ai parametri specificati.

Per inviare richieste di inferenza:

  1. Per ottenere l'endpoint del gateway, esegui il seguente comando:

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

    Sostituisci quanto segue:

    • GATEWAY_NAME: il nome della risorsa gateway.
    • PORT_NUMBER: il numero di porta configurato nel gateway.
  2. Per inviare una richiesta all'endpoint /v1/completions utilizzando curl, esegui il seguente comando:

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

    Sostituisci quanto segue:

    • MODEL_NAME: il nome del modello o dell'adattatore LoRa da utilizzare.
    • PROMPT_TEXT: il prompt di input per il modello.
    • MAX_TOKENS: il numero massimo di token da generare nella risposta.
    • TEMPERATURE: controlla la casualità dell'output. Utilizza il valore 0 per un output deterministico o un numero più alto per un output più creativo.

L'esempio seguente mostra come inviare una richiesta di esempio a 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"
}'

Tieni presente i seguenti comportamenti:

  • Corpo della richiesta: il corpo della richiesta può includere parametri aggiuntivi come stop e top_p. Per un elenco completo delle opzioni, consulta la specifica dell'API OpenAI.
  • Gestione degli errori: implementa una gestione degli errori adeguata nel codice del client per gestire i potenziali errori nella risposta. Ad esempio, controlla il codice di stato HTTP nella risposta curl. In genere, un codice di stato diverso da 200 indica un errore.
  • Autenticazione e autorizzazione: per i deployment di produzione, proteggi il tuo endpoint API con meccanismi di autenticazione e autorizzazione. Includi le intestazioni appropriate (ad es. Authorization) nelle richieste.

Passaggi successivi