Servir un LLM con GKE Inference Gateway

En este tutorial se describe cómo desplegar un modelo de lenguaje grande (LLM) en Google Kubernetes Engine (GKE) con GKE Inference Gateway. El tutorial incluye pasos para configurar el clúster, desplegar el modelo, configurar GKE Inference Gateway y gestionar las solicitudes de LLM.

Este tutorial está dirigido a ingenieros de aprendizaje automático, administradores y operadores de plataformas, y especialistas en datos e IA que quieran desplegar y gestionar aplicaciones de LLM en GKE con GKE Inference Gateway.

Antes de leer esta página, familiarícese con lo siguiente:

Fondo

En esta sección se describen las tecnologías clave que se usan en este tutorial. Para obtener más información sobre los conceptos y la terminología del servicio de modelos, así como sobre cómo las funciones de IA generativa de GKE pueden mejorar y respaldar el rendimiento del servicio de modelos, consulta el artículo Acerca de la inferencia de modelos en GKE.

vLLM

vLLM es un framework de código abierto altamente optimizado para servir LLMs que aumenta el rendimiento de servicio en GPUs. Estas son algunas de las funciones principales:

  • Implementación optimizada de Transformer con PagedAttention
  • Agrupación continua que mejora el rendimiento general del servicio
  • Paralelismo de tensores y servicio distribuido en varias GPUs

Para obtener más información, consulta la documentación de vLLM.

GKE Inference Gateway

GKE Inference Gateway mejora las capacidades de GKE para ofrecer LLMs. Optimiza las cargas de trabajo de inferencia con funciones como las siguientes:

  • Balanceo de carga optimizado para inferencias basado en métricas de carga.
  • Compatibilidad con el servicio denso de varias cargas de trabajo de adaptadores LoRA.
  • Enrutamiento basado en modelos para simplificar las operaciones.

Para obtener más información, consulta Acerca de GKE Inference Gateway.

Acceder al modelo

Para implementar el modelo Llama3.1 en GKE, firma el contrato de licencia y genera un token de acceso de Hugging Face.

Debes firmar el acuerdo de consentimiento para usar el modelo Llama3.1. Te las indicamos a continuación:

  1. Accede a la página de consentimiento y verifica que has dado tu consentimiento para usar tu cuenta de Hugging Face.
  2. Acepta los términos del modelo.

Generar un token de acceso

Para acceder al modelo a través de Hugging Face, necesitas un token de Hugging Face.

Sigue estos pasos para generar un token si aún no tienes uno:

  1. Haz clic en Tu perfil > Configuración > Tokens de acceso.
  2. Selecciona New Token (Nuevo token).
  3. Especifica el nombre que quieras y un rol de al menos Read.
  4. Selecciona Generar un token.
  5. Copia el token generado en el portapapeles.

Prepara tu entorno

En este tutorial, usarás Cloud Shell para gestionar los recursos alojados enGoogle Cloud. Cloud Shell tiene preinstalado el software que necesitas para este tutorial, como kubectl y la CLI de gcloud.

Para configurar tu entorno con Cloud Shell, sigue estos pasos:

  1. En la Google Cloud consola, inicia una sesión de Cloud Shell haciendo clic en Icono de activación de Cloud Shell Activar Cloud Shell en la Google Cloud consola. Se iniciará una sesión en el panel inferior de la consola Google Cloud .

  2. Define las variables de entorno predeterminadas:

    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
    

    Sustituye los siguientes valores:

    • PROJECT_ID: tu Google Cloud ID de proyecto.
    • REGION: una región que admita el tipo de acelerador que quieras usar. Por ejemplo, us-central1 para la GPU H100.
    • CLUSTER_NAME: el nombre de tu clúster.
    • HF_TOKEN: el token de Hugging Face que has generado antes.

Crear y configurar Google Cloud recursos

Crear un clúster y un grupo de nodos de GKE

Sirve LLMs en GPUs en un clúster Autopilot o Standard de GKE. Te recomendamos que uses un clúster de Autopilot para disfrutar de una experiencia de Kubernetes totalmente gestionada. Para elegir el modo de funcionamiento de GKE que mejor se adapte a tus cargas de trabajo, consulta Elegir un modo de funcionamiento de GKE.

Autopilot

En Cloud Shell, ejecuta el siguiente comando:

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

Sustituye los siguientes valores:

  • PROJECT_ID: tu Google Cloud ID de proyecto.
  • CONTROL_PLANE_LOCATION: la región de Compute Engine del plano de control de tu clúster. Proporciona una región que admita el tipo de acelerador que quieras usar. Por ejemplo, us-central1 para la GPU H100.
  • CLUSTER_NAME: el nombre de tu clúster.

GKE crea un clúster de Autopilot con nodos de CPU y GPU según lo soliciten las cargas de trabajo desplegadas.

Estándar

  1. En Cloud Shell, ejecuta el siguiente comando para crear un clúster 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
    

    Sustituye los siguientes valores:

    • PROJECT_ID: tu Google Cloud ID de proyecto.
    • CONTROL_PLANE_LOCATION: la región de Compute Engine del plano de control de tu clúster. Proporciona una región que admita el tipo de acelerador que quieras usar. Por ejemplo, us-central1 para la GPU H100.
    • CLUSTER_NAME: el nombre de tu clúster.

    La creación del clúster puede tardar varios minutos.

  2. Para crear un grupo de nodos con el tamaño de disco adecuado para ejecutar el modelo Llama-3.1-8B-Instruct, ejecuta el siguiente comando:

    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 \
    

    GKE crea un grupo de nodos que contiene una GPU H100.

Configurar la autorización para extraer métricas

Para configurar la autorización para extraer métricas, crea el secreto 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

Crear un secreto de Kubernetes para las credenciales de Hugging Face

En Cloud Shell, haz lo siguiente:

  1. Para comunicarte con tu clúster, configura kubectl:

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

    Sustituye los siguientes valores:

    • CONTROL_PLANE_LOCATION: la región de Compute Engine del plano de control de tu clúster.
    • CLUSTER_NAME: el nombre de tu clúster.
  2. Crea un secreto de Kubernetes que contenga el token de Hugging Face:

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

    Sustituye HF_TOKEN por el token de Hugging Face que has generado anteriormente.

Instala los CRDs InferenceObjective y InferencePool.

En esta sección, instalarás las definiciones de recursos personalizados (CRDs) necesarias para GKE Inference Gateway.

Los CRDs amplían la API de Kubernetes. Esto te permite definir nuevos tipos de recursos. Para usar GKE Inference Gateway, instala las CRDs InferencePool y InferenceObjective en tu clúster de GKE ejecutando el siguiente comando:

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

Desplegar el servidor de modelos

En este ejemplo se despliega un modelo Llama3.1 mediante un servidor de modelos vLLM. El despliegue se ha etiquetado como app:vllm-llama3.1-8b-instruct. Esta implementación también usa dos adaptadores LoRA llamados food-review y cad-fabricator de Hugging Face. Puedes actualizar este despliegue con tu propio servidor de modelos y contenedor de modelos, puerto de servicio y nombre de despliegue. También puedes configurar adaptadores LoRA en la implementación o implementar el modelo base.

  1. Para implementar en un tipo de acelerador nvidia-h100-80gb, guarda el siguiente manifiesto como vllm-llama3.1-8b-instruct.yaml. Este manifiesto define un despliegue de Kubernetes con tu modelo y tu servidor de modelos:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: vllm-llama3.1-8b-instruct
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: vllm-llama3.1-8b-instruct
      template:
        metadata:
          labels:
            app: vllm-llama3.1-8b-instruct
        spec:
          containers:
            - name: vllm
              # Versions of vllm after v0.8.5 have an issue due to an update in NVIDIA driver path.
              # The following workaround can be used until the fix is applied to the vllm release
              # BUG: https://github.com/vllm-project/vllm/issues/18859
              image: "vllm/vllm-openai:latest"
              imagePullPolicy: Always
              command: ["sh", "-c"]
              args:
              - >-
                PATH=$PATH:/usr/local/nvidia/bin
                LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/nvidia/lib:/usr/local/nvidia/lib64
                python3 -m vllm.entrypoints.openai.api_server
                --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: 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"
          # This is the second container in the Pod, a sidecar to the vLLM container.
          # It watches the ConfigMap and downloads LoRA adapters.
            - name: lora-adapter-syncer
              image: us-central1-docker.pkg.dev/k8s-staging-images/gateway-api-inference-extension/lora-syncer:main
              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 10ms TPOT at a max
          #      batch size around 50, or 100 tokens/sec)
          #   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 / 100 ~ 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 40% to the time from above (40s +
          #      16s = 56s)
          #
          # Thus we think it will take us at worst about 56s 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 to
          #      stop sending us new requests (56s + 30s = 86s).
          #
          # 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 (86s * 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.1-8b-adapters
    ---
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: vllm-llama3.1-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.k8s.io"
        kind: InferencePool
        name: vllm-llama3.1-8b-instruct
      default:
        config:
          type: HTTP
          httpHealthCheck:
              requestPath: /health
              port: 8000
    
  2. Aplica el manifiesto a tu clúster:

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

Crear un recurso InferencePool

El recurso personalizado de InferencePool Kubernetes define un grupo de pods con un LLM base y una configuración de computación comunes.

El recurso personalizado InferencePool incluye los siguientes campos clave:

  • selector: especifica qué pods pertenecen a este grupo. Las etiquetas de este selector deben coincidir exactamente con las etiquetas aplicadas a los pods de tu servidor de modelos.
  • targetPort: define los puertos que usa el servidor de modelos en los pods.

El recurso InferencePool permite a GKE Inference Gateway enrutar el tráfico a los pods de tu servidor de modelos.

Para crear un InferencePool con Helm, sigue estos pasos:

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

Cambie el siguiente campo para que coincida con su implementación:

  • inferencePool.modelServers.matchLabels.app: la clave de la etiqueta usada para seleccionar los pods de tu servidor de modelos.

Este comando crea un objeto InferencePool que representa lógicamente el despliegue del servidor de modelos y hace referencia a los servicios de endpoint de modelo de los pods que selecciona Selector.

Crea un recurso InferenceObjective con una criticidad de servicio

El recurso personalizado InferenceObjective define los parámetros de servicio de un modelo, incluida su prioridad. Debe crear recursos InferenceObjective para definir qué modelos se publican en un InferencePool. Estos recursos pueden hacer referencia a modelos base o adaptadores LoRA admitidos por los servidores de modelos en InferencePool.

El campo metadata.name especifica el nombre del modelo, el campo priority define su criticidad de servicio y el campo poolRef enlaza con InferencePool, donde se ofrece el modelo.

Para crear un InferenceObjective, sigue estos pasos:

  1. Guarda el siguiente archivo de manifiesto de ejemplo como inferenceobjective.yaml:

    apiVersion: inference.networking.x-k8s.io/v1alpha2
    kind: InferenceObjective
    metadata:
      name: MODEL_NAME
    spec:
      priority: VALUE
      poolRef:
        name: INFERENCE_POOL_NAME
        kind: "InferencePool"
    

    Haz los cambios siguientes:

    • MODEL_NAME: el nombre de tu modelo base o adaptador LoRA. Por ejemplo, food-review.
    • VALUE: la prioridad del objetivo de inferencia. Es un número entero en el que un valor más alto indica una solicitud más crítica. Por ejemplo, 10.
    • INFERENCE_POOL_NAME: el nombre del InferencePool que has creado en el paso anterior. Por ejemplo, vllm-llama3.1-8b-instruct.
  2. Aplica el manifiesto de ejemplo a tu clúster:

    kubectl apply -f inferenceobjective.yaml
    

En el siguiente ejemplo se crean dos objetos InferenceObjective. La primera configura el modelo food-review LoRA en la vllm-llama3.1-8b-instruct InferencePool con una prioridad de 10. La segunda configura el llama3-base-model para que se sirva con una prioridad más alta, 20.

apiVersion: inference.networking.k8s.io/v1alpha1
kind: InferenceObjective
metadata:
  name: food-review
spec:
  priority: 10
  poolRef:
    name: vllm-llama3.1-8b-instruct
    kind: "InferencePool"
---
apiVersion: inference.networking.k8s.io/v1alpha1
kind: InferenceObjective
metadata:
  name: llama3-base-model
spec:
  priority: 20
  poolRef:
    name: vllm-llama3.1-8b-instruct
    kind: "InferencePool"

Crear la pasarela

El recurso Gateway actúa como punto de entrada del tráfico externo en tu clúster de Kubernetes. Define los listeners que aceptan conexiones entrantes.

GKE Inference Gateway admite las clases Gateway gke-l7-rilb y gke-l7-regional-external-managed. Para obtener más información, consulta la documentación de GKE sobre GatewayClasses.

Para crear una pasarela, sigue estos pasos:

  1. Guarda el siguiente archivo de manifiesto de ejemplo como 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
    

    Sustituye GATEWAY_NAME por un nombre único para tu recurso Gateway. Por ejemplo, inference-gateway.

  2. Aplica el manifiesto a tu clúster:

    kubectl apply -f gateway.yaml
    

Crea el recurso HTTPRoute.

En esta sección, crearás un recurso HTTPRoute para definir cómo enruta la puerta de enlace las solicitudes HTTP entrantes a tu InferencePool.

El recurso HTTPRoute define cómo enruta la puerta de enlace de GKE las solicitudes HTTP entrantes a los servicios de backend, que es tu InferencePool. Especifica las reglas de coincidencia (por ejemplo, cabeceras o rutas) y el backend al que se debe reenviar el tráfico.

Para crear un HTTPRoute, sigue estos pasos:

  1. Guarda el siguiente archivo de manifiesto de ejemplo como 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.k8s.io
          kind: InferencePool
    

    Haz los cambios siguientes:

    • HTTPROUTE_NAME: un nombre único para tu recurso HTTPRoute. Por ejemplo, my-route.
    • GATEWAY_NAME: el nombre del recurso Gateway que has creado. Por ejemplo, inference-gateway.
    • PATH_PREFIX: el prefijo de ruta que usas para que coincidan las solicitudes entrantes. Por ejemplo, / para que coincida con todo.
    • INFERENCE_POOL_NAME: el nombre del recurso InferencePool al que quieras dirigir el tráfico. Por ejemplo, vllm-llama3.1-8b-instruct.
  2. Aplica el manifiesto a tu clúster:

    kubectl apply -f httproute.yaml
    

Enviar una solicitud de inferencia

Una vez que hayas configurado GKE Inference Gateway, podrás enviar solicitudes de inferencia al modelo desplegado.

Para enviar solicitudes de inferencia, sigue estos pasos:

  • Recupera el endpoint de la pasarela.
  • Crea una solicitud JSON con el formato correcto.
  • Usa curl para enviar la solicitud al endpoint /v1/completions.

De esta forma, puedes generar texto a partir de la petición que introduzcas y de los parámetros que especifiques.

  1. Para obtener el endpoint de Gateway, ejecuta el siguiente comando:

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

    Sustituye GATEWAY_NAME por el nombre de tu recurso Gateway.

  2. Para enviar una solicitud al endpoint /v1/completions mediante curl, ejecuta el siguiente comando:

    curl -i -X POST http://${IP}:${PORT}/v1/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "MODEL_NAME",
        "prompt": "PROMPT_TEXT",
        "max_tokens": MAX_TOKENS,
        "temperature": "TEMPERATURE"
    }'
    

    Haz los cambios siguientes:

    • MODEL_NAME: el nombre del modelo o del adaptador LoRA que se va a usar.
    • PROMPT_TEXT: la petición de entrada del modelo.
    • MAX_TOKENS: número máximo de tokens que se generarán en la respuesta.
    • TEMPERATURE: controla la aleatoriedad de la salida. Usa el valor 0 para obtener resultados deterministas o un número más alto para obtener resultados más creativos.

Ten en cuenta lo siguiente:

  • Cuerpo de la solicitud: el cuerpo de la solicitud puede incluir parámetros adicionales, como stop y top_p. Consulta la especificación de la API de OpenAI para ver la lista completa de opciones.
  • Gestión de errores: implementa una gestión de errores adecuada en el código de tu cliente para gestionar los posibles errores en la respuesta. Por ejemplo, comprueba el código de estado HTTP en la respuesta curl. Por lo general, un código de estado distinto de 200 indica que se ha producido un error.
  • Autenticación y autorización: en las implementaciones de producción, protege tu endpoint de API con mecanismos de autenticación y autorización. Incluya los encabezados adecuados (por ejemplo, Authorization) en sus solicitudes.

Configurar la observabilidad de Inference Gateway

GKE Inference Gateway proporciona observabilidad del estado, el rendimiento y el comportamiento de tus cargas de trabajo de inferencia. Esto te ayuda a identificar y resolver problemas, optimizar el uso de los recursos y asegurar la fiabilidad de tus aplicaciones. Puede ver estas métricas de observabilidad en Cloud Monitoring a través del explorador de métricas.

Para configurar la observabilidad de GKE Inference Gateway, consulta Configurar la observabilidad.

Eliminar los recursos desplegados

Para evitar que se apliquen cargos en tu Google Cloud cuenta por los recursos que has creado a partir de esta guía, ejecuta el siguiente comando:

gcloud container clusters delete CLUSTER_NAME \
    --location=CONTROL_PLANE_LOCATION

Sustituye los siguientes valores:

  • CONTROL_PLANE_LOCATION: la región de Compute Engine del plano de control de tu clúster.
  • CLUSTER_NAME: el nombre de tu clúster.

Siguientes pasos