Tôi vẫn nhớ rõ ngày hôm đó — deadline sản phẩm còn 3 tiếng, production bỗng dưng CrashLoopBackOff toàn bộ pod inference. Logs trả về:
Error: failed to initialize NVIDIA container runtime:
cudaErrorInsufficientDriver: CUDA driver version is insufficient for CUDA runtime version
Container exited with code 137 (killed by OOM)
Hoá ra, developer mới deploy một model 15B params lên node chỉ có 4GB VRAM. Đó là lúc tôi nhận ra: Kubernetes GPU scheduling không chỉ là resource: nvidia.com/gpu: 1. Bài viết này sẽ chia sẻ toàn bộ kiến thức tôi đã đổ vỡ để xây dựng GPU cluster ổn định cho inference ở HolySheep AI.
1. Kiến Trúc GPU Scheduling Trong Kubernetes
Trước khi code, cần hiểu rõ 3 thành phần cốt lõi:
- Device Plugin: Giao diện giữa Kubernetes và NVIDIA driver
- Resource Manager: Quản lý allocation GPU cho containers
- Topology Manager: Tối ưu locality giữa GPU và NUMA node
2. Cấu Hình Node Với N标签
Đầu tiên, gắn labels cho node để phân loại GPU capacity:
# Liệt kê GPU hiện có trên node
nvidia-smi --query-gpu=gpu_name,memory.total,driver_version --format=csv
Gắn labels cho node gpu-node-01
kubectl label node gpu-node-01 \
nvidia.com/gpu.product=NVIDIA-A100-80GB \
nvidia.com/gpu.memory=80GB \
nvidia.com/gpu.count=4 \
gpu-tier=high-memory
3. Deploy GPU Device Plugin
# DaemonSet GPU Device Plugin
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nvidia-device-plugin-daemonset
namespace: kube-system
spec:
selector:
matchLabels:
name: nvidia-device-plugin
template:
metadata:
labels:
name: nvidia-device-plugin
spec:
tolerations:
- key: nvidia.com/gpu
operator: Exists
effect: NoSchedule
containers:
- image: nvcr.io/nvidia/k8s-device-plugin:v0.14.6
name: nvidia-device-plugin
args:
- "--config-file=/etc/config/nvidia-device-plugin/config.yaml"
env:
- name: PASS_SPECS_AS_ARGS
value: "true"
volumeMounts:
- name: config
mountPath: /etc/config/nvidia-device-plugin
volumes:
- name: config
configMap:
name: nvidia-device-plugin-config
4. Inference Deployment Với Resource Limits
Đây là phần critical nhất — nhiều người chỉ set nvidia.com/gpu: 1 mà quên memory và compute limits:
apiVersion: apps/v1
kind: Deployment
metadata:
name: llama-inference-service
labels:
app: llama-inference
spec:
replicas: 3
selector:
matchLabels:
app: llama-inference
template:
metadata:
labels:
app: llama-inference
spec:
nodeSelector:
gpu-tier: high-memory
containers:
- name: inference
image: holysheepai/llama-serve:latest
ports:
- containerPort: 8080
resources:
limits:
nvidia.com/gpu: 1
memory: 32Gi
cpu: "4"
requests:
nvidia.com/gpu: 1
memory: 28Gi
cpu: "2"
env:
- name: MODEL_NAME
value: "llama-3-8b-instruct"
- name: HF_TOKEN
valueFrom:
secretKeyRef:
name: hf-secrets
key: token
- name: MAX_BATCH_SIZE
value: "16"
- name: CUDA_VISIBLE_DEVICES
value: "0"
tolerations:
- key: "nvidia.com/gpu"
operator: "Exists"
effect: "NoSchedule"
5. Autoscaling Với KEDA + GPU Metrics
Scale inference pod dựa trên GPU utilization thay vì CPU:
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: llama-inference-scaler
namespace: production
spec:
scaleTargetRef:
name: llama-inference-service
minReplicaCount: 2
maxReplicaCount: 10
cooldownPeriod: 300
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus.monitoring:9090
metricName: gpu_utilization_avg
threshold: "70"
query: avg(gpu_utilization{gpu_device="0"})
6. Tích Hợp HolySheep AI API Cho Hybrid Inference
Với các model cần 85%+ chi phí tiết kiệm, tôi khuyên dùng đăng ký HolySheep AI — nơi tỷ giá chỉ ¥1=$1, hỗ trợ WeChat/Alipay, và latency trung bình dưới 50ms. So sánh giá 2026:
- DeepSeek V3.2: $0.42/MTok (rẻ nhất)
- Gemini 2.5 Flash: $2.50/MTok (cân bằng)
- GPT-4.1: $8/MTok
- Claude Sonnet 4.5: $15/MTok (đắt nhất)
Code tích hợp HolySheep API cho batch inference:
import requests
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY"
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
def inference_with_holysheep(prompt: str, model: str = "deepseek-v3.2") -> dict:
"""
Inference qua HolySheep API - latency <50ms
Tiết kiệm 85%+ so với OpenAI native
"""
headers = {
"Authorization": f"Bearer {HOLYSHEEP_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [
{"role": "system", "content": "Bạn là trợ lý AI chuyên về Kubernetes."},
{"role": "user", "content": prompt}
],
"temperature": 0.7,
"max_tokens": 2048
}
try:
response = requests.post(
f"{HOLYSHEEP_BASE_URL}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
raise TimeoutError("HolySheep API timeout > 30s")
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
raise PermissionError("Invalid API key - kiểm tra YOUR_HOLYSHEEP_API_KEY")
raise RuntimeError(f"HTTP {e.response.status_code}: {e.response.text}")
Batch inference với retry logic
def batch_inference(prompts: list, max_workers: int = 10):
results = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(inference_with_holysheep, p): i
for i, p in enumerate(prompts)
}
for future in as_completed(futures):
idx = futures[future]
try:
result = future.result()
results.append({"index": idx, "status": "success", "data": result})
except Exception as e:
results.append({"index": idx, "status": "error", "message": str(e)})
return results
Sử dụng
if __name__ == "__main__":
test_prompts = [
"Giải thích về Kubernetes GPU scheduling?",
"Cách config nvidia device plugin?",
"Tối ưu batch inference như thế nào?"
]
results = batch_inference(test_prompts)
print(f"Hoàn thành: {len([r for r in results if r['status']=='success'])}/{len(test_prompts)}")
7. Monitoring GPU Với PrometheusExporter
---
Prometheus rules cho GPU monitoring
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: gpu-monitoring-rules
namespace: monitoring
spec:
groups:
- name: gpu-alerts
rules:
- alert: GPUOutOfMemory
expr: DCGM_FI_DEV_FB_USED / DCGM_FI_DEV_FB_FREE > 0.95
for: 5m
labels:
severity: critical
annotations:
summary: "GPU {{ $labels.instance }} sắp hết VRAM"
description: "Memory usage: {{ $value | humanizePercentage }}"
- alert: GPUTemperatureHigh
expr: DCGM_FI_DEV_GPU_TEMP > 85
for: 2m
labels:
severity: warning
annotations:
summary: "GPU {{ $labels.instance }} quá nóng: {{ $value }}°C"
8. Priority và Preemption Cho GPU Pods
# Priority Classes
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: gpu-production-priority
value: 1000
globalDefault: false
description: "Production inference pods - không bị preempt"
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: gpu-batch-priority
value: 500
globalDefault: false
description: "Batch training jobs - có thể bị preempt"
---
Apply priority vào pod spec
spec:
priorityClassName: gpu-production-priority
containers:
- name: inference
image: holysheepai/llama-serve:latest
Lỗi Thường Gặp Và Cách Khắc Phục
1. Lỗi "CUDA out of memory" Mặc Dù Đã Set Limits
# Nguyên nhân: OOMKilled do kernel overhead không tính trong limits
Giải pháp: Set memory limits cao hơn 20-30% so với VRAM thực tế
resources:
limits:
nvidia.com/gpu: 1
memory: 32Gi # Model 8B cần ~16GB VRAM, set 32GB buffer
Hoặc set runtime class cho systemd
spec:
runtimeClassName: nvidia
containers:
- name: inference
2. Lỗi "failed to create executor" Với Multiple GPUs
# Nguyên nhân: TensorFlow/PyTorch không detect đúng GPU count
Giải pháp: Explicitly set CUDA_VISIBLE_DEVICES trong container
env:
- name: CUDA_VISIBLE_DEVICES
value: "0,1" # Chỉ định 2 GPU cụ thể
- name: CUDA_DEVICE_ORDER
value: "PCI_BUS_ID" # Đảm bảo consistent ordering
Kiểm tra trong container
command: ["/bin/bash", "-c"]
args:
- nvidia-smi && python -c "import torch; print(torch.cuda.device_count())"
3. Lỗi "Scheduling Failed - Insufficient nvidia.com/gpu"
# Nguyên nhân: Node không có GPU available hoặc device plugin chưa chạy
Kiểm tra: kubectl get nodes -o jsonpath='{.items[*].status.capacity.nvidia\.com/gpu}'
Output phải hiển thị số GPU
Fix: Restart device plugin DaemonSet
kubectl rollout restart daemonset nvidia-device-plugin-daemonset -n kube-system
kubectl rollout status daemonset nvidia-device-plugin-daemonset -n kube-system
Verify device plugin pod đang chạy
kubectl get pods -n kube-system -l name=nvidia-device-plugin
4. Lỗi "401 Unauthorized" Khi Gọi HolySheep API
# Nguyên nhân: API key sai hoặc chưa set đúng format
Kiểm tra:
1. Key có prefix "sk-" không?
2. Key có bị trùng khoảng trắng không?
Fix: Tạo secret mới và mount vào pod
kubectl create secret generic holysheep-api-key \
--from-literal=api-key='YOUR_HOLYSHEEP_API_KEY' \
--namespace=production
Mount vào container
env:
- name: HOLYSHEEP_API_KEY
valueFrom:
secretKeyRef:
name: holysheep-api-key
key: api-key
base_url phải là api.holysheep.ai/v1 (KHÔNG phải api.openai.com)
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
5. Lỗi "CrashLoopBackOff" Sau Khi Upgrade NVIDIA Driver
# Nguyên nhân: Driver version không tương thích với CUDA runtime version trong container
Kiểm tra:
Node driver: nvidia-smi
Container CUDA: nvcc --version
Fix: Update container image với CUDA version matching driver
Nếu node có driver 535.x, container phải dùng CUDA 12.x
containers:
- name: inference
image: nvidia/cuda:12.2.0-runtime-ubuntu22.04
# Thay vì image cũ dùng CUDA 11.x
Verify compatibility
kubectl exec -it <pod-name> -- nvidia-smi
Kết Luận
Qua 3 năm vận hành GPU cluster tại HolySheep AI, tôi rút ra: GPU scheduling không chỉ là Kubernetes — đó là cả một hệ sinh thái từ driver, CUDA version, batch size tuning, đến cost optimization. Đặc biệt với inference, việc kết hợp local GPU cho real-time và HolySheep API cho batch giúp tiết kiệm đến 85% chi phí với tỷ giá ¥1=$1.
Nếu bạn đang xây dựng inference service, hãy bắt đầu từ resource limits đúng cách, sau đó mở rộng với autoscaling và hybrid architecture.
👉 Đăng ký HolySheep AI — nhận tín dụng miễn phí khi đăng ký