Skip to content
About Me
----

GPU Optimization & Spot Instances: Karpenter, NVIDIA MIG & Cost Engineering

Architect Key Takeaways

Production guide to slashing enterprise AI/ML infrastructure costs by 70%+ using Karpenter GPU NodePools, NVIDIA Multi-Instance GPU (MIG) slicing, AWS Neuron Inferentia, and fault-tolerant spot training.

GPU Optimization & Spot Instances: Karpenter, NVIDIA MIG & Cost Engineering

Section titled “GPU Optimization & Spot Instances: Karpenter, NVIDIA MIG & Cost Engineering”

Graphics Processing Units (GPUs) represent the single largest cloud expenditure in modern enterprise engineering budgets. An on-demand cluster of 8x NVIDIA H100 or A100 nodes can easily surpass $25,000 to $50,000 per month.

Without disciplined cost engineering, ML platforms suffer from massive waste:

  • Low GPU Utilization: Inference pods reserving an entire $3.67/hr GPU while using only 8% compute capacity.
  • On-Demand Overspending: Running batch training jobs on static, expensive on-demand nodes instead of leveraging 70% cheaper Spot instances.
  • Node Fragmentation: Kubernetes cluster autoscalers failing to bin-pack heterogeneous GPU instances.

This handbook details the production strategies used by top cloud architects to cut GPU infrastructure costs by 60% to 80% without sacrificing performance or SLA.

Enterprise GPU Cost Optimization Architecture


1. Hardware Slicing: NVIDIA MIG (Multi-Instance GPU)

Section titled “1. Hardware Slicing: NVIDIA MIG (Multi-Instance GPU)”

In many production environments, smaller models (e.g., embedding generators, rerankers, BERT classifiers, or Whisper ASR) do not require a full 80GB A100 or H100 GPU. However, standard Kubernetes scheduling assigns one physical GPU per container, locking out other workloads.

MIG (Multi-Instance GPU) partitions an NVIDIA A100 or H100 into up to 7 independent hardware instances:

  • Each MIG instance features completely isolated memory (VRAM), memory controllers, and Streaming Multiprocessors (SMs).
  • True hardware isolation: A fault or Out-Of-Memory (OOM) error in one MIG slice will never crash neighboring workloads.
  • Zero “noisy neighbor” latency spikes compared to shared software slicing.
MIG Profile Compute (SMs) Dedicated VRAM Max Instances per GPU Ideal Production Workload
1g.10gb 1/7 (~14 SMs) 10 GB 7 Embedding models (bge-large), OCR, Fraud Detection, Rerankers
2g.20gb 2/7 (~28 SMs) 20 GB 3 Mid-sized NLP, Whisper Speech-to-Text, Quantized LLaMA 8B
3g.40gb 3/7 (~42 SMs) 40 GB 2 Heavy computer vision (YOLOv8x), batch processing
7g.80gb Full GPU (98 SMs) 80 GB 1 Full distributed training, unquantized LLM inference

1.3 Configuring MIG with the NVIDIA GPU Operator

Section titled “1.3 Configuring MIG with the NVIDIA GPU Operator”

Enable MIG mode dynamically on your EKS worker nodes by applying a ConfigMap to the gpu-operator:

apiVersion: v1
kind: ConfigMap
metadata:
name: default-mig-parted-config
namespace: gpu-operator
data:
config.yaml: |
version: v1
mig-configs:
all-1g.10gb:
- devices: all
mig-enabled: true
mig-devices:
"1g.10gb": 7

Once applied, Kubernetes exposes MIG instances as standard resources:

# Pod manifest requesting an isolated 1g.10gb MIG slice
apiVersion: v1
kind: Pod
metadata:
name: embedding-service
namespace: mlops
spec:
containers:
- name: text-embeddings
image: ghcr.io/huggingface/text-embeddings-inference:1.2
resources:
limits:
nvidia.com/mig-1g.10gb: 1

2. Dynamic GPU Provisioning with Karpenter

Section titled “2. Dynamic GPU Provisioning with Karpenter”

Legacy Kubernetes Cluster Autoscaler (CAS) is slow: it takes 5–8 minutes to discover unevictable pods, launch EC2 instances, and initialize NVIDIA drivers.

Karpenter bypasses Node Groups entirely, evaluating pending pod compute requests and provisioning optimized, bare EC2 GPU instances directly in under 45 seconds.

2.1 Production Karpenter EC2NodeClass and NodePool for GPU Workloads

Section titled “2.1 Production Karpenter EC2NodeClass and NodePool for GPU Workloads”
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: gpu-spot-nodepool
spec:
template:
spec:
requirements:
# 1. Prefer cost-effective Spot instances (up to 70% discount)
- key: karpenter.sh/capacity-type
operator: In
values: ["spot", "on-demand"]
# 2. Allow modern cost-optimized GPU families
- key: node.kubernetes.io/instance-type
operator: In
values:
- g5.2xlarge # 1x A10G (24GB VRAM) - ~$0.40/hr Spot
- g5.12xlarge # 4x A10G (96GB VRAM) - ~$1.70/hr Spot
- g6.8xlarge # 1x L4 (24GB Ada Lovelace)
- p4d.24xlarge # 8x A100 (320GB VRAM) - For large distributed training
- key: kubernetes.io/arch
operator: In
values: ["amd64"]
nodeClassRef:
group: karpenter.k8s.aws
kind: EC2NodeClass
name: gpu-nodeclass
taints:
- key: nvidia.com/gpu
value: "true"
effect: NoSchedule
# Automatically consolidate or terminate idle GPU nodes
disruption:
consolidationPolicy: WhenEmpty
consolidateAfter: 60s
---
apiVersion: karpenter.k8s.aws/v1
kind: EC2NodeClass
metadata:
name: gpu-nodeclass
spec:
amiFamily: AL2
subnetSelectorTerms:
- tags:
karpenter.sh/discovery: enterprise-eks-cluster
securityGroupSelectorTerms:
- tags:
karpenter.sh/discovery: enterprise-eks-cluster
blockDeviceMappings:
- deviceName: /dev/xvda
ebs:
volumeSize: 200Gi
volumeType: gp3
iops: 10000
throughput: 500

3. Fault-Tolerant Distributed Training on Spot Instances

Section titled “3. Fault-Tolerant Distributed Training on Spot Instances”

Spot instances offer 60% to 80% cost savings over on-demand pricing, but come with one critical constraint: AWS can reclaim the instance with a 2-minute termination warning.

If a spot node in a 4-node PyTorch training cluster is terminated without protection, the entire training run crashes and days of compute are lost.

  1. AWS Node Termination Handler (NTH): Monitors AWS EventBridge for EC2 Spot Interruption Warnings (EC2 Spot Instance Interruption Notice).
  2. Graceful SIGTERM Hook: When termination notice arrives (120-second countdown), Kubernetes sends SIGTERM to worker pods.
  3. Emergency Checkpoint Flush to S3: The PyTorch training loop catches SIGTERM, pauses gradient updates, flushes weights to local NVMe, and uploads an emergency checkpoint snapshot to Amazon S3.
import os
import signal
import sys
import torch
import boto3
class SpotTerminationHandler:
"""Catches Kubernetes SIGTERM from Karpenter / AWS Spot Termination Handler."""
def __init__(self, model, optimizer, epoch, s3_bucket, checkpoint_prefix):
self.model = model
self.optimizer = optimizer
self.epoch = epoch
self.s3_bucket = s3_bucket
self.prefix = checkpoint_prefix
self.interrupted = False
# Register OS signal handlers for graceful termination
signal.signal(signal.SIGTERM, self._handle_termination)
signal.signal(signal.SIGINT, self._handle_termination)
def _handle_termination(self, signum, frame):
print(f"\n[ALERT] Spot Interruption Signal ({signum}) received! Initiating emergency checkpoint...")
self.interrupted = True
self.save_emergency_checkpoint()
print("[SUCCESS] Checkpoint safely synced to S3. Exiting cleanly.")
sys.exit(0)
def save_emergency_checkpoint(self):
checkpoint_path = f"/tmp/emergency_ckpt_epoch_{self.epoch}.pt"
torch.save({
'epoch': self.epoch,
'model_state_dict': self.model.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
}, checkpoint_path)
# Stream directly to S3
s3 = boto3.client('boto3')
s3.upload_file(checkpoint_path, self.s3_bucket, f"{self.prefix}/latest_checkpoint.pt")

When Karpenter provisions a replacement spot node ~60 seconds later, the training job pulls latest_checkpoint.pt from S3 and resumes without human intervention.


4. Alternative Accelerators: AWS Inferentia2 & Trainium

Section titled “4. Alternative Accelerators: AWS Inferentia2 & Trainium”

NVIDIA GPUs are not the only choice for enterprise AI. AWS has developed purpose-built custom silicon for deep learning:

  • AWS Trainium (trn1 instances): Built specifically for training large language models at 50% lower training cost than comparable EC2 GPU instances.
  • AWS Inferentia2 (inf2 instances): Purpose-built for generative AI and deep learning inference, offering 4x higher throughput and 10x lower latency than standard EC2 instances.

To leverage Inf2/Trn1 instances, install the AWS Neuron Helm Chart which provides the K8s device plugin:

# Pod requesting dedicated Neuron core on Inf2 instance
resources:
limits:
aws.amazon.com/neuroncore: 1

Technology Primary Use Case Cost Reduction Complexity SLA Tradeoff
NVIDIA MIG Multi-tenant inference & small models Up to 85% (7 workloads per GPU) Low None (Hardware isolated)
Karpenter Spot Distributed training & batch jobs 60% - 75% Medium Requires automated checkpointing
AWS Inferentia2 High-throughput LLM & GenAI inference 50% vs A10G Medium (requires Neuron compilation) None
Quantization (INT8/FP4) Compressing model footprint in VRAM 50% VRAM reduction Low (via vLLM / AWQ) Negligible accuracy impact (<1%)

🧠 Production Architecture Scenario: Sashing AI Cloud Spend

Section titled “🧠 Production Architecture Scenario: Sashing AI Cloud Spend”
Scenario: The Runaway $40,000/Month GPU Invoice

A fintech company is running 12 microservices on AWS EKS. Each microservice (embeddings, fraud classification, sentiment, text summary) has its own dedicated g5.2xlarge instance (1x A10G, $1.21/hr on-demand). In total, they run 24 pods (with replicas) across 24 on-demand nodes, generating $21,000/mo just for inference. GPU utilization metrics in Grafana show an average compute utilization of only 11%.

  1. Consolidate with MIG: Migrate the workloads to 4x p4d.24xlarge / A100 nodes partitioned into 1g.10gb and 2g.20gb MIG slices. The 24 workloads fit comfortably on only 4 physical GPUs with zero noisy neighbor interference.
  2. Replace On-Demand with Karpenter Spot: Provision instances using Karpenter’s spot-first policy with graceful node termination handling.
  3. Enable Autoscaling to Zero: During nighttime off-peak hours (1 AM to 6 AM), KServe scales non-critical inference replicas to zero.

Monthly GPU bill dropped from $21,000/mo to $4,800/mo (a 77% cost reduction), while maintaining sub-15ms p99 inference SLAs.