Tüm Ürünler
Search
Belge Merkezi

Container Service for Kubernetes:Configure an auto scaling policy for a service with KServe

Son Güncelleme:Oct 06, 2026

KServe model hizmetlerini dağıtırken ve yönetirken son derece dinamik çıkarım yükünü yönetmeniz gerekir. KServe, Kubernetes HPA ve ölçeklendirme denetleyicilerini entegre ederek CPU, bellek, GPU kullanımı veya özel ölçümlere göre Pod çoğaltmalarını ayarlar. Bu konuda, V100 GPU'lar üzerindeki Qwen-7B-Chat-Int8 modeli örnek alınarak KServe hizmetleri için esnek ölçeklendirme yapılandırması gösterilmektedir.

Bu konudaki örnekler, V100 GPU üzerinde çalışan bir Qwen-7B-Chat-Int8 modelini kullanır.

Bir ölçeklendirme türü seçin

Ölçeklendirme türü Tetikleyici Dağıtım modu Kullanım senaryosu
CPU/bellek tabanlı HPA CPU veya bellek kullanımı bir eşiği aştığında Raw Deployment Öngörülemeyen trafiğe sahip, CPU veya bellek sınırlı çıkarım iş yükleri
GPU kullanımı tabanlı HPA Özel GPU ölçümü (DCGM) bir eşiği aştığında Raw Deployment LLM sunumu gibi GPU sınırlı çıkarım iş yükleri
Zamanlanmış ölçeklendirme (CronHPA) Zaman çizelgesi (cron ifadesi) Raw Deployment İş saatleri zirveleri gibi öngörülebilir trafik desenleri
Not

HPA, 0'a ölçeklendirmeyi desteklemez. --min-replicas değeri 0'dan büyük olmalıdır.

Ön koşullar

CPU/bellek tabanlı esnek ölçeklendirmeyi yapılandırın

HPA, Raw Deployment modunda CPU veya bellek kullanımına göre pod çoğaltmalarını ayarlar. Bu örnekte, CPU tabanlı ölçeklendirme kullanan bir sklearn-iris modeli ele alınmaktadır.

Kubernetes belgelerindeki Yatay Pod Otomatik Ölçeklendirme bölümüne bakın.

  1. Çıkarım hizmetini ölçeklendirme parametreleriyle gönderin.

    Parametre Açıklama
    --scale-metric Ölçeklendirme ölçümü. Geçerli değerler: cpu, memory.
    --scale-target Yüzde cinsinden ölçeklendirme eşiği.
    --min-replicas Minimum çoğaltma sayısı. 0'dan büyük olmalıdır.
    --max-replicas Maksimum çoğaltma sayısı. --min-replicas değerinden yüksek olmalıdır.
    arena serve kserve \
        --name=sklearn-iris \
        --image=kube-ai-registry.cn-shanghai.cr.aliyuncs.com/ai-sample/kserve-sklearn-server:v0.12.0 \
        --cpu=1 \
        --memory=200Mi \
        --scale-metric=cpu \
        --scale-target=10 \
        --min-replicas=1 \
        --max-replicas=10 \
        "python -m sklearnserver --model_name=sklearn-iris --model_dir=/models --http_port=8080"

    Beklenen çıktı:

    inferenceservice.serving.kserve.io/sklearn-iris created
    INFO[0002] The Job sklearn-iris has been submitted successfully
    INFO[0002] You can run `arena serve get sklearn-iris --type kserve -n default` to check the job status
  2. Aşağıdaki içeriğe sahip iris-input.json adlı bir dosya oluşturun:

    cat <<EOF > "./iris-input.json"
    {
      "instances": [
        [6.8,  2.8,  4.8,  1.4],
        [6.0,  3.4,  4.5,  1.6]
      ]
    }
    EOF
  3. Çıkarım hizmetini test edin.

    # Get the load balancer IP of the nginx-ingress-lb service in the kube-system namespace.
    NGINX_INGRESS_IP=`kubectl -n kube-system get svc nginx-ingress-lb -ojsonpath='{.status.loadBalancer.ingress[0].ip}'`
    # Get the hostname of the sklearn-iris InferenceService.
    SERVICE_HOSTNAME=$(kubectl get inferenceservice sklearn-iris -o jsonpath='{.status.url}' | cut -d "/" -f 3)
    # Send a prediction request using the iris-input.json file.
    curl -H "Host: $SERVICE_HOSTNAME" -H "Content-Type: application/json" \
         http://$NGINX_INGRESS_IP:80/v1/models/sklearn-iris:predict -d @./iris-input.json

    Beklenen çıktı:

    {"predictions":[1,1]}%
  4. Ölçeklendirmeyi tetiklemek için bir stres testi çalıştırın.

    Not

    Bu adımda Hey stres testi aracı kullanılmaktadır.

    hey -z 2m -c 20 -m POST -host $SERVICE_HOSTNAME -H "Content-Type: application/json" -D ./iris-input.json http://${NGINX_INGRESS_IP}:80/v1/models/sklearn-iris:predict
  5. Stres testi devam ederken, ayrı bir terminalde HPA ölçeklendirme durumunu kontrol edin.

    kubectl describe hpa sklearn-iris-predictor

    Hizmetin ölçeklendirme durumunu görüntülemek için genişletin

    Name:                                                  sklearn-iris-predictor
    Namespace:                                             default
    Labels:                                                app=isvc.sklearn-iris-predictor
                                                           arena.kubeflow.org/uid=3399d840e8b371ed7ca45dda29debeb1
                                                           chart=kserve-0.1.0
                                                           component=predictor
                                                           heritage=Helm
                                                           release=sklearn-iris
                                                           serving.kserve.io/inferenceservice=sklearn-iris
                                                           servingName=sklearn-iris
                                                           servingType=kserve
    Annotations:                                           arena.kubeflow.org/username: kubecfg:certauth:admin
                                                           serving.kserve.io/deploymentMode: RawDeployment
    CreationTimestamp:                                     Sat, 11 May 2024 17:15:47 +0800
    Reference:                                             Deployment/sklearn-iris-predictor
    Metrics:                                               ( current / target )
      resource cpu on pods  (as a percentage of request):  0% (2m) / 10%
    Min replicas:                                          1
    Max replicas:                                          10
    Behavior:
      Scale Up:
        Stabilization Window: 0 seconds
        Select Policy: Max
        Policies:
          - Type: Pods     Value: 4    Period: 15 seconds
          - Type: Percent  Value: 100  Period: 15 seconds
      Scale Down:
        Select Policy: Max
        Policies:
          - Type: Percent  Value: 100  Period: 15 seconds
    Deployment pods:       10 current / 10 desired
    Conditions:
      Type            Status  Reason               Message
      ----            ------  ------               -------
      AbleToScale     True    ScaleDownStabilized  recent recommendations were higher than current one, applying the highest recent recommendation
      ScalingActive   True    ValidMetricFound     the HPA was able to successfully calculate a replica count from cpu resource utilization (percentage of request)
      ScalingLimited  False   DesiredWithinRange   the desired count is within the acceptable range
    Events:
      Type    Reason             Age                  From                       Message
      ----    ------             ----                 ----                       -------
      Normal  SuccessfulRescale  38m                  horizontal-pod-autoscaler  New size: 8; reason: cpu resource utilization (percentage of request) above target
      Normal  SuccessfulRescale  28m                  horizontal-pod-autoscaler  New size: 7; reason: All metrics below target
      Normal  SuccessfulRescale  27m                  horizontal-pod-autoscaler  New size: 1; reason: All metrics below target

    Events bölümü, HPA'nın yük altında 8 çoğaltmaya kadar ölçeklendiğini, ardından yük azaldıkça 7 ve 1'e geri döndüğünü göstermektedir.

GPU kullanımı tabanlı esnek ölçeklendirmeyi yapılandırın

Bu tür, özel GPU ölçümlerini ortaya çıkarmak için ack-alibaba-cloud-metrics-adapter bileşeniyle birlikte Raw Deployment modunda HPA kullanır. Bkz. Alibaba Cloud Prometheus ölçümlerine dayalı yatay pod otomatik ölçeklendirme.

Bu örnekte, GPU kullanımı tabanlı otomatik ölçeklendirme yapılandırılmaktadır.

  1. Qwen-7B-Chat-Int8 model verilerini hazırlayın. Bkz. Bir vLLM çıkarım hizmeti dağıtma.

  2. Özel GPU ölçümlerini yapılandırın. Bkz. GPU ölçümlerine dayalı esnek ölçeklendirmeyi uygulama.

  3. GPU tabanlı ölçeklendirme ile vLLM çıkarım hizmetini dağıtın.

    arena serve kserve \
        --name=qwen \
        --image=kube-ai-registry.cn-shanghai.cr.aliyuncs.com/kube-ai/vllm:0.4.1 \
        --gpus=1 \
        --cpu=4 \
        --memory=12Gi \
        --scale-metric=DCGM_CUSTOM_PROCESS_SM_UTIL \
        --scale-target=50 \
        --min-replicas=1 \
        --max-replicas=2 \
        --data="llm-model:/mnt/models/Qwen-7B-Chat-Int8" \
        "python3 -m vllm.entrypoints.openai.api_server --port 8080 --trust-remote-code --served-model-name qwen --model /mnt/models/Qwen-7B-Chat-Int8 --gpu-memory-utilization 0.95 --quantization gptq --max-model-len=6144"

    Beklenen çıktı:

    inferenceservice.serving.kserve.io/qwen created
    INFO[0002] The Job qwen has been submitted successfully
    INFO[0002] You can run `arena serve get qwen --type kserve -n default` to check the job status
  4. Çıkarım hizmetini test edin.

    # Get the IP address of the Nginx Ingress.
    NGINX_INGRESS_IP=$(kubectl -n kube-system get svc nginx-ingress-lb -ojsonpath='{.status.loadBalancer.ingress[0].ip}')
    # Get the hostname of the InferenceService.
    SERVICE_HOSTNAME=$(kubectl get inferenceservice qwen -o jsonpath='{.status.url}' | cut -d "/" -f 3)
    # Send a test request to the vLLM chat completions endpoint.
    curl -H "Host: $SERVICE_HOSTNAME" -H "Content-Type: application/json" http://$NGINX_INGRESS_IP:80/v1/chat/completions -d '{"model": "qwen", "messages": [{"role": "user", "content": "Test"}], "max_tokens": 10, "temperature": 0.7, "top_p": 0.9, "seed": 10}'

    Beklenen çıktı:

    {"id":"cmpl-77088b96abe744c89284efde2e779174","object":"chat.completion","created":1715590010,"model":"qwen","choices":[{"index":0,"message":{"role":"assistant","content":"OK, what do you need to test?<|im_end|>"},"logprobs":null,"finish_reason":"length","stop_reason":null}],"usage":{"prompt_tokens":10,"total_tokens":20,"completion_tokens":10}}%
  5. GPU tabanlı ölçeklendirmeyi tetiklemek için bir stres testi çalıştırın.

    Not

    Bu adımda Hey stres testi aracı kullanılmaktadır.

    hey -z 2m -c 5 -m POST -host $SERVICE_HOSTNAME -H "Content-Type: application/json" -d '{"model": "qwen", "messages": [{"role": "user", "content": "Test"}], "max_tokens": 10, "temperature": 0.7, "top_p": 0.9, "seed": 10}' http://$NGINX_INGRESS_IP:80/v1/chat/completions
  6. Stres testi devam ederken, ayrı bir terminalde HPA ölçeklendirme durumunu kontrol edin.

    kubectl describe hpa qwen-hpa

    qwen-hpa ölçeklendirme durumunu görüntülemek için genişletin

    Name:                                     qwen-hpa
    Namespace:                                default
    Labels:                                   <none>
    Annotations:                              <none>
    CreationTimestamp:                        Tue, 14 May 2024 14:57:03 +0800
    Reference:                                Deployment/qwen-predictor
    Metrics:                                  ( current / target )
      "DCGM_CUSTOM_PROCESS_SM_UTIL" on pods:  0 / 50
    Min replicas:                             1
    Max replicas:                             2
    Deployment pods:                          1 current / 1 desired
    Conditions:
      Type            Status  Reason            Message
      ----            ------  ------            -------
      AbleToScale     True    ReadyForNewScale  recommended size matches current size
      ScalingActive   True    ValidMetricFound  the HPA was able to successfully calculate a replica count from pods metric DCGM_CUSTOM_PROCESS_SM_UTIL
      ScalingLimited  True    TooFewReplicas    the desired replica count is less than the minimum replica count
    Events:
      Type    Reason             Age   From                       Message
      ----    ------             ----  ----                       -------
      Normal  SuccessfulRescale  43m   horizontal-pod-autoscaler  New size: 2; reason: pods metric DCGM_CUSTOM_PROCESS_SM_UTIL above target
      Normal  SuccessfulRescale  34m   horizontal-pod-autoscaler  New size: 1; reason: All metrics below target

    Hizmet, stres testi sırasında 2 pod'a ölçeklendi ve testin bitmesinden yaklaşık 5 dakika sonra tekrar 1 pod'a döndü.

Zamanlanmış esnek ölçeklendirmeyi yapılandırın

Bu tür, öngörülebilir trafik desenleri için uygun olan cron zamanlamasına göre pod çoğaltmalarını ayarlamak üzere ack-kubernetes-cronhpa-controller bileşenini (CronHPA) kullanır.

  1. CronHPA bileşenini yükleyin. Bkz. Konteynerlerin zamanlanmış yatay ölçeklendirmesi için CronHPA kullanma.

  2. Qwen-7B-Chat-Int8 model verilerini hazırlayın. Bkz. Bir vLLM çıkarım hizmeti dağıtma.

  3. vLLM çıkarım hizmetini dağıtın.

    arena serve kserve \
        --name=qwen-cronhpa \
        --image=kube-ai-registry.cn-shanghai.cr.aliyuncs.com/kube-ai/vllm:0.4.1 \
        --gpus=1 \
        --cpu=4 \
        --memory=12Gi \
        --annotation="serving.kserve.io/autoscalerClass=external" \
        --data="llm-model:/mnt/models/Qwen-7B-Chat-Int8" \
       "python3 -m vllm.entrypoints.openai.api_server --port 8080 --trust-remote-code --served-model-name qwen --model /mnt/models/Qwen-7B-Chat-Int8 --gpu-memory-utilization 0.95 --quantization gptq --max-model-len=6144"

    Beklenen çıktı:

    inferenceservice.serving.kserve.io/qwen-cronhpa created
    INFO[0004] The Job qwen-cronhpa has been submitted successfully
    INFO[0004] You can run `arena serve get qwen-cronhpa --type kserve -n default` to check the job status
  4. Çıkarım hizmetini test edin.

    # Get the IP address of the Nginx Ingress.
    NGINX_INGRESS_IP=`kubectl -n kube-system get svc nginx-ingress-lb -ojsonpath='{.status.loadBalancer.ingress[0].ip}'`
    # Get the hostname of the InferenceService.
    SERVICE_HOSTNAME=$(kubectl get inferenceservice qwen-cronhpa -o jsonpath='{.status.url}' | cut -d "/" -f 3)
    # Send a test request to the vLLM chat completions endpoint.
    curl -H "Host: ${SERVICE_HOSTNAME}" -H "Content-Type: application/json" \
         http://$NGINX_INGRESS_IP:80/v1/chat/completions -X POST \
         -d '{"model": "qwen", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 512, "temperature": 0.7, "top_p": 0.9, "seed": 10, "stop":["<|endoftext|>", "<|im_end|>", "<|im_start|>"]}'

    Beklenen çıktı:

    {"id":"cmpl-b7579597aa284f118718b22b83b726f8","object":"chat.completion","created":1715589652,"model":"qwen","choices":[{"index":0,"message":{"role":"assistant","content":"OK, what do you need to test?<|im_end|>"},"logprobs":null,"finish_reason":"length","stop_reason":null}],"usage":{"prompt_tokens":10,"total_tokens":20,"completion_tokens":10}}%
  5. CronHPA yapılandırmasını uygulayın. Bu örnekte, her gün saat 10:30'da 2 pod'a ve saat 12:00'de 1 pod'a geri ölçeklendirme yapılır.

    Zamanlanmış otomatik ölçeklendirmeyi yapılandırmak için komutu görüntülemek üzere genişletin

    kubectl apply -f- <<EOF
    apiVersion: autoscaling.alibabacloud.com/v1beta1
    kind: CronHorizontalPodAutoscaler
    metadata:
      name: qwen-cronhpa
      namespace: default
    spec:
       scaleTargetRef:
          apiVersion: apps/v1
          kind: Deployment
          name: qwen-cronhpa-predictor
       jobs:
       # Scale out at 10:30 every day.
       - name: "scale-up"
         schedule: "0 30 10 * * *"
         targetSize: 2
         runOnce: false
      # Scale in at 12:00 every day.
       - name: "scale-down"
         schedule: "0 0 12 * * *"
         targetSize: 1
         runOnce: false
    EOF

    Önceden ayarlanmış ölçeklendirme yapılandırmasını görüntülemek için genişletin

    Name:         qwen-cronhpa
    Namespace:    default
    Labels:       <none>
    Annotations:  <none>
    API Version:  autoscaling.alibabacloud.com/v1beta1
    Kind:         CronHorizontalPodAutoscaler
    Metadata:
      Creation Timestamp:  2024-05-12T14:06:49Z
      Generation:          2
      Resource Version:    9205625
      UID:                 b9e72da7-262e-4***-b***-26586b7****c
    Spec:
      Jobs:
        Name:         scale-up
        Schedule:     0 30 10 * * *
        Target Size:  2
        Name:         scale-down
        Schedule:     0 0 12 * * *
        Target Size:  1
      Scale Target Ref:
        API Version:  apps/v1
        Kind:         Deployment
        Name:         qwen-cronhpa-predictor
    Status:
      Conditions:
        Job Id:           3972f7cc-bab0-482e-8cbe-7c4*******5
        Last Probe Time:  2024-05-12T14:06:49Z
        Message:
        Name:             scale-up
        Run Once:         false
        Schedule:         0 30 10 * * *
        State:            Submitted
        Target Size:      2
        Job Id:           36a04605-0233-4420-967c-ac2********6
        Last Probe Time:  2024-05-12T14:06:49Z
        Message:
        Name:             scale-down
        Run Once:         false
        Schedule:         0 0 12 * * *
        State:            Submitted
        Target Size:      1
      Scale Target Ref:
        API Version:  apps/v1
        Kind:         Deployment
        Name:         qwen-cronhpa-predictor
    Events:           <none>

    CronHPA kaynağında iki zamanlanmış iş bulunur. qwen-cronhpa-predictor Dağıtımı, her gün saat 10:30'da 2 pod'a ve saat 12:00'de 1 pod'a ölçeklenir.

Sonraki adımlar

Bkz. Otomatik Ölçeklendirme.