Gestire un LLM con GKE Inference Gateway


Questo tutorial descrive come eseguire il deployment di un modello linguistico di grandi dimensioni (LLM) su Google Kubernetes Engine (GKE) con GKE Inference Gateway. Il tutorial include i passaggi per la configurazione del cluster, il deployment del modello, la configurazione di GKE Inference Gateway e la gestione delle richieste LLM.

Questo tutorial è rivolto a ingegneri di machine learning (ML), amministratori e operatori di piattaforme e specialisti di dati e AI che vogliono eseguire il deployment e gestire applicazioni LLM utilizzando LLM su GKE con GKE Inference Gateway.

Prima di leggere questa pagina, acquisisci familiarità con quanto segue:

Sfondo

Questa sezione descrive le tecnologie chiave utilizzate in questo tutorial. Per ulteriori informazioni sui concetti e sulla terminologia relativi al servizio di modelli e su come le funzionalità di AI generativa di GKE possono migliorare e supportare le prestazioni del servizio di modelli, consulta Informazioni sull'inferenza dei modelli su GKE.

vLLM

vLLM è un framework di gestione degli LLM open source altamente ottimizzato che aumenta la velocità effettiva di gestione sulle GPU, con funzionalità come le seguenti:

  • Implementazione ottimizzata di Transformer con PagedAttention
  • Batching continuo che migliora la velocità effettiva complessiva della pubblicazione
  • Parallelismo dei tensori e pubblicazione distribuita su più GPU

Per saperne di più, consulta la documentazione di vLLM.

GKE Inference Gateway

GKE Inference Gateway migliora le funzionalità di GKE per la pubblicazione di LLM. Ottimizza i workload di inferenza con funzionalità come:

  • Bilanciamento del carico ottimizzato per l'inferenza basato sulle metriche di carico.
  • Supporto per l'erogazione densa di più carichi di lavoro degli adattatori LoRA.
  • Routing basato sul modello per operazioni semplificate.

Per maggiori informazioni, consulta Informazioni su GKE Inference Gateway.

Obiettivi

  1. Accedere al modello.
  2. Prepara l'ambiente.
  3. Crea e configura le Google Cloud risorse.
  4. Installa le CRD InferenceModel e InferencePool.
  5. Esegui il deployment del server del modello.
  6. Configura l'osservabilità per Inference Gateway.

Prima di iniziare

  • Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  • In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  • Verify that billing is enabled for your Google Cloud project.

  • Enable the required API.

    Enable the API

  • In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  • Verify that billing is enabled for your Google Cloud project.

  • Enable the required API.

    Enable the API

  • Make sure that you have the following role or roles on the project: roles/container.admin, roles/iam.serviceAccountAdmin

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Vai a IAM
    2. Seleziona il progetto.
    3. Fai clic su Concedi l'accesso.
    4. Nel campo Nuove entità, inserisci il tuo identificatore dell'utente. In genere si tratta dell'indirizzo email di un Account Google.

    5. Nell'elenco Seleziona un ruolo, seleziona un ruolo.
    6. Per concedere altri ruoli, fai clic su Aggiungi un altro ruolo e aggiungi ogni ruolo aggiuntivo.
    7. Fai clic su Salva.
    8. Ottenere l'accesso al modello

      Per eseguire il deployment del modello Llama3.1 su GKE, firma il contratto di consenso alla licenza e genera un token di accesso Hugging Face.

      Per utilizzare il modello Llama3.1 devi firmare il contratto di consenso. Segui queste istruzioni:

      1. Accedi alla pagina del consenso e verifica il consenso per l'utilizzo del tuo account Hugging Face.
      2. Accetta i termini del modello.

      Generare un token di accesso

      Per accedere al modello tramite Hugging Face, è necessario un token Hugging Face.

      Segui questi passaggi per generare un nuovo token se non ne hai già uno:

      1. Fai clic su Il tuo profilo > Impostazioni > Token di accesso.
      2. Seleziona Nuovo token.
      3. Specifica un nome a tua scelta e un ruolo di almeno Read.
      4. Seleziona Genera un token.
      5. Copia il token generato negli appunti.

      prepara l'ambiente

      In questo tutorial utilizzerai Cloud Shell per gestire le risorse ospitate su Google Cloud. Cloud Shell include il software necessario per questo tutorial, tra cui kubectl e gcloud CLI.

      Per configurare l'ambiente con Cloud Shell, segui questi passaggi:

      1. Nella console Google Cloud , avvia una sessione di Cloud Shell facendo clic su Icona di attivazione di Cloud Shell Attiva Cloud Shell nella Google Cloud console. Viene avviata una sessione nel riquadro inferiore della console Google Cloud .

      2. Imposta le variabili di ambiente predefinite:

        gcloud config set project PROJECT_ID
        gcloud config set billing/quota_project PROJECT_ID
        export PROJECT_ID=$(gcloud config get project)
        export REGION=REGION
        export CLUSTER_NAME=CLUSTER_NAME
        export HF_TOKEN=HF_TOKEN
        

        Sostituisci i seguenti valori:

        • PROJECT_ID: il tuo Google Cloud ID progetto.
        • REGION: una regione che supporta il tipo di acceleratore che vuoi utilizzare, ad esempio us-central1 per la GPU H100.
        • CLUSTER_NAME: il nome del tuo cluster.
        • HF_TOKEN: il token Hugging Face che hai generato in precedenza.

      Creare e configurare risorse Google Cloud

      Per creare le risorse richieste, segui queste istruzioni.

      Crea un cluster GKE e un pool di nodi

      Gestisci LLM su GPU in un cluster GKE Autopilot o Standard. Ti consigliamo di utilizzare un cluster Autopilot per un'esperienza Kubernetes completamente gestita. Per scegliere la modalità operativa GKE più adatta ai tuoi carichi di lavoro, consulta Scegliere una modalità operativa GKE.

      Autopilot

      In Cloud Shell, esegui questo comando:

      gcloud container clusters create-auto CLUSTER_NAME \
          --project=PROJECT_ID \
          --location=CONTROL_PLANE_LOCATION \
          --release-channel=rapid
      

      Sostituisci i seguenti valori:

      • PROJECT_ID: il tuo Google Cloud ID progetto.
      • CONTROL_PLANE_LOCATION: la regione di Compute Engine del control plane del tuo cluster. Fornisci una regione che supporti il tipo di acceleratore che vuoi utilizzare, ad esempio us-central1 per la GPU H100.
      • CLUSTER_NAME: il nome del tuo cluster.

      GKE crea un cluster Autopilot con nodi CPU e GPU come richiesto dai carichi di lavoro di cui è stato eseguito il deployment.

      Standard

      1. In Cloud Shell, esegui questo comando per creare un cluster Standard:

        gcloud container clusters create CLUSTER_NAME \
            --project=PROJECT_ID \
            --location=CONTROL_PLANE_LOCATION \
            --workload-pool=PROJECT_ID.svc.id.goog \
            --release-channel=rapid \
            --num-nodes=1 \
            --enable-managed-prometheus \
            --monitoring=SYSTEM,DCGM \
            --gateway-api=standard
        

        Sostituisci i seguenti valori:

        • PROJECT_ID: il tuo Google Cloud ID progetto.
        • CONTROL_PLANE_LOCATION: la regione di Compute Engine del control plane del tuo cluster. Fornisci una regione che supporti il tipo di acceleratore che vuoi utilizzare, ad esempio us-central1 per la GPU H100.
        • CLUSTER_NAME: il nome del tuo cluster.

        La creazione del cluster potrebbe richiedere diversi minuti.

      2. Per creare un node pool con le dimensioni del disco appropriate per l'esecuzione del modello Llama-3.1-8B-Instruct, esegui il comando seguente:

        gcloud container node-pools create gpupool \
            --accelerator type=nvidia-h100-80gb,count=2,gpu-driver-version=latest \
            --project=PROJECT_ID \
            --location=CONTROL_PLANE_LOCATION \
            --node-locations=CONTROL_PLANE_LOCATION-a \
            --cluster=CLUSTER_NAME \
            --machine-type=a3-highgpu-2g \
            --num-nodes=1 \
            --disk-type="pd-standard"
        

        GKE crea un singolo pool di nodi contenente una GPU H100.

      1. Per configurare l'autorizzazione per eseguire lo scraping delle metriche, crea il secret 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 secret Kubernetes per le credenziali di Hugging Face

      In Cloud Shell:

      1. Per comunicare con il cluster, configura kubectl:

          gcloud container clusters get-credentials CLUSTER_NAME \
              --location=CONTROL_PLANE_LOCATION
        

        Sostituisci i seguenti valori:

        • CONTROL_PLANE_LOCATION: la regione di Compute Engine del control plane del cluster.
        • CLUSTER_NAME: il nome del tuo cluster.
      2. Crea un secret di Kubernetes che contenga il token Hugging Face:

          kubectl create secret generic HF_SECRET \
              --from-literal=token=HF_TOKEN \
              --dry-run=client -o yaml | kubectl apply -f -
        

        Sostituisci quanto segue:

        • HF_TOKEN: il token Hugging Face che hai generato in precedenza.
        • HF_SECRET: il nome del secret Kubernetes. Ad esempio, hf-secret.

      Installa le CRD InferenceModel e InferencePool

      In questa sezione, installa le definizioni di risorse personalizzate (CRD) necessarie per GKE Inference Gateway.

      Le CRD estendono l'API Kubernetes. In questo modo puoi definire nuovi tipi di risorse. Per utilizzare GKE Inference Gateway, installa i CRD InferencePool e InferenceModel nel tuo cluster GKE eseguendo il seguente comando:

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

      Esegui il deployment del server del modello

      Questo esempio esegue il deployment di un modello Llama3.1 utilizzando un server di modelli vLLM. Il deployment è etichettato come app:vllm-llama3-8b-instruct. Questo deployment utilizza anche due adattatori LoRA denominati food-review e cad-fabricator di Hugging Face. Puoi aggiornare questo deployment con il tuo server di modelli e il tuo contenitore di modelli, la porta di pubblicazione e il nome del deployment. Puoi configurare facoltativamente gli adattatori LoRA nel deployment o eseguire il deployment del modello di base.

      1. 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 tuo modello e il server del modello:

        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: VLLM_USE_V1
                      value: "1"
                    - 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 the 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
        
      2. Applica il manifest al cluster:

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

      Crea una risorsa InferencePool

      La risorsa personalizzata Kubernetes InferencePool definisce un gruppo di pod con una configurazione di calcolo e LLM di base comune.

      La risorsa personalizzata InferencePool include i seguenti campi chiave:

      • selector: specifica quali pod appartengono a questo pool. Le etichette in questo selettore devono corrispondere esattamente a quelle applicate ai pod del server del modello.
      • targetPort: definisce le porte utilizzate dal server del modello all'interno dei pod.

      La risorsa InferencePool consente a GKE Inference Gateway di indirizzare il traffico ai pod del server di modelli.

      Per creare un InferencePool utilizzando Helm, segui questi passaggi:

      helm install vllm-llama3-8b-instruct \
        --set inferencePool.modelServers.matchLabels.app=vllm-llama3-8b-instruct \
        --set provider.name=gke \
        --set healthCheckPolicy.create=false \
        --version v0.3.0 \
        oci://registry.k8s.io/gateway-api-inference-extension/charts/inferencepool
      

      Modifica il seguente campo in modo che corrisponda al tuo deployment:

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

      Questo comando crea un oggetto InferencePool che rappresenta logicamente il deployment del server del modello e fa riferimento ai servizi endpoint del modello all'interno dei pod selezionati da Selector.

      Crea una risorsa InferenceModel con una criticità di pubblicazione

      La risorsa personalizzata Kubernetes InferenceModel definisce un modello specifico, inclusi i modelli ottimizzati con LoRA, e la sua criticità di pubblicazione.

      La risorsa personalizzata InferenceModel include i seguenti campi chiave:

      • modelName: specifica il nome del modello base o dell'adattatore LoRA.
      • Criticality: specifica la criticità della pubblicazione del modello.
      • poolRef: fa riferimento al InferencePool su cui viene pubblicato il modello.

      InferenceModel consente a GKE Inference Gateway di instradare il traffico verso i pod del server del modello in base al nome e alla criticità del modello.

      Per creare un InferenceModel, segui questi 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: CRITICALITY
          poolRef:
            name: INFERENCE_POOL_NAME
        

        Sostituisci quanto segue:

        • MODEL_NAME: il nome del modello di base o dell'adattatore LoRA. Ad esempio, food-review.
        • CRITICALITY: la criticità di pubblicazione scelta. Scegli tra Critical, Standard o Sheddable. Ad esempio, Standard.
        • INFERENCE_POOL_NAME: il nome di 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 modello food-review LoRA su vllm-llama3-8b-instruct InferencePool con una criticità di pubblicazione Standard. L'oggetto InferenceModel configura anche 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 funge da punto di ingresso per il traffico esterno nel tuo cluster Kubernetes. Definisce i listener che accettano le connessioni in entrata.

      GKE Inference Gateway supporta le classi Gateway gke-l7-rilb e gke-l7-regional-external-managed. Per saperne di più, consulta la documentazione di GKE sulle classi Gateway.

      Per creare un gateway, segui questi passaggi:

      1. Salva il seguente manifest di esempio come gateway.yaml:

        apiVersion: gateway.networking.k8s.io/v1
        kind: Gateway
        metadata:
          name: GATEWAY_NAME
        spec:
          gatewayClassName: gke-l7-regional-external-managed
          listeners:
            - protocol: HTTP # Or HTTPS for production
              port: 80 # Or 443 for HTTPS
              name: http
        

        Sostituisci GATEWAY_NAME con un nome univoco per la risorsa Gateway. Ad esempio, inference-gateway.

      2. Applica il manifest al cluster:

        kubectl apply -f gateway.yaml
        

      Crea la risorsa HTTPRoute

      In questa sezione, crei una risorsa HTTPRoute per definire il modo in cui il gateway instrada le richieste HTTP in entrata al tuo InferencePool.

      La risorsa HTTPRoute definisce il modo in cui GKE Gateway instrada le richieste HTTP in entrata ai servizi di backend, ovvero il tuo InferencePool. Specifica le regole di corrispondenza (ad esempio, intestazioni o percorsi) e il backend a cui deve essere inoltrato il traffico.

      Per creare una HTTPRoute, segui questi passaggi:

      1. 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
              group: inference.networking.x-k8s.io
              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 che utilizzi per trovare le richieste in entrata. Ad esempio, / per trovare una corrispondenza con tutti.
        • INFERENCE_POOL_NAME: il nome della risorsa InferencePool a cui vuoi indirizzare il traffico. Ad esempio: vllm-llama3-8b-instruct.
      2. Applica il manifest al cluster:

        kubectl apply -f httproute.yaml
        

      Inviare una richiesta di inferenza

      Dopo aver configurato GKE Inference Gateway, puoi inviare richieste di inferenza al modello di cui è stato eseguito il deployment.

      Per inviare richieste di inferenza:

      • Recupera l'endpoint del gateway.
      • Crea una richiesta JSON formattata correttamente.
      • Utilizza curl per inviare la richiesta all'endpoint /v1/completions.

      In questo modo puoi generare testo in base al prompt di input e ai parametri specificati.

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

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

        Sostituisci quanto segue:

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

        curl -i -X POST https://${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.

      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 client per gestire i potenziali errori nella risposta. Ad esempio, controlla il codice di stato HTTP nella risposta curl. Un codice di stato diverso da 200 in genere indica un errore.
      • Autenticazione e autorizzazione: per i deployment di produzione, proteggi l'endpoint API con meccanismi di autenticazione e autorizzazione. Includi le intestazioni appropriate (ad esempio, Authorization) nelle tue richieste.

      Configurare l'osservabilità per Inference Gateway

      GKE Inference Gateway fornisce osservabilità su integrità, prestazioni e comportamento dei carichi di lavoro di inferenza. Ciò è utile per identificare e risolvere i problemi, ottimizzare l'utilizzo delle risorse e garantire l'affidabilità delle tue applicazioni. Puoi visualizzare queste metriche di osservabilità in Cloud Monitoring tramite Esplora metriche.

      Per configurare l'osservabilità per GKE Inference Gateway, consulta Configura l'osservabilità.

      Elimina le risorse di cui è stato eseguito il deployment

      Per evitare che al tuo account Google Cloud vengano addebitati costi relativi alle risorse che hai creato da questa guida, esegui questo comando:

      gcloud container clusters delete CLUSTER_NAME \
          --location=CONTROL_PLANE_LOCATION
      

      Sostituisci i seguenti valori:

      • CONTROL_PLANE_LOCATION: la regione di Compute Engine del control plane del tuo cluster.
      • CLUSTER_NAME: il nome del tuo cluster.

      Passaggi successivi