Stage 13, Part 2 of 9, AI/ML Workload Orchestration

Text

PART 2: ADVANCED CONCEPTS

5. vLLM

vLLM is the de-facto industry standard for high-throughput LLM inference. It combines PagedAttention and continuous batching to maximize GPU utilization.

PagedAttention

Traditional LLM serving allocates KV cache as one contiguous block per sequence. This wastes 60–80% of GPU memory due to fragmentation.

PagedAttention stores KV blocks in a paged table — memory is allocated per token-block rather than per whole sequence. This is what makes high occupancy and large effective concurrency possible.

text
Traditional:                      PagedAttention:
Sequence A: [████████░░░░░░░░]      Block table:
Sequence B: [████░░░░░░░░░░░░]      Seq A → [B1][B2][B3]
Sequence C: [██████░░░░░░░░░░]      Seq B → [B4][B5]
                                    Seq C → [B6][B7][B8]
Wasted: ~70%                        Wasted: ~4%

Continuous Batching

Traditional batching waits for all sequences to finish before starting new ones. GPU sits idle while waiting for the longest sequence — utilization ~40–60%.

Continuous batching adds new requests as slots become available, mixing prefill (new requests) and decode (ongoing) in the same batch.

text
Traditional Batching:              Continuous Batching:
Time →                             Time →
[Req1][Req2][Req3]                 [Req1][Req4][Req7]
Wait for all to finish             [Req2][Req5][Req8]
[Req4][Req5][Req6]                 [Req3][Req6][Req9]
GPU idle between batches           GPU never idle

vLLM Deployment on Kubernetes

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm
spec:
  replicas: 1
  selector:
    matchLabels:
      app: vllm
  template:
    metadata:
      labels:
        app: vllm
    spec:
      containers:
      - name: vllm
        image: vllm/vllm-openai:latest
        args:
        - "--model"
        - "meta-llama/Llama-2-7b-hf"
        - "--tensor-parallel-size"
        - "1"
        - "--max-model-len"
        - "4096"
        resources:
          limits:
            nvidia.com/gpu: 1
          requests:
            cpu: 4
            memory: 16Gi
        ports:
        - containerPort: 8000
        readinessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 60
          periodSeconds: 10

vLLM Performance

Real-world benchmarks show vLLM achieving 2–24x throughput compared to naive implementations. Stripe achieved a 73% reduction in inference costs by migrating to vLLM for 50 million daily API calls with one-third of the fleet.

Key vLLM Flags

FlagPurpose
--tensor-parallel-sizeNumber of GPUs for tensor parallelism
--max-model-lenMaximum sequence length
--gpu-memory-utilizationFraction of GPU memory to use (default 0.9)
--enable-prefix-cachingEnable KV-cache prefix reuse
--quantizationQuantization method (awq, gptq, fp8)

6. TGI (Text Generation Inference)

TGI is Hugging Face's production inference server. It includes tensor parallelism, quantization, continuous batching, and token streaming.

TGI Features

FeaturePurpose
Continuous batchingDynamic request grouping for better GPU utilization
Token streamingBetter UX for long responses
Tensor parallelismMulti-GPU model sharding
QuantizationReduce memory footprint
Flash AttentionFaster attention computation

TGI Deployment on Kubernetes

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: tgi
spec:
  replicas: 1
  selector:
    matchLabels:
      app: tgi
  template:
    metadata:
      labels:
        app: tgi
    spec:
      containers:
      - name: tgi
        image: ghcr.io/huggingface/text-generation-inference:latest
        args:
        - "--model-id"
        - "meta-llama/Llama-2-7b-chat-hf"
        - "--num-shard"
        - "1"
        - "--max-batch-prefill-tokens"
        - "4096"
        - "--max-batch-total-tokens"
        - "8192"
        resources:
          limits:
            nvidia.com/gpu: 1
        ports:
        - containerPort: 80

TGI Best Practices

PracticeWhy
Set --num-shard = GPU countPrevent OOMKill mid-request
Tune --max-batch-prefill-tokensControl prefill memory
Tune --max-batch-total-tokensControl total batch memory
Use A10 or newerTGI does not support V100 or T4

Critical: Kubernetes requests.nvidia.com/gpu must match --num-shard count, not total GPU count. If you set num-shard=4 but request only 2 GPUs, the pod will OOMKill mid-request.

TGI vs vLLM

AspectTGIvLLM
Backed byHugging FacevLLM project
Continuous batching✅✅
PagedAttention❌ (uses different memory management)✅
Tensor parallelism✅✅
Streaming✅✅
EcosystemHugging FaceOpenAI-compatible

7. Triton Inference Server

NVIDIA Triton Inference Server is a multi-framework inference server. It supports TensorRT, PyTorch, ONNX, TensorFlow, and vLLM as a backend.

Triton with vLLM Backend

Triton's vLLM backend combines Triton's multi-model management with vLLM's PagedAttention and continuous batching.

Triton Deployment

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: triton
spec:
  replicas: 1
  selector:
    matchLabels:
      app: triton
  template:
    metadata:
      labels:
        app: triton
    spec:
      containers:
      - name: triton
        image: nvcr.io/nvidia/tritonserver:24.01-trtllm-python-py3
        args:
        - "--model-repository=/models"
        - "--model-control-mode=explicit"
        resources:
          limits:
            nvidia.com/gpu: 1
        ports:
        - containerPort: 8000  # HTTP
        - containerPort: 8001  # gRPC
        - containerPort: 8002  # Metrics

Triton Model Repository

text
/models
├── llama-2-7b
│   ├── config.pbtxt
│   └── 1/
│       └── model.py
└── bert
    ├── config.pbtxt
    └── 1/
        └── model.onnx

When to Use Triton

ScenarioTriton?
Multi-framework✅ Yes
Enterprise deployment✅ Yes
LLM-only⚠️ vLLM direct is simpler
Multi-model serving✅ Yes
Simple LLM❌ vLLM direct

8. KV-Cache Management and Offloading

The KV cache is the invisible state that every LLM request carries. Hit it, and your response is 10x cheaper and 50x faster. Miss it, and you're recomputing work you just did.

The KV-Cache Problem

ScenarioImpact
Cache hit10x cheaper, 50x faster
Cache missFull recomputation
Cache-blind routingScatters related requests, destroys locality

Tiered KV-Cache

Google Cloud's approach extends KV-cache from NVIDIA GPU HBM (Tier 1) to CPU RAM and local SSDs (Tier 2).

text
Tier 1: GPU HBM (fastest, smallest)
Tier 2: CPU RAM (medium speed, larger)
Tier 3: Local NVMe SSD (slower, largest)

LMCache

LMCache extends the KV cache from GPU HBM to CPU RAM and local SSDs, dramatically increasing total cache size.

yaml
# vLLM with LMCache
env:
- name: VLLM_USE_LMCACHE
  value: "1"
- name: LMCACHE_BACKEND
  value: "local_disk"

When to Use KV-Cache Offloading

ScenarioOffloading?
Long context✅ Yes
Multi-turn chat✅ Yes
RAG pipelines✅ Yes
Short prompts❌ No benefit
Single-turn QA❌ No benefit

9. Inference Autoscaling

Traditional HPA based on CPU and memory may respond too slowly for LLM inference. KEDA enables direct SLO-driven scaling by leveraging actual SLIs like Inter-Token Latency (ITL) and end-to-end response times from vLLM.

vLLM Metrics for Autoscaling

MetricMeaningUse
num_requests_waitingQueue depthScale up trigger
num_requests_runningActive requestsUtilization
inter_token_latencyTime between tokensSLO metric
time_to_first_tokenTTFTUser experience

KEDA ScaledObject for vLLM

yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: vllm-scaler
spec:
  scaleTargetRef:
    name: vllm
  minReplicaCount: 1
  maxReplicaCount: 10
  pollingInterval: 15
  cooldownPeriod: 300
  triggers:
  - type: prometheus
    metadata:
      serverAddress: http://prometheus:9090
      metricName: num_requests_waiting
      threshold: "5"
      query: |
        sum(vllm:num_requests_waiting)

Scaling Behavior

ActionTime
Scale up~30–60 seconds
Scale down~5 minute cooldown

Knative vs KEDA

AspectKnativeKEDA
Scaling metricRequest concurrencyCustom metrics
Scale to zero✅ Yes✅ (with HTTP add-on)
Cold startHigherLower
SLO-driven❌✅
Best forServerless inferenceProduction inference

10. Model Caching and Warm Pools

Cold start is the biggest UX problem in AI inference. A model that takes 5 minutes to load will fail autoscaling.

Cold Start Decomposition

The startup path has six phases:

PhaseTimeOptimization
T_capacityNode provisioningKarpenter, warm pools
T_schedulePod schedulingNode affinity
T_imageImage pullImage pre-warming
T_modelModel weight loadingLocal NVMe cache
T_runtimeRuntime initializationPre-built runtime
T_warmupGPU warmupWarm pools

KServe LocalModelCache

KServe's LocalModelCache caches models on Kubernetes nodes' local NVMe volumes.

yaml
apiVersion: serving.kserve.io/v1alpha1
kind: LocalModelCache
metadata:
  name: llama-cache
spec:
  sourceModelUri: "hf://meta-llama/Llama-2-7b-hf"
  nodeGroups:
  - gpu-node-group
  persistentVolumeClaim: llama-model-pvc

Warm Pools

Warm pools keep pre-loaded model instances ready for immediate traffic. The trade-off is cost: idle GPUs in the warm pool still cost money.

StrategyCold StartCost
No warm pool5 minLowest
1 warm replica<10 secMedium
Full warm pool<1 secHighest

Model Caching Strategies

StrategyCold StartCost
Hugging Face Hub5+ min$
Local NVMe cache30 sec$$
Warm pool<10 sec$$$

11. Cache-Aware Routing

Kubernetes' default load balancing is cache-blind, scattering related requests across pods and destroying locality. This makes AI workloads slower and vastly more expensive than they should be.

The Problem

text
Request 1 (User A, prompt X) → Pod 1 (cache miss, 5s)
Request 2 (User A, prompt X) → Pod 2 (cache miss, 5s)
Request 3 (User A, prompt X) → Pod 3 (cache miss, 5s)

3x work, 3x latency, 3x cost

The Solution: llm-d

llm-d is a Kubernetes-native framework for distributed LLM inference with an AI-aware scheduler. It uses KV-cache-aware routing to direct requests to pods that already hold relevant context in GPU memory.

Gateway API Inference Extension

The Gateway API Inference Extension replaces the default Service with AI-aware routing.

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: llm-route
spec:
  parentRefs:
  - name: inference-gateway
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /v1
    backendRefs:
    - name: vllm-pods
      kind: Service
      port: 8000

When to Use Cache-Aware Routing

ScenarioCache-Aware?
Multi-turn chat✅ Yes
RAG pipelines✅ Yes
Long system prompts✅ Yes
Single-turn QA❌ No benefit
Unique prompts❌ No benefit

12. KAI Scheduler

KAI Scheduler is NVIDIA's open-source, Kubernetes-native scheduler for AI workloads. It provides GPU-oriented placement, grouping, and resource-sharing policy.

KAI Scheduler Capabilities

CapabilityPurpose
Gang schedulingAll-or-nothing placement
Hierarchical queuesTeam quotas with DRF
GPU sharingFractional GPU support
Topology-aware placementNVLink/NVSwitch awareness
Workload priority and preemptionCritical job priority

HAMi GPU Hard Isolation

In June 2026, HAMi's GPU memory hard isolation shipped as a built-in feature of KAI Scheduler. This provides memory-level isolation for shared GPUs without requiring MIG.

KAI Scheduler Use Cases

Use CaseKAI?
Multi-team GPU sharing✅ Yes
Distributed training✅ Yes
Inference with sharing✅ Yes
Single-team cluster❌ Default scheduler

1:1 copy of the class Google Doc, code in code blocks.