We need to design a GPU-aware autoscaler for ML inference microservices. This is a detailed system design problem. The user likely expects a thorough solution: architecture, components, algorithms, data flow, integration, and SLA management. We need to produce a comprehensive answer.
We'll structure the response:
-
Problem statement and requirements: autoscaling for ML inference services on GPUs, taking into account GPU utilization, request latency, batch sizes, etc. Need telemetry, heuristics for bin-packing, prewarming, and SLA dashboards.
-
High-level architecture: components: telemetry collector, decision engine (autoscaler), pod scaler (K8s), prewarmer, dashboard.
-
Telemetry collection: what metrics to collect (GPU utilization, memory, compute, request latency, queue length, batch statistics, model load/unload times), how to collect (NVIDIA DCGM, Kubernetes metrics, custom exporters), sampling, aggregation.
-
Bin-packing heuristics: scheduling decisions to place pods on GPU nodes efficiently. Consider GPU memory usage, compute capability, MIG (if applicable), and affinity/anti-affinity. Use algorithms like first-fit decreasing, best-fit, or more advanced ML-based predictions. Include handling of multi-model pods (multiple models on same GPU) and shareable resources. Need to consider fragmentation and overhead.
-
Prewarming strategies: predict incoming load and pre-warm nodes/pods. Use time-series forecasting (e.g., Prophet, LSTM) on request rates, plus events (schedule, news). Pre-warm by creating pods (or ensuring GPU nodes are available) in advance. Also consider model caching (loading models into GPU memory) to reduce cold start latency. Might need to pre-load models onto idle GPUs.
-
Autoscaling logic: when to scale out/in (thresholds, reactive vs predictive). GPU-aware: target metrics per GPU (e.g., keep utilization between 60-80%). Also consider scaling based on end-to-end latency. Use multiple metrics with weights. Might implement custom metrics for K8s HPA or use external autoscaler.
-
SLA dashboards: visualize key metrics: latency percentiles, GPU utilization, autoscaling events, model load times, error rates, capacity vs demand. Show predictive vs actual. Alerting on SLA breaches.
-
Implementation details: using Kubernetes, NVIDIA GPU operator, custom metrics API, prometheus/grafana, maybe a service like KEDA for event-driven scaling. The decision engine as a separate service (maybe written in Go/Python) that watches metrics and applies policies.
-
Challenges: heterogeneity of GPUs, model sizes, batch processing, cold start, GPU memory fragmentation, cost optimization. Solutions.
-
Summary.
We need to be detailed, but not overly verbose. Provide algorithms, maybe pseudo-code for bin-packing. Also mention integration with inference frameworks (TensorRT, Triton, TorchServe). And ensure the design is practical.
We can also talk about capacity planning: pre-warming nodes (using cluster autoscaler) and pod-level autoscaling.
Let's outline:
I. Introduction
II. System Architecture
A. Telemetry Layer
B. Decision Engine
C. Scaling Executor
D. Prewarmer
E. Dashboard
III. Telemetry Collection
-
Metrics: GPU (DCGM), Pod (CPU/memory), Inference (latency, queue, batch), Model (load times, memory).
-
Collection: Prometheus node exporter, DCGM exporter, custom sidecar or server.
-
Aggregation and storage.
IV. Bin-Packing Heuristics for GPU Pod Placement
-
Problem: assign inference pods (each with GPU requirements, memory, maybe specific GPU type) to nodes to maximize utilization and minimize fragmentation.
-
Algorithm: First-fit decreasing (sort pods by memory descending, assign to first node with enough memory). But need to account for multi-model pods (multiple models on same GPU) as separate "containers"? Actually, in Kubernetes, each pod can request a GPU, but multiple pods can share a GPU? With MIG, we can partition; otherwise, one pod typically gets exclusive GPU. But for ML inference, we often run multiple models on the same GPU using a framework like Triton, which can handle multiple models in one process, but that's a single pod. Or multiple pods can't share a GPU unless using MIG or time-slicing. So bin-packing might be at pod level: each pod requests 1 GPU, but may have memory limit. So we need to assign pods to nodes with enough GPU memory and compute, while leaving room for growth. Could also consider GPU sharing via MIG (NVIDIA) to treat GPU as slices. We should design for both scenarios: exclusive and MIG. Also consider that some models require high compute, some are memory-bound.
-
Heuristic: For each node, we have total GPU memory and compute capacity. When placing a pod, we allocate a GPU (or MIG instance) that fits the model's memory requirement. Use a score based on memory utilization and compute utilization to minimize waste. Could also use knapsack-like algorithm.
-
Implementation: decision engine interacts with Kubernetes scheduler via custom scheduler or by using the default scheduler with node selectors/taints? Usually, autoscaler just adds replicas and scheduler places them. But we want GPU-aware placement. Could use a custom scheduler or scheduler extender (like Descheduler). Or use "resource wipe" in node utilization. Alternatively, let the default scheduler handle but influence with node affinity and taints. The autoscaler could choose which nodes to add pods to by setting nodeSelector? Better to have a custom scheduler for GPU-intensive workloads. Or we can rely on the cluster autoscaler to add nodes, and then the pod scheduler to place pods based on available resources. But the bin-packing is at cluster level: we want to pack pods efficiently onto existing nodes before adding new nodes. The default scheduler does bin-packing? It spreads by default? Actually, default scheduler uses a priority function that includes "MostRequestedPriority" to bin-pack. But we may need to customize for GPU memory. Could develop a scheduler plugin. Alternatively, the autoscaler could evict and reschedule? But simpler: In the decision engine, when we decide to scale out, we could create a "placement hint" by adding a node label to a node we want to use? That's not straightforward.
V. Prewarming Strategies
-
Two levels: node prewarming (start up GPU nodes) and pod prewarming (start inference pods before traffic arrives) and model preloading (load model into GPU memory before request).
-
Node prewarming: predict future load, request nodes from cloud provider (e.g., spot instances) ahead of time. Use time-series forecasting of request rate per service. If forecast > current capacity minus buffer, then scale nodes proactively. Use cluster autoscaler with --expander=random? Or directly create nodes via cloud provider API? Usually cluster autoscaler manages node pools; we can also manage separate node groups for GPU and use preemptible/spot. Prewarming nodes can be done by scaling the node pool ahead of time.
-
Pod prewarming: Instead of waiting for HPA to react, we can create extra pods (replicas) on standby that are running but not receiving traffic? But in a typical service mesh, traffic is load-balanced to all pods. So having extra pods will distribute traffic; but we don't want to over-provision unnecessarily. Perhaps we can use the "over-provisioning" pattern: keep a number of ready pods that are not fully loaded? Actually, autoscaling usually sets replicas based on load; pre-warming means we increase replicas before the load actually spikes. So we set a higher replica count than current demand. Those pods will handle load when it arrives. That's fine; they will be idle until traffic, but they consume resources (GPU memory, maybe a model loaded). That's okay if we have slack nodes. So prewarming essentially means we anticipate and scale out earlier than reactive thresholds.
-
Model preloading: Models may be large, and loading into GPU can take seconds. If a pod starts up and needs to load a model, there is a cold start latency. Solutions: keep models cached in GPU memory across pods? If pods share GPU, but not typical. Could use a model server like Triton that maintains a model repository and loads models on demand; but still cold start. To prewarm models, we can have a sidecar that loads the model into GPU as soon as the pod starts, and we keep the pod running (even if no traffic) to have the model loaded. That's essentially pod prewarming. Alternatively, use a shared model cache using NVIDIA GPU Cache (like with MPS?). Not standard. So we'll focus on pod prewarming.
-
forecasting: Use historical data, daily/weekly patterns, and detect upcoming events (e.g., product launch). Use models like Prophet, LSTM, or even simpler moving averages with confidence intervals. Set a safety margin. When predicted load (req/s) exceeds current capacity * predictive threshold, trigger scaling actions with lead time.
-
Trigger prewarming at service level: for each deployment, compute predicted required replicas based on per-pod capacity (based on average throughput). Also account for GPU memory constraints.
VI. SLA Dashboards
- Metrics: request latency (p50, p95, p99), error rate, throughput, GPU utilization, GPU memory, number of pods, node count, autoscaling events, model load time, queue length, batch size.
- Dashboards: real-time graphs, time series comparisons, capacity planning forecast vs actual.
- Alerting: if latency > SLA threshold, if utilization > high threshold for prolonged period, if model load time > threshold, if prewarm failure.
- Tools: Grafana with Prometheus data source. Use custom exporters to expose metrics.
VII. Implementation Details
- Use Kubernetes with NVIDIA GPU operator for GPU support.
- Telemetry: Prometheus server scrapes DCGM exporter, kube-state-metrics, and custom metrics from inference servers (maybe via Prometheus client). Also collect from sidecar for model load times.
- Decision engine: a separate service (e.g., written in Go) that periodically evaluates (or event-driven) and adjusts HPA or deployment replicas. Alternatively, extend KEDA with custom scaler.
- Scaling executor: uses Kubernetes API to patch deployment replica counts, or to create node pools.
- Prewarmer: part of decision engine; may also use a job to pre-load models? Actually, just scaling pods.
- SLA dashboard: Grafana dashboards, maybe with alerts to Slack.
VIII. Algorithms and Pseudo-code
-
Describe bin-packing: define NodeGPU struct with used_memory, used_compute, total_memory, total_compute. PodGPU requirement: min_memory, min_compute. Choose node with best fit (remaining memory close to requirement but not less). Actually best-fit: minimize leftover. So iterate nodes, compute candidate nodes that can fit, pick one with smallest leftover memory after allocation. Could also consider compute. Might be multi-dimensional bin packing; could treat as knapsack with two constraints. Simplify by using memory as primary constraint, because compute often correlated, but we can have separate limits. Could use a score = (remaining_memory - required_memory) + (remaining_compute - required_compute) but weighted. Or choose max(remaining_memory/required_memory, remaining_compute/required_compute) >1 but minimize max? We need a heuristic.
-
We'll propose: For each node, compute fit_score = (node.free_memory - pod.mem_req) + (node.free_compute - pod.compute_req) if both non-negative; choose node with smallest fit_score. If none, trigger new node.
-
For scaling in: select pods on nodes with highest utilization (or lowest number of pods) to remove, but ensure we don't remove below min replicas. Also consider if pod is only one using a model, etc. Might simply remove the pod with the highest load? Actually scaling in aims to reduce number of pods; we want to pick pods that are least useful; heuristic: choose pod on node with highest total utilization, or the pod with lowest request count? Or use a cost function: if we remove a pod, we need to ensure remaining capacity still meets load. We need to first compute required number of replicas based on current load and per-pod capacity. If we have more than needed, we can remove any. But we want to pack. So after deciding we need to reduce by X replicas, we choose nodes where removal improves pack (e.g., nodes with low utilization could become empty and be candidate for node downsizing). Might be complex. Simpler: remove pods from nodes with highest GPU utilization, because that might free up space to consolidate onto fewer nodes, allowing node removal. Or if we have many underutilized nodes, we could move pods? But without migration, we just delete pods; the scheduler will place new ones on nodes with capacity. For scaling in, we can set pod deletion to happen on nodes with highest utilization, but that might cause fragmentation. Better to delete pods from nodes with smallest number of pods, to empty nodes and allow cluster autoscaler to delete nodes. So we can choose pods on nodes with fewest pods first. We'll propose that.
-
Prewarming forecasting: Use time-series per service. For each service, gather request rate metrics (e.g., requests per second) from Prometheus. Resample to 5-min intervals. Train a model offline or use simple exponential smoothing with weekly seasonality. Predict for next N steps (e.g., next 30 min). Compute required replicas = ceil(predicted_rps / avg_pod_throughput). Add buffer (e.g., 20%). If required > current, then set desired replicas = required. If required < current *0.8? maybe scale in.
IX. Edge Cases and Optimizations
- Model switching: pods may serve multiple models; need to account memory for each model when they are hot. Could use model-level metrics: per-model memory usage on GPU. Telemetry should collect per-model memory if possible (via Triton metrics).
- Multiple GPU types: nodes may have different GPUs (e.g., T4, A100). Need to match pod requirements (maybe via node labels). Bin-packing should group similar GPUs.
- MIG: partition GPUs into smaller instances. Our telemetry should treat MIG instances as separate GPU resources? Actually, Kubernetes treats MIG as separate device IDs. So we could have multiple pods on same physical GPU but each gets a MIG slice. That's useful for isolation. Our bin-packing must consider MIG profile.
- GPU sharing via time-slicing: not recommended for inference due to latency. So we stick to exclusive.
X. Summary
We'll produce a structured answer with sections.
Also, we might include diagrams? We can't draw, but we can describe.
Make sure we address all parts: telemetry collection, bin-packing heuristics, prewarming strategies, and SLA dashboards.
We'll assume ML inference microservices are deployed as Kubernetes pods, each requesting a GPU. They might use Triton Inference Server or similar.
Let's begin writing.
GPU‑Aware Autoscaler for ML Inference Microservices
1. Overview
ML inference services often run on GPUs and must meet strict latency SLAs while keeping GPU utilization high to control cost. An autoscaler must:
- Collect fine‑grained telemetry from GPUs, pods, and inference requests.
- Make bin‑packing decisions to place pods efficiently on GPU nodes.
- Pre‑warm capacity before traffic spikes to avoid cold‑start latency.
- Provide dashboards for operators to monitor SLA compliance and capacity.
The design below is Kubernetes‑native and works with any inference framework (Triton, TorchServe, TensorFlow Serving, etc.). It can be deployed as a set of custom controllers or integrated with existing tools like KEDA and Cluster Autoscaler.
2. High‑Level Architecture
+-------------------+ +-------------------+ +-------------------+
| Telemetry | | Decision | | Execution |
| Collector | ---> | Engine | ---> | (K8s API) |
| (DCGM, Prom, etc) | | (Heuristics, | | - Scale pods |
+-------------------+ | Forecast) | | - Add nodes |
^ +-------------------+ | - Prewarm pods |
| ^ +-------------------+
| | |
+-------------------+ +-------------------+ |
| SLA Dashboard | <---- | Prewarmer | <-----------+
| (Grafana/Alert) | | (Forecast, |
+-------------------+ | Warm‑up Jobs) |
+-------------------+
- Telemetry Collector: Scrapes GPU, pod, and inference metrics into a central store (Prometheus).
- Decision Engine: Core autoscaler that evaluates current vs. desired capacity using bin‑packing and predictive models.
- Execution: Adjusts Kubernetes replica counts or node pool sizes.
- Prewarmer: Runs alongside the Decision Engine to trigger proactive scaling.
- SLA Dashboard: Visualizes metrics and alerts on SLA violations.
3. Telemetry Collection
3.1 Metrics to Capture
| Category | Metric | Source | Purpose |
|---|
| GPU hardware | dcgm_gpu_utilization, dcgm_fb_used, dcgm_fb_free, dcgm_power_usage | NVIDIA DCGM exporter | Bin‑packing, bottleneck detection |
| Kubernetes pod | container_cpu_usage, container_memory_usage, kubepod_status_phase | kube‑state‑metrics, cAdvisor | Coarse resource usage, liveness |
| Inference request | inference_request_latency_seconds, inference_queue_length, inference_batch_size, inference_requests_total | Inference server Prom client (e.g., Triton metrics) | SLA tracking, throughput per pod |
| Model loading | model_load_duration_seconds, model_memory_usage_bytes | Custom sidecar or server event | Cold‑start latency, memory planning |
| Node capacity | node_gpu_count, node_gpu_memory_total | Node labels + DCGM | Cluster capacity |
All metrics are scraped by Prometheus and stored for 30‑90 days (depending on retention). Tagging:
namespace, pod, model_name, gpu_id, node.
3.2 Collection Setup
- DCGM Exporter: Runs as DaemonSet on GPU nodes.
- kube‑state‑metrics: Provides pod‑to‑node mapping.
- Inference server: Exposes Prometheus endpoint (e.g., Triton has built‑in metrics; TorchServe can be configured). If not available, run a sidecar exporter that translates server logs/events to Prometheus.
- Model‑load exporter: Instrument model loading code to emit
model_load_duration_seconds and model_memory_usage_bytes as a gauge when a model is loaded/unloaded.
Aggregation: Use PromQL to create derived metrics:
sum(rate(inference_requests_total[1m])) by (deployment) → request rate.
avg(dcgm_gpu_utilization) by (node) → node GPU utilization.
max(inference_queue_length) by (pod) → per‑pod backlog.
4. Bin‑Packing Heuristics for GPU Pod Placement
4.1 Placement Problem
Each inference pod requests exclusive access to a GPU (or a MIG slice). We must decide which node (and which GPU on that node) will host a new pod to maximize overall utilization and minimize fragmentation. Constraints:
- GPU memory must be ≥ model memory requirement + overhead.
- Compute capability (e.g., SM count, Tensor Core) should match workload (some models are compute‑bound).
- Heterogeneous GPU types (T4, A100, etc.) require matching.
- MIG: If a node uses MIG, treat each MIG instance as a separate “GPU” with its own memory/compute.
4.2 Data Structures
class NodeGPU:
node: string
gpu_id: int # physical GPU index or MIG instance id
total_memory: int # in MiB
total_compute: int # normalized compute units (e.g., SM count)
used_memory: int
used_compute: int
# optional: gpu_type (e.g., "a100")
Maintain a global view of all NodeGPUs, refreshed every few seconds from Prometheus/DCGM and the Kubernetes API.
4.3 Heuristic: Best‑Fit Decreasing (BFD)
When scaling out:
- Sort pending pod requests by decreasing memory requirement (or a combined score
memory * α + compute * β). Typically memory is the limiting factor.
- For each pod, select the node GPU that:
- Has
free_memory >= pod.mem_req AND free_compute >= pod.comp_req.
- Minimizes a waste score:
waste = (free_memory - pod.mem_req) + (free_compute - pod.comp_req). (Weighted sum can be used.)
- If multiple nodes tie, choose the one with highest current utilization (to further pack).
- If no node fits, the Decision Engine marks the deployment as needing more nodes → triggers cluster autoscaler (via expanding node pool or adding new node group).
When scaling in:
- Target pods to delete on nodes with lowest pod count first, because removing a pod from a node with 1‑2 pods may free an entire node, enabling the Cluster Autoscaler to delete it.
- Avoid removing the only pod serving a model that would otherwise become unavailable; maintain a minimum replica count per deployment.
We can also occasionally run a descheduler (e.g., Kubernetes Descheduler with custom policy) to reshuffle pods if fragmentation becomes high.
4.4 Interaction with Scheduler
The Decision Engine does not directly place pods; it:
- Annotates pods with a preferred node name (via
spec.affinity.nodeAffinity) when they are created, based on the best‑fit node.
- If the POD is part of a Deployment, we can set
spec.template.spec.affinity using a mutating webhook that injects the affinity at creation time.
- Alternatively, we can use the cluster‑autoscaler’s “node‑group‑updater” to add a taint to nodes we want to avoid, guiding the default scheduler.
5. Prewarming Strategies
Prewarming addresses cold start latency: model loading onto a GPU can take 1‑10 seconds. To avoid penalizing users during spikes, we keep capacity ready before demand arrives.
5.1 Levels of Prewarming
- Node‑level: Launch new GPU nodes before they are needed, reducing the time for the Cluster Autoscaler to provision them (which can be minutes).
- Pod‑level: Increase replica counts ahead of traffic so idle pods are already running with models loaded.
- Model‑level: Pre‑load models into GPU memory on warm pods (usually happens automatically when the pod starts).
5.2 Forecasting Model
For each inference service:
5.3 Trigger Logic
- Periodic (every 5‑10 min) run the forecast for all services.
- If
needed_replicas > current_replicas * 1.2 → scale out to needed_replicas.
- If
needed_replicas < current_replicas * 0.8 → scale in (after a longer cool‑down to avoid flaps).
- Forecast‑driven scaling is coarse; a reactive loop runs more frequently (every 30 s) to handle sudden spikes (e.g., if GPU utilization > 85% for 2 min, add one replica immediately). The two loops work together; reactive scaling takes precedence for immediate action but the predictive loop adjusts the baseline.
5.4 Node Prewarming
- If the forecast indicates that the cluster will need N additional GPUs and the current node pool has insufficient capacity, ask the Cluster Autoscaler to increase the node pool size proactively.
- On cloud providers: set the node pool size via API (e.g., GKE
gcloud container clusters resize).
- Alternatively, maintain a warm pool of pre‑emptible/spot GPU nodes in “stopped” state that can be started quickly (some clouds support “instance‑suspend”).
- Pre‑warming nodes is cheaper than keeping them running all the time. Use spot instances for cost savings; if pre‑empted, autoscaler will request a new node.
5.5 Avoiding Over‑Provisioning
- The safety buffer and separate scale‑in hysteresis keep resource usage reasonable.
- Use budget alerts (e.g., if GPU‑hours exceed threshold) to adjust buffer size.
6. SLA Dashboards
6.1 Primary SLAs
- Latency: P95, P99 request latency (e.g., < 100 ms for p99).
- Availability: Success rate > 99.9%.
- Throughput: Minimum requests per second per pod (capacity guarantee).
6.2 Dashboard Panels (Grafana)
| Panel | Description | Metrics |
|---|
| Cluster GPU Utilization | % of total GPU memory & compute used | sum(dcgm_fb_used) / sum(dcgm_fb_total) |
| Per‑Service Latency | p95, p99 latency trend | histogram_quantile(0.99, rate(inference_latency_seconds_bucket[5m])) |
| Autoscaling Events | Timeline of replica changes & node additions | kube_deployment_status_replicas_updated, custom event log |
| Model Load Time | Box plot of model_load_duration_seconds per model | model_load_duration_seconds |
| Capacity vs Demand | Current total capacity (max_qps) vs current load (qps) | custom calculations |
| Queue Length | Max queue length per pod | inference_queue_length |
| Forecast Error | Difference between predicted and actual rps | Δ = forecast - actual (computed) |
6.3 Alerting Rules (Prometheus Alertmanager)
- LatencySLA:
histogram_quantile(0.99, rate(inference_latency_seconds_bucket[5m])) > 0.1 for 2 minutes.
- HighUtilization:
avg(dcgm_gpu_utilization) by (node) > 90 for 10 minutes.
- ColdStartRisk:
model_load_duration_seconds > 5 for recent pods.
- PrewarmFailure:
forecast_qps - current_capacity > safety_margin for 5 minutes.
- ResourceWaste:
avg(dcgm_fb_used) by (node) < 20 for 30 minutes (underutilized nodes → possible downscale).
7. Implementation Details
7.1 Kubernetes Setup
- GPU Operator (NVIDIA) to manage drivers and DCGM.
- Node labels:
nvidia.com/gpu.product (e.g., A100-SXM4-40GB), nvidia.com/gpu.memory.
- MIG: If used, node labels enumerate MIG instances as separate GPUs (
nvidia.com/gpu.mig.strategy=singleton).
7.2 Prometheus Stack
- Deploy Prometheus with
scrape_interval: 15s.
- Import:
dcgm-exporter DaemonSet.
kube-state-metrics.
node-exporter.
- Inference server exporters.
7.3 Decision Engine as Custom Autoscaler
- Write an external component (Go/Python) that:
- Queries Prometheus for current metrics.
- Runs the forecast (weekly retrain) and bin‑packing.
- Computes desired replica counts per deployment and desired node pool size.
- Calls Kubernetes APIs:
- Patch Deployment
spec.replicas.
- Annotate new pods with
affinity (if needed).
- Update node pool size via cloud provider API or by patching a
MachineDeployment (Cluster API).
- Implement cooldown periods (e.g., 2 min after scaling before another scale‑out) to avoid thrashing.
- Use leader election (e.g.,
kopf or built‑in lock) if running multiple replicas for HA.
7.4 Integration with Existing Tools
- KEDA (Kubernetes Event‑Driven Autoscaling) can be extended with a custom scaler that reads our predictive metrics and adjusts scale.
- Cluster Autoscaler: we can use its expander and node‑group‑updater to add nodes. Our Decision Engine may simply adjust the node pool size; Cluster Autoscaler will then provision nodes.
7.5 Model‑Load Prewarming on Pods
- Inference pods should start with the model already loaded. This is done by:
- Using an initContainer that loads the model into GPU memory before the main container starts (if framework supports it).
- Or, the main container loads the model on start and we treat a pod as “ready” only after model load finishes (readiness probe checks for a
model_loaded flag). The pod stays in Ready state once the model is loaded, and subsequent requests hit it.
- This ensures that a newly scaled‑out pod is instantly ready to serve requests.
8. Edge Cases & Optimizations
8.1 Heterogeneous GPUs
- Label nodes with
gpu-type and gpu-memory.
- When a pod has a requirement (e.g.,
nvidia.com/gpu.memory: "16Gi" and nvidia.com/gpu.type: "a100"), the bin‑packing algorithm only considers nodes matching the type.
8.2 MIG Partitioning
- Treat each MIG instance as a separate
NodeGPU with its own memory/compute (DCGM exposes per‑MIG stats).
- Pods request a specific
nvidia.com/gpu.mig.instance label.
- The bin‑packing algorithm handles these as smaller resource units, dramatically improving packing density for small models.
8.3 Multi‑Model Pods (Triton)
- A single pod (e.g., Triton server) can host multiple models. The pod’s total GPU memory requirement is the sum of all active models. Our telemetry must capture per‑model memory usage inside the pod (Triton exposes
nv_gpu_model_memory_usage). The bin‑packing decision for a new pod must account for the entire set of models it will run (known from deployment configuration). If dynamic model loading occurs, we must keep a buffer.
8.4 GPU Compute vs Memory
- Some models (e.g., large transformer) are memory‑bound, others (e.g., CNN) are compute‑bound.
- We compute two resource dimensions:
mem_req = model memory size + overhead.
comp_req = estimated SM utilization (e.g., from profiling) normalized to a common scale.
- The best‑fit score becomes a multi‑dimensional packing problem. A simple approach: pick the most constrained dimension (usually memory) first, then within those candidates choose the one with highest free compute.
8.5 Handling Bursty Traffic
- The reactive loop reacts within 30 s to high utilization.
- Use fast‑scale‑out mode: when utilization > 90% for two consecutive samples, add multiple replicas (e.g., double) to catch up quickly.
- The pre‑warmer will have already primed the capacity if forecasting is accurate, reducing reliance on reactive spikes.
8.6 Cost Optimization
- Prefer spot/pre‑emptible GPU instances for non‑critical services. If a spot node is reclaimed, pods are evicted; the autoscaler will quickly spin up a replacement from a different pool (on‑demand) if needed, but at higher cost. Use mixed‑instance policies (node group with on‑demand and spot, with priorities).
- Use right‑sizing: measure the actual memory and compute used by each model; set pod requests accordingly to avoid over‑allocation.
9. Sample Pseudo‑Code: Decision Loop
import time
from kubernetes import client as k8s
import prometheus
class Autoscaler:
def __init__(self):
self.prom = prometheus.PrometheusClient()
self.k8s = k8s.AppsV1Api()
self.cluster_autoscaler = ClusterAutoscalerClient()
def run(self):
while True:
self.predictive_loop()
self.reactive_loop()
time.sleep(30) # reactive loop period
def predictive_loop(self):
# runs every 10 minutes
for deployment in self.get_deployments():
forecast_qps = self.forecast_qps(deployment)
current_replicas = deployment.status.replicas
needed = self.replicas_from_qps(forecast_qps, deployment)
if needed > current_replicas * 1.2:
self.scale_deployment(deployment, needed)
elif needed < current_replicas * 0.8:
self.scale_deployment(deployment, max(needed, deployment.min_replicas))
# Node pool prewarming
total_gpu_needed = sum(self.pending_gpu_demand())
current_gpu_capacity = self.total_gpu_capacity()
if total_gpu_needed > current_gpu_capacity * 0.9:
extra = total_gpu_needed - current_gpu_capacity
self.cluster_autoscaler.expand_node_pool(int(extra) + 1)
def reactive_loop(self):
for node in self.get_gpu_nodes():
if node.gpu_utilization > 0.85 for 2 minutes:
# find deployment causing load; simplistic: pick a deployment with highest qps
dep = self.hot_deployment(node)
current = dep.replicas
self.scale_deployment(dep, current + 1)
def scale_deployment(self, dep, target_replicas):
patch = {"spec": {"replicas": target_replicas}}
self.k8s.patch_namespaced_deployment_scale(dep.name, dep.namespace, patch)
def get_gpu_nodes(self):
# query DCGM + k8s to build NodeGPU objects
pass
# ... other helper methods
The bin‑packing advice (node affinity) is applied when creating new pods via a mutating webhook that reads a desired-node annotation from the Deployment (set by the Decision Engine based on the best‑fit node for the upcoming replica). Alternatively, the Decision Engine could directly create a ReplicaSet with proper affinity (but modifying Deployments is standard).
10. Conclusion
This design provides a GPU‑aware autoscaling solution for ML inference microservices that:
- Continuously monitors GPU, pod, and inference metrics.
- Uses bin‑packing heuristics to maximize utilization and reduce fragmentation.
- Employs time‑series forecasting to pre‑warm both nodes and pods, minimizing cold‑start latency.
- Offers real‑time SLA dashboards and alerts.
All components are built on Kubernetes and open‑source tools (Prometheus, Grafana, DCGM, KEDA), making the system portable and extensible. The modular architecture allows operators to tune each piece (e.g., swapping Prophet for an LSTM) without rewriting the entire platform.