GPU 是数据中心里最昂贵的资源之一,每一张卡闲置都在烧钱,每一张卡过载都在丢任务。容量规划的本质,是在"算力供给"与"业务需求"之间找到那个最优平衡点——既不让用户排队等到失去耐心,也不让机房里堆满吃灰的 A100。本篇从利用率监控体系出发,系统讲解扩容评估模型、规模计算公式、方案制定、实施流程、缩容评估、成本分析与自动化实践,帮你把"要不要买卡、买多少卡、什么时候买"这件事变成可量化、可追溯的工程决策。
容量规划(Capacity Planning)是 GPU 集群运维中承上启下的核心环节。它向上对接业务团队的算力需求,向下指导硬件采购与机房建设,横向串联监控、调度、成本三大系统。没有容量规划的集群,要么在业务高峰时捉襟见肘,要么在低谷期浪费数百万的硬件折旧。
当前集群有多少卡?分布在哪些节点?显存、算力、网络带宽的总量与可用量各是多少?这是规划的基线数据。
这些卡实际被用了多少?是满载、半载还是空载?利用率在时间轴上如何分布?哪些卡是"伪繁忙"(显存占满但算力为零)?
什么时候应该扩容?是利用率连续 N 天超过阈值就扩,还是任务排队时间超过 SLA 就扩?触发条件必须量化、可告警。
扩多少?不是拍脑袋说"再加一个机柜",而是基于需求预测、利用率目标、碎片率、冗余系数综合计算得出。
扩容的 ROI 是多少?自建 vs 云上?采购 vs 租赁?每增加一张卡的边际收益能否覆盖其 TCO?这是最终决策的约束条件。
容量规划不是一次性活动,而是一个持续运转的闭环。不同周期对应不同的决策粒度:
| 周期 | 频率 | 核心动作 | 决策粒度 | 输出物 |
|---|---|---|---|---|
| 实时监控 | 每 30s | 采集利用率、队列长度 | 单卡 / 单节点 | 告警事件 |
| 日度巡检 | 每日 1 次 | 汇总当日利用率分布 | 集群级 | 日报邮件 |
| 周度分析 | 每周 1 次 | 趋势分析、空闲卡排查 | 队列 / 项目级 | 周报 + 建议 |
| 月度评估 | 每月 1 次 | 扩容 / 缩容评估 | 集群级 | 评估报告 |
| 季度规划 | 每季 1 次 | 硬件采购、预算编制 | 数据中心级 | 采购计划书 |
| 年度战略 | 每年 1 次 | 架构演进、技术路线 | 组织级 | 战略规划文档 |
容量规划的核心原则:数据驱动、量化决策、提前预判、留有余量。永远不要在业务已经崩了的时候才开始规划扩容——那时候从下单到上线至少 8-12 周,来不及了。
容量规划的一切决策都建立在利用率数据之上。数据不准,规划就是空中楼阁。本节从 DCGM 指标体系出发,构建一套覆盖采集、分布、趋势、告警、空闲检测的完整监控链路。
NVIDIA DCGM(Data Center GPU Management)提供了 GPU 运维所需的全部基础指标。容量规划最关心以下几类:
| 指标字段 | 含义 | 单位 | 规划用途 |
|---|---|---|---|
DCGM_FI_DEV_GPU_UTIL | GPU 计算利用率 | % | 核心:判断是否过载 / 空闲 |
DCGM_FI_DEV_MEM_COPY_UTIL | 显存带宽利用率 | % | 判断是否访存瓶颈 |
DCGM_FI_DEV_FB_USED | 已用显存 | MB | 判断显存是否即将 OOM |
DCGM_FI_DEV_FB_FREE | 剩余显存 | MB | 调度可用显存 |
DCGM_FI_DEV_SM_CLOCK | SM 时钟频率 | MHz | 判断是否降频(热限) |
DCGM_FI_DEV_TEMP_CURRENT | 当前温度 | °C | 散热容量评估 |
DCGM_FI_DEV_POWER_USAGE | 功耗 | W | 电力容量评估 |
DCGM_FI_PROF_PIPE_TENSOR_ACTIVE | Tensor Core 活跃度 | ratio | 真实计算强度(profiling 级) |
# Helm values: dcgm-exporter
# 启用 profiling 指标(需要 --set argument.nvidiaDriverCapabilities=compute,utility)
arguments:
- "-f"
- "/etc/dcgm-exporter/dcp-metrics-included.csv"
# 采集间隔 30 秒,足够捕捉趋势又不产生过多存储压力
env:
- name: DCGM_EXPORTER_INTERVAL
value: "30000" # 毫秒
# 关键:开启 profiling metrics
- name: DCGM_EXPORTER_PROFILING_METRICS
value: "true"
serviceMonitor:
enabled: true
interval: 30s
scrapeTimeout: 10s
# 1. 集群整体平均 GPU 利用率(最近 5 分钟)
avg(
rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m])
)
# 2. 按节点分组,找出利用率最低的 10 个节点
topk(10,
avg by (node) (
rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m])
)
)
# 3. 利用率超过 90% 的 GPU 数量(过载检测)
count(
rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m]) > 90
)
# 4. 利用率低于 5% 且持续 1 小时的 GPU(空闲检测)
count_over_time(
(rate(DCGM_FI_DEV_GPU_UTIL[5m]) < 5)[1h:]
)
# 5. Tensor Core 真实活跃度均值(区分"伪繁忙")
avg by (gpu) (
DCGM_FI_PROF_PIPE_TENSOR_ACTIVE{job="dcgm-exporter"}
)
单看"平均利用率 72%"是不够的。同样 72% 的均值,可能是所有卡均匀 70-75%(健康),也可能是一半卡 100%、一半卡 40%(严重不均衡)。必须看分布。
#!/usr/bin/env python3
"""从 Prometheus 拉取利用率数据,生成分桶直方图"""
import requests
import numpy as np
from collections import Counter
PROM = "http://prometheus:9090"
def fetch_gpu_util():
"""拉取所有 GPU 当前利用率"""
query = 'rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m])'
resp = requests.get(f"{PROM}/api/v1/query",
params={"query": query}).json()
vals = []
for item in resp["data"]["result"]:
vals.append(float(item["value"][1]))
return np.array(vals)
def distribution(util):
"""分桶统计:0-10, 10-20, ..., 90-100"""
bins = np.arange(0, 110, 10)
hist, _ = np.histogram(util, bins=bins)
total = len(util)
print(f"{'区间':>12} {'数量':>6} {'占比':>8} {'柱状图'}")
print("-" * 70)
for i, count in enumerate(hist):
pct = count / total * 100
bar = "█" * int(pct / 2)
print(f"{bins[i]:>3}-{bins[i+1]:>3}% {count:>6} {pct:>7.1f}% {bar}")
print(f"\n均值: {util.mean():.1f}% 中位数: {np.median(util):.1f}% "
f"P90: {np.percentile(util, 90):.1f}% P99: {np.percentile(util, 99):.1f}%")
if __name__ == "__main__":
util = fetch_gpu_util()
print(f"采集到 {len(util)} 张 GPU 的利用率数据\n")
distribution(util)
容量规划更关心趋势而非瞬时值。一条缓慢上升的利用率曲线,比一次突然的峰值更能说明问题。
#!/usr/bin/env python3
"""周度利用率趋势分析 + 线性预测"""
import requests
import numpy as np
from datetime import datetime, timedelta
PROM = "http://prometheus:9090"
def fetch_daily_avg(days=90):
"""拉取过去 N 天的日均利用率"""
end = datetime.now()
results = []
for i in range(days):
day = end - timedelta(days=i)
start_ts = int(day.replace(hour=0, minute=0).timestamp())
end_ts = int(day.replace(hour=23, minute=59).timestamp())
query = 'avg(rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m]))'
resp = requests.get(f"{PROM}/api/v1/query_range", params={
"query": query,
"start": start_ts, "end": end_ts, "step": "3600s"
}).json()
vals = [float(r[1]) for r in resp["data"]["result"][0]["values"]]
results.append((day.strftime("%m-%d"), np.mean(vals)))
return list(reversed(results))
def trend_predict(data, predict_days=30):
"""线性回归预测未来 N 天的利用率"""
x = np.arange(len(data))
y = np.array([d[1] for d in data])
# 最小二乘拟合
slope, intercept = np.polyfit(x, y, 1)
print(f"趋势斜率: {slope:.4f}%/天 截距: {intercept:.2f}%")
print(f"当前利用率: {y[-1]:.1f}%")
# 预测
for d in range(1, predict_days + 1):
pred = slope * (len(data) + d - 1) + intercept
flag = " ← 超过 85% 阈值" if pred > 85 else ""
if d % 7 == 0: # 每周打印一次
print(f" +{d:3d}天: 预测 {pred:.1f}%{flag}")
# 计算何时到达 85%
if slope > 0:
days_to_threshold = int((85 - intercept) / slope - len(data))
print(f"\n按当前趋势,预计 {days_to_threshold} 天后达到 85% 扩容阈值")
return slope, intercept
if __name__ == "__main__":
data = fetch_daily_avg(90)
print(f"过去 90 天日均利用率趋势:\n")
trend_predict(data)
groups:
- name: gpu_capacity_alerts
rules:
# 1. 集群平均利用率连续 3 天超过 85%
- alert: GpuClusterUtilHigh
expr: |
avg_over_time(
avg(rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m]))[3d:1h]
) > 85
for: 6h
labels:
severity: warning
team: gpu-ops
annotations:
summary: "集群平均 GPU 利用率连续3天超过 85%"
description: "当前值 {{ $value | humanize }}%,建议启动扩容评估"
# 2. 单卡利用率持续 100%(可能卡死或独占)
- alert: GpuSingleCardSaturated
expr: |
rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m]) >= 99
for: 30m
labels:
severity: info
annotations:
summary: "GPU {{ $labels.gpu }} on {{ $labels.node }} 持续满载 30min"
# 3. GPU 空闲超过 2 小时(浪费检测)
- alert: GpuIdleWaste
expr: |
max_over_time(
rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m])[2h:]
) < 5
for: 10m
labels:
severity: info
team: gpu-ops
annotations:
summary: "GPU {{ $labels.gpu }} on {{ $labels.node }} 空闲超 2h"
description: "检查是否有僵尸进程或可回收的空闲资源"
# 4. 任务排队深度告警
- alert: GpuQueueDepthHigh
expr: gpu_scheduler_queue_depth > 50
for: 15m
labels:
severity: warning
annotations:
summary: "调度队列深度 {{ $value }},排队严重"
"空闲"的 GPU 不一定真的空闲——可能是进程挂了但没释放显存,也可能是用户起了个 Jupyter 但没跑任何东西。空闲检测要区分"真空闲"和"伪空闲"。
#!/bin/bash
# gpu_idle_detect.sh — 检测空闲 GPU 并区分真/伪空闲
# 用法: gpu_idle_detect.sh [idle_threshold%] [duration_min]
THRESH=${1:-5} # 利用率阈值,默认 5%
DURATION=${2:-120} # 持续时长(分钟),默认 120
echo "=== GPU 空闲检测 (阈值 ${THRESH}%, 持续 ${DURATION}min) ==="
echo "时间: $(date)"
echo
# 获取所有 GPU 节点
NODES=$(kubectl get nodes -l node-type=gpu -o jsonpath='{.items[*].metadata.name}')
for node in $NODES; do
# 在节点上执行检测
kubectl debug node/$node -it --image=nvidia/cuda:12.2-base -- bash -c "
nvidia-smi --query-gpu=index,utilization.gpu,memory.used,memory.total \
--format=csv,noheader,nounits | while IFS=',' read -r idx util mem_used mem_total; do
idx=\$(echo \$idx | xargs)
util=\$(echo \$util | xargs)
mem_used=\$(echo \$mem_used | xargs)
mem_total=\$(echo \$mem_total | xargs)
if [ \$util -lt ${THRESH} ]; then
if [ \$mem_used -gt 100 ]; then
# 显存占用但算力为零 → 伪空闲
echo \" GPU \$idx: 伪空闲 (util=\${util}%, mem=\${mem_used}/\${mem_total}MB)\"
# 列出占用该 GPU 的进程
fuser -v /dev/nvidia\${idx} 2>/dev/null | head -5
else
# 显存也几乎为空 → 真空闲
echo \" GPU \$idx: 真空闲 (util=\${util}%, mem=\${mem_used}MB)\"
fi
fi
done
" 2>/dev/null
done
有了数据,接下来是分析。利用率分析必须多维度交叉,单一维度的数字往往具有误导性。
GPU 利用率在时间轴上通常呈现明显的周期性:工作日 vs 周末、白天 vs 夜间、月初 vs 月末。理解这些周期是容量规划的基础。
#!/usr/bin/env python3
"""时间维度利用率分析:按小时/星期/月份拆解"""
import requests
import numpy as np
from datetime import datetime
PROM = "http://prometheus:9090"
def hourly_pattern():
"""分析一天 24 小时的利用率模式"""
# 取过去 30 天,按小时聚合
query = 'avg by (hour) (avg_over_time(rate(DCGM_FI_DEV_GPU_UTIL[5m])[1h]))'
# 使用 record rule 预聚合更高效,这里简化演示
resp = requests.get(f"{PROM}/api/v1/query_range", params={
"query": 'avg(rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter"}[5m]))',
"start": int((datetime.now().timestamp()) - 30*86400),
"end": int(datetime.now().timestamp()),
"step": "3600s"
}).json()
hourly = [[] for _ in range(24)]
for ts, val in resp["data"]["result"][0]["values"]:
hour = datetime.fromtimestamp(int(ts)).hour
hourly[hour].append(float(val))
print("小时 平均利用率 峰值 跷谷 模式")
print("-" * 55)
for h in range(24):
if hourly[h]:
avg = np.mean(hourly[h])
peak = np.max(hourly[h])
valley = np.min(hourly[h])
mode = "高峰" if avg > 75 else ("低谷" if avg < 40 else "平稳")
bar = "█" * int(avg / 3)
print(f" {h:02d}h {avg:5.1f}% {peak:5.1f}% {valley:5.1f}% {mode:4s} {bar}")
hourly_pattern()
空间维度指 GPU 在集群中的物理 / 逻辑分布。不同机柜、不同交换机域、不同节点型号的利用率可能差异巨大。
| 分组维度 | 分析目的 | 典型发现 |
|---|---|---|
| 按机柜 | 发现散热 / 电力热点 | 某机柜因空调故障,GPU 降频导致利用率偏低 |
| 按交换机域 | 发现网络拓扑瓶颈 | 跨交换机 NCCL 通信慢,分布式任务效率低 |
| 按 GPU 型号 | 对比不同型号的性价比 | L40S 利用率 80% 但任务吞吐量仅 A100 的 60% |
| 按节点批次 | 发现硬件老化差异 | 旧批次节点故障率高,有效利用率打折 |
| 按 NUMA 亲和 | 发现 CPU-GPU 拓扑问题 | 跨 NUMA 访问导致 PCIe 带宽减半 |
#!/usr/bin/env python3
"""按用户和团队维度聚合 GPU 使用情况"""
import requests
from collections import defaultdict
PROM = "http://prometheus:9090"
def user_utilization():
"""从调度器标签聚合每个用户的 GPU 使用量与利用率"""
# 假设 dcgm-exporter 带有 user/team 标签(通过 pod 映射注入)
query = '''
sum by (user, team) (
rate(DCGM_FI_DEV_GPU_UTIL{job="dcgm-exporter", user!=""}[24h])
)
'''
resp = requests.get(f"{PROM}/api/v1/query", params={"query": query}).json()
users = []
for item in resp["data"]["result"]:
user = item["metric"]["user"]
team = item["metric"]["team"]
util_sum = float(item["value"][1])
users.append((user, team, util_sum))
# 按利用率总和排序
users.sort(key=lambda x: x[2], reverse=True)
print(f"{'用户':>16} {'团队':>12} {'24h利用率总和':>14} {'估算GPU占用'}")
print("-" * 60)
for user, team, util_sum in users[:20]:
# 利用率总和 / 100 ≈ 占用的 GPU 数量
gpu_count = util_sum / 100
print(f"{user:>16} {team:>12} {util_sum:>13.1f}% {gpu_count:>10.1f} 卡")
# 团队汇总
team_summary = defaultdict(float)
for _, team, util_sum in users:
team_summary[team] += util_sum
print(f"\n--- 团队汇总 ---")
for team, total in sorted(team_summary.items(), key=lambda x: -x[1]):
print(f" {team:12s}: {total:.1f}% ({total/100:.1f} 卡)")
user_utilization()
不同任务类型对 GPU 的利用模式截然不同。训练任务通常长时间满载,推理任务可能波动剧烈,数据处理任务可能显存重但算力轻。
#!/usr/bin/env python3
"""按任务类型分析 GPU 利用模式"""
import requests
import numpy as np
PROM = "http://prometheus:9090"
def task_type_analysis():
"""分析不同任务类型的 GPU 利用特征"""
task_types = ["training", "inference", "finetune", "data_proc", "eval"]
print(f"{'任务类型':>12} {'平均利用率':>10} {'峰值':>8} {'标准差':>8} {'平均时长':>10} {'特征'}")
print("-" * 75)
for tt in task_types:
query = f'''
label_replace(
rate(DCGM_FI_DEV_GPU_UTIL{{job="dcgm-exporter", task_type="{tt}"}}[5m]),
"task_type", "{tt}", "task_type", ".*"
)
'''
resp = requests.get(f"{PROM}/api/v1/query", params={"query": query}).json()
vals = [float(r["value"][1]) for r in resp["data"]["result"]]
if not vals:
continue
arr = np.array(vals)
avg, peak, std = arr.mean(), arr.max(), arr.std()
# 判断特征
if avg > 85 and std < 10:
feature = "持续满载(训练型)"
elif avg > 60 and std > 25:
feature = "波动剧烈(推理型)"
elif avg < 30 and std < 15:
feature = "算力轻载(数据型)"
else:
feature = "混合模式"
print(f"{tt:>12} {avg:>9.1f}% {peak:>7.1f}% {std:>7.1f}% {'2.5h':>10} {feature}")
task_type_analysis()
一份合格的月度利用率报告应包含:(1) 集群总览(卡数、平均利用率、峰值时段);(2) 时间维度趋势图与预测;(3) 空间维度热力图(按机柜 / 交换机域);(4) 用户 / 团队排行;(5) 任务类型分布;(6) 空闲卡清单与原因;(7) 异常事件回顾;(8) 扩容 / 缩容建议。
扩容不是"利用率高就买卡"这么简单。一个完整的扩容评估模型需要综合考虑需求预测、利用率趋势、排队时间、任务完成时间、SLA 要求等多个因子,最终输出一个明确的"是否扩容、扩多少、何时到货"的决策。
需求预测是扩容评估的起点。需要从业务方获取未来 N 个月的算力需求预估,结合历史增长趋势进行修正。
#!/usr/bin/env python3
"""GPU 算力需求预测"""
import numpy as np
from datetime import datetime, timedelta
class DemandForecaster:
def __init__(self, historical_gpu_hours):
"""historical_gpu_hours: 过去 N 月每月消耗的 GPU·小时数"""
self.history = np.array(historical_gpu_hours)
def linear_forecast(self, months_ahead=3):
"""线性增长预测"""
x = np.arange(len(self.history))
slope, intercept = np.polyfit(x, self.history, 1)
future = [slope * (len(self.history) + i) + intercept
for i in range(months_ahead)]
return np.array(future), slope
def seasonal_forecast(self, months_ahead=3):
"""带季节性的预测(简单移动平均 + 趋势)"""
if len(self.history) < 12:
return self.linear_forecast(months_ahead)
# 12 个月季节性
seasonal = self.history[-12:] / np.mean(self.history[-12:])
trend = self.linear_forecast(12)[0]
future = []
for i in range(months_ahead):
base = trend[len(self.history) + i] if i < len(trend) else trend[-1]
season_factor = seasonal[i % 12]
future.append(base * season_factor)
return np.array(future), 0
def business_adjusted(self, biz_growth_rate, months_ahead=3):
"""结合业务方提供的增长率修正"""
base, slope = self.linear_forecast(months_ahead)
# 业务方说用户数将增长 30%,但算力需求通常亚线性增长
# 经验系数:算力增长 = 用户增长 ^ 0.8
adjusted = base * (1 + biz_growth_rate) ** 0.8
return adjusted
# 示例:过去 6 个月的 GPU·小时消耗
forecaster = DemandForecaster([
185000, # 5月
210000, # 6月
245000, # 7月
268000, # 8月
302000, # 9月
335000, # 10月
])
linear_pred, slope = forecaster.linear_forecast(3)
print(f"历史月均增长率: {slope:.0f} GPU·h/月")
print(f"线性预测未来3月: {linear_pred.astype(int)}")
biz_pred = forecaster.business_adjusted(0.30, 3)
print(f"业务修正(+30%用户): {biz_pred.astype(int)}")
扩容触发条件是多因子组合判定,单一条件不构成扩容充分理由:
| 触发条件 | 阈值 | 持续时长 | 权重 | 说明 |
|---|---|---|---|---|
| 集群平均利用率 | > 85% | 连续 14 天 | 0.30 | 最核心指标,但需排除异常任务干扰 |
| P95 利用率 | > 95% | 连续 7 天 | 0.20 | 反映高峰期压力 |
| 任务排队时间中位数 | > 30 min | 连续 7 天 | 0.20 | 用户体感直接指标 |
| SLA 违约率 | > 2% | 月度 | 0.15 | 任务未在承诺时间内完成 |
| 需求预测增长率 | > 15%/月 | 趋势确认 | 0.10 | 前瞻性指标 |
| 碎片率 | > 30% | 持续 | 0.05 | 调度碎片导致有效容量缩水 |
#!/usr/bin/env python3
"""扩容触发条件综合判定"""
from dataclasses import dataclass
@dataclass
class CapacityMetrics:
avg_util_14d: float # 14天平均利用率 %
p95_util_7d: float # 7天P95利用率 %
queue_median_7d: float # 7天排队中位数 (分钟)
sla_violation_rate: float # 月度SLA违约率 %
demand_growth_rate: float # 需求月增长率 %
fragmentation_rate: float # 碎片率 %
@dataclass
class TriggerCondition:
name: str
threshold: float
weight: float
actual: float
@property
def triggered(self) -> bool:
return self.actual >= self.threshold
@property
def score(self) -> float:
"""归一化得分:实际值/阈值,上限1.5"""
return min(self.actual / self.threshold, 1.5) * self.weight
def evaluate_expansion(m: CapacityMetrics):
conditions = [
TriggerCondition("平均利用率>85%", 85, 0.30, m.avg_util_14d),
TriggerCondition("P95利用率>95%", 95, 0.20, m.p95_util_7d),
TriggerCondition("排队中位数>30min", 30, 0.20, m.queue_median_7d),
TriggerCondition("SLA违约>2%", 2, 0.15, m.sla_violation_rate),
TriggerCondition("需求增长>15%/月", 15, 0.10, m.demand_growth_rate),
TriggerCondition("碎片率>30%", 30, 0.05, m.fragmentation_rate),
]
print("=== 扩容触发条件评估 ===")
print(f"{'条件':>22} {'阈值':>8} {'实际':>8} {'权重':>6} {'触发':>6} {'得分'}")
print("-" * 70)
total_score = 0
triggered_count = 0
for c in conditions:
total_score += c.score
triggered_count += 1 if c.triggered else 0
flag = "✓" if c.triggered else "✗"
print(f"{c.name:>22} {c.threshold:>7.1f} {c.actual:>7.1f} "
f"{c.weight:>5.2f} {flag:>6} {c.score:.3f}")
print(f"\n综合得分: {total_score:.3f} / 1.0")
print(f"触发条件数: {triggered_count} / {len(conditions)}")
# 决策逻辑
if total_score >= 0.75 and triggered_count >= 3:
decision = "强烈建议扩容"
elif total_score >= 0.60 and triggered_count >= 2:
decision = "建议扩容(启动评估流程)"
elif total_score >= 0.45:
decision = "观望(持续监控)"
else:
decision = "无需扩容"
print(f"决策: {decision}")
return decision
# 示例:当前集群指标
metrics = CapacityMetrics(
avg_util_14d=87.2,
p95_util_7d=96.5,
queue_median_7d=42,
sla_violation_rate=3.1,
demand_growth_rate=18,
fragmentation_rate=22,
)
evaluate_expansion(metrics)
决定要扩容之后,下一个问题是"扩多少"。这一步必须用公式说话,不能凭感觉。
最基础的思路:当前 N 张卡,利用率 U,目标利用率 T,需要多少张卡?
# 简单线性:当前负载不变,降低利用率到目标值
# N_new = N_current * (U_current / U_target)
N_current = 128 # 当前 GPU 数量
U_current = 87.2 # 当前平均利用率 %
U_target = 70.0 # 目标利用率 %
N_new = N_current * (U_current / U_target)
N_add = N_new - N_current
print(f"当前: {N_current} 卡, 利用率 {U_current}%")
print(f"目标利用率: {U_target}%")
print(f"需要总量: {N_new:.1f} 卡")
print(f"需新增: {N_add:.1f} 卡 → 向上取整 {int(N_add) + 1} 卡")
# 输出: 需新增 31.6 卡 → 向上取整 32 卡
调度碎片导致有效容量低于标称容量。比如 128 张卡,碎片率 22%,有效容量只有 128 × (1 - 0.22) ≈ 100 张。
必须留出冗余卡应对:节点故障、计划内维护、突发峰值。通常冗余系数 R = 1.10 ~ 1.15。
从下单到上线需要 8-12 周,期间需求还在增长。必须预判这段时间的增量。
N_add = N_current × (U_current / U_target) × (1 + F_frag) × R_redundant × (1 + G_growth)^(T_lead/12) − N_current
其中:N_current = 当前卡数;U_current = 当前利用率;U_target = 目标利用率;F_frag = 碎片率;R_redundant = 冗余系数(1.10-1.15);G_growth = 月增长率;T_lead = 交付周期(月)。
#!/usr/bin/env python3
"""完整扩容规模计算器"""
import math
from dataclasses import dataclass
@dataclass
class ExpansionInput:
n_current: int # 当前 GPU 数量
u_current: float # 当前平均利用率 (%)
u_target: float # 目标利用率 (%)
frag_rate: float # 碎片率 (0-1)
redundancy: float # 冗余系数 (1.0-1.2)
growth_monthly: float # 月增长率 (0-1)
lead_time_months: float # 交付周期 (月)
def calculate_expansion(inp: ExpansionInput):
"""计算扩容规模"""
# Step 1: 基础线性
n_base = inp.n_current * (inp.u_current / inp.u_target)
# Step 2: 碎片修正
n_frag = n_base * (1 + inp.frag_rate)
# Step 3: 冗余修正
n_redundant = n_frag * inp.redundancy
# Step 4: 增长预判
growth_factor = (1 + inp.growth_monthly) ** inp.lead_time_months
n_future = n_redundant * growth_factor
# Step 5: 需新增
n_add = n_future - inp.n_current
# 向上取整到 8 的倍数(一个节点通常 8 卡)
n_add_rounded = math.ceil(n_add / 8) * 8
print("=== 扩容规模计算 ===")
print(f"当前: {inp.n_current} 卡, 利用率 {inp.u_current}%")
print(f"目标利用率: {inp.u_target}%")
print(f"碎片率: {inp.frag_rate*100:.0f}%, 冗余系数: {inp.redundancy}")
print(f"月增长率: {inp.growth_monthly*100:.0f}%, 交付周期: {inp.lead_time_months} 月")
print(f"---")
print(f"Step 1 基础线性: {n_base:.1f} 卡")
print(f"Step 2 碎片修正: {n_frag:.1f} 卡")
print(f"Step 3 冗余修正: {n_redundant:.1f} 卡")
print(f"Step 4 增长预判: {n_future:.1f} 卡 (×{growth_factor:.3f})")
print(f"Step 5 需新增: {n_add:.1f} 卡 → 取整 {n_add_rounded} 卡")
print(f"扩容后总规模: {inp.n_current + n_add_rounded} 卡")
print(f"预估上线后利用率: {inp.u_current * inp.n_current / (inp.n_current + n_add_rounded) / (1+inp.frag_rate):.1f}%")
return n_add_rounded
# 实际案例输入
inp = ExpansionInput(
n_current=128,
u_current=87.2,
u_target=70.0,
frag_rate=0.15,
redundancy=1.10,
growth_monthly=0.05, # 月增 5%
lead_time_months=2.5, # 交付 10 周
)
calculate_expansion(inp)
上述计算结果偏保守(预估上线后利用率仅 47.8%),这是因为增长预判 + 冗余系数叠加放大了需求。实际操作中可以分两批采购:先买 64 卡应急,3 个月后再评估是否需要第二批。这样既缓解当前压力,又避免一次性过度投资。
| 策略 | 首批 | 二批 | 优点 | 缺点 |
|---|---|---|---|---|
| 一次性扩容 | 100% | — | 一步到位,谈判折扣大 | 资金占用大,利用率短期偏低 |
| 分两批 60/40 | 60% | 3-6 月后 40% | 缓解当前压力,保留灵活性 | 两次采购成本略高 |
| 分三批 40/35/25 | 40% | 逐季评估 | 最灵活,资金压力最小 | 管理复杂,可能跟不上增长 |
| 云上过渡 | 自建 50% | 云上弹性 | 即时可用,自建到货后下云 | 云上单价高,迁移有成本 |
确定了扩容规模后,需要制定详细的实施方案。这不是"买卡"一件事,而是涉及硬件、网络、电力、散热、机房、时间、成本七大维度的系统工程。
| 型号 | 显存 | FP16 TFLOPS | 功耗 | NVLink | 适用场景 | 参考单价 |
|---|---|---|---|---|---|---|
| H100 SXM5 | 80GB HBM3 | 989 | 700W | 900 GB/s | 大规模训练 | ~$30k |
| A100 SXM4 80G | 80GB HBM2e | 624 | 400W | 600 GB/s | 训练 / 微调 | ~$15k |
| L40S | 48GB GDDR6 | 362 | 350W | 无 | 推理 / 微调 | ~$8k |
| A10 | 24GB GDDR6 | 125 | 150W | 无 | 轻量推理 | ~$2.5k |
训练集群选 H100/A100(NVLink 互联是分布式训练的刚需);推理集群选 L40S(性价比高、功耗低、不需要 NVLink);混合集群可按比例搭配。切忌用 H100 做推理——杀鸡用牛刀,TCO 算不过来。
64 × H100 集群网络规划
========================
[计算网络 — InfiniBand]
- 8 个节点 × 8 卡/节点 = 64 GPU
- 每节点 8 × 200Gb IB 端口 (1:1 GPU:Port)
- 叶交换机: 8 × NVIDIA QM9700 (64-port 400G NDR)
- 胖树拓扑: 2 层,无阻塞
- 线缆: 64 × DAC (直连铜缆, <3m) + 32 × AOC (有源光缆)
[存储网络 — RoCE/RDMA]
- 2 × 100Gb RoCE 端口/节点
- 连接并行存储 (Lustre / WekaFS)
- 专用 VLAN, PFC + ECN 配置
[管理网络 — Ethernet]
- 2 × 10Gb 管理端口/节点 (IPMI + SSH)
- 带外管理交换机
[总带宽预算]
- 计算: 64 × 200G = 12.8 Tb/s
- 存储: 8 × 2 × 100G = 1.6 Tb/s
- 管理: 8 × 2 × 10G = 160 Gb/s
#!/usr/bin/env python3
"""扩容集群电力容量计算"""
# 单节点功耗估算
gpu_power = 700 # H100 SXM5 TDP (W)
gpu_count_per_node = 8
cpu_power = 350 # 双路 CPU
mem_power = 150 # 1TB DDR5
nic_power = 120 # 8×IB + 2×RoCE
fan_other = 200 # 风扇 + 主板 + 其他
node_power = (gpu_power * gpu_count_per_node +
cpu_power + mem_power + nic_power + fan_other)
print(f"单节点峰值功耗: {node_power} W = {node_power/1000:.1f} kW")
# 机柜规划
nodes_per_rack = 4 # 每柜 4 节点 (受电力和散热限制)
rack_power = node_power * nodes_per_rack
print(f"单柜功耗: {rack_power/1000:.1f} kW")
# 需要的机柜数
total_nodes = 8 # 64 卡 / 8 卡每节点
total_racks = (total_nodes + nodes_per_rack - 1) // nodes_per_rack
total_power = total_racks * rack_power
print(f"总节点数: {total_nodes}")
print(f"总机柜数: {total_racks}")
print(f"集群总功耗: {total_power/1000:.1f} kW")
# PDU 和 UPS 规划
print(f"\n--- 电力规划 ---")
print(f"PDU: 每柜 2× {int(rack_power*1.2/1000)}kW 冗余PDU")
print(f"UPS: 需 {int(total_power*1.3/1000)}kVA UPS 容量 (含30%余量)")
print(f"市电: 需 {int(total_power*1.5/1000)}kW 市电容量 (含冷却开销)")
# 输出:
# 单节点峰值功耗: 6420 W = 6.4 kW
# 单柜功耗: 25.7 kW
# 总节点数: 8, 总机柜数: 2
# 集群总功耗: 51.4 kW
# PDU: 每柜 2× 30kW 冗余PDU
# UPS: 需 67kVA UPS 容量
# 市电: 需 77kW 市电容量
8×H100 单节点 6.4kW,远超传统风冷机柜的 10-15kW/柜上限。必须考虑液冷。
散热方案对比 (64×H100 集群, 总热负载 ~51kW)
================================================
方案A: 风冷 (行级精密空调)
- 每柜热负载: 25.7kW → 超出风冷极限 (15kW/柜)
- 需要: 4× 30kW 行级空调 (N+1冗余)
- 风险: GPU 可能热限降频, 性能损失 10-15%
- 结论: ✗ 不推荐
方案B: 冷板式液冷 + 风冷辅助
- GPU/CPU 冷板液冷, 内存/IO 风冷
- CDU (冷量分配单元): 2× 60kW (N+1)
- 一次侧: 7-12°C 冷冻水 (接机房冷水机组)
- 二次侧: 25-35°C SCD (供液温度)
- 结论: ✓ 推荐, PUE ~1.15
方案C: 浸没式液冷
- 单相浸没, 油温 40-50°C
- 无需风扇, 噪音大幅降低
- 缺点: 运维复杂, 改造成本高
- 结论: ○ 可选, 适合新建机房
| 阶段 | 耗时 | 关键交付物 | 前置依赖 |
|---|---|---|---|
| 需求确认与预算审批 | 1-2 周 | 采购申请单 | 扩容评估报告 |
| 供应商询价与下单 | 2-3 周 | 采购合同 | 预算审批 |
| 硬件生产与交付 | 4-8 周 | 到货验收单 | 采购合同 |
| 机房准备(电力/散热) | 2-4 周(可并行) | 机房验收报告 | 设施方案 |
| 上架与布线 | 1 周 | 物理连接验收 | 到货 + 机房就绪 |
| 系统配置与测试 | 1-2 周 | 测试报告 | 上架完成 |
| 上线与灰度验证 | 1 周 | 上线确认书 | 测试通过 |
| 总计 | 8-14 周 |
从决定扩容到新卡上线承接业务,中间有 8 个关键步骤。每一步都有明确的输入、输出和验收标准。
向 2-3 家 NVIDIA 授权供应商询价,对比价格、交期、售后服务。关键参数:GPU 型号、数量、节点配置(CPU/内存/存储)、网络配件(IB 网卡/线缆/交换机)。输出:采购合同,明确交期和验收标准。注意锁定交期——GPU 供货周期波动大,签合同时务必写明违约条款。
到货后逐箱清点:序列号登记、外观检查、防静电包装完整性。关键:用 nvidia-smi -q 在到货节点上做开箱检测,确认 GPU 型号、显存大小、PCIe 链路速率与订单一致。输出:到货验收单,附每张卡的序列号和基础信息截图。
按机房规划图将节点上架。注意:重设备(GPU 节点通常 40-60kg)需两人操作或使用服务器升降车。上架后确认导轨锁定、滑轨顺畅。液冷节点需同时安装 CDU 管路并做打压测试。输出:上架完成确认,附机柜正面 / 背面照片。
按网络拓扑图布线。IB 线缆按端口映射表逐一连接,每根线缆两端贴标签(来源端口→目标端口)。关键:IB 线缆走线需避免与电力线平行走线,保持 30cm 以上间距。布线完成后用 ibstat 确认所有端口 LinkUp。输出:布线验收报告 + ibnetdiscover 拓扑截图。
批量安装操作系统、NVIDIA 驱动、CUDA Toolkit、NCCL、容器运行时、Kubernetes 组件。使用 Ansible/Terraform 自动化部署,确保所有节点配置一致。关键配置项:GPU 驱动版本、CUDA 版本、IB 驱动参数、NCCL 环境变量、容器运行时(containerd + nvidia-runtime)。输出:配置清单 + Ansible playbook 执行日志。
分三层测试:(1) 单卡测试——nvidia-smi -q、gpu-burn 满载 30 分钟确认无降频/报错;(2) 多卡测试——NCCL all_reduce_perf 测试节点内 8 卡互联带宽;(3) 多节点测试——跨节点 NCCL 测试 + 实际训练任务跑通。输出:测试报告,包含每卡温度曲线、带宽测试结果、异常事件清单。
将新节点加入 Kubernetes 集群,打上正确的标签和污点。调度器开始向新节点分配任务。关键:先打 NoSchedule 污点,手动放行少量测试任务验证端到端流程,确认无误后移除污点正式承接生产流量。输出:节点加入确认 + 调度器状态截图。
上线后持续观察 7 天:利用率是否正常承接、温度是否在安全范围、有无硬件报错(dmesg / NVIDIA 系统日志)、用户任务成功率是否正常。7 天无异常则关闭扩容项目,归档所有文档。输出:上线验证报告,扩容项目关闭。
#!/bin/bash
# gpu_burnin.sh — 新节点 GPU 老化测试
# 用法: gpu_burnin.sh [duration_minutes]
DURATION=${1:-30}
LOG=/var/log/gpu-burnin-$(date +%Y%m%d-%H%M%S).log
echo "=== GPU Burn-in 测试开始 ===" | tee $LOG
echo "时长: ${DURATION} 分钟" | tee -a $LOG
echo "节点: $(hostname)" | tee -a $LOG
echo "GPU 数量: $(nvidia-smi -L | wc -l)" | tee -a $LOG
echo | tee -a $LOG
# 1. 基础信息检查
echo "--- 1. 基础信息 ---" | tee -a $LOG
nvidia-smi --query-gpu=index,name,driver_version,memory.total,pci.link.gen.current \
--format=csv | tee -a $LOG
# 2. 满载压力测试
echo -e "\n--- 2. 满载压力测试 (${DURATION}min) ---" | tee -a $LOG
# 使用 gpu-burn (基于 CUDA 矩阵乘法)
docker run --rm --gpus all \
-v $LOG:/tmp/burn.log \
leela/gpu-burn ${DURATION} 2>&1 | tee -a $LOG
# 3. 温度检查
echo -e "\n--- 3. 测试后温度 ---" | tee -a $LOG
nvidia-smi --query-gpu=index,temperature.gpu,temperature.memory,power.draw,clocks.sm \
--format=csv | tee -a $LOG
# 4. ECC 错误检查
echo -e "\n--- 4. ECC 错误统计 ---" | tee -a $LOG
nvidia-smi --query-gpu=index,ecc.errors.uncorrected.volatile.total \
--format=csv | tee -a $LOG
# 5. NCCL 带宽测试 (节点内)
echo -e "\n--- 5. NCCL all-reduce 带宽 ---" | tee -a $LOG
/usr/local/bin/all_reduce_perf -b 8 -e 128M -f 2 -g 8 2>&1 | tail -5 | tee -a $LOG
echo -e "\n=== Burn-in 测试完成 ===" | tee -a $LOG
echo "日志: $LOG"
扩容是花钱,缩容是省钱。当利用率持续偏低时,及时缩容可以释放资源、降低能耗、减少折旧。但缩容比扩容更危险——稍有不慎就把正在跑的任务杀掉了。
| 条件 | 阈值 | 持续时长 | 说明 |
|---|---|---|---|
| 集群平均利用率 | < 40% | 连续 30 天 | 排除节假日和业务低谷期 |
| 空闲 GPU 占比 | > 30% | 持续 14 天 | 大量卡长期无任务 |
| 任务排队深度 | ≈ 0 | 持续 14 天 | 几乎无排队,供给远大于需求 |
| 需求趋势 | 下降趋势 | 确认 | 业务方确认需求不会反弹 |
| 硬件租约到期 | 临近 | — | 云上实例或租赁设备到期不续 |
(1) 误杀运行中任务:缩容前必须确认目标节点上无活跃任务。(2) 数据丢失:节点本地存储的数据(如模型缓存、checkpoint)必须迁移。(3) 调度域缩小:缩容后剩余集群的碎片率可能上升,大任务无法调度。(4) 需求反弹:缩容后业务突然增长,又要紧急扩容,来回折腾成本更高。
#!/bin/bash
# safe_scale_down.sh — 安全缩容流程
# 用法: safe_scale_down.sh <node_name>
NODE=$1
if [ -z "$NODE" ]; then
echo "用法: safe_scale_down.sh <node_name>"
exit 1
fi
echo "=== 安全缩容流程: $NODE ==="
# Step 1: 检查节点上是否有运行中的 Pod
echo "--- Step 1: 检查运行中的任务 ---"
PODS=$(kubectl get pods --all-namespaces --field-selector spec.nodeName=$NODE \
-o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}')
if [ -n "$PODS" ]; then
echo "⚠️ 节点上有运行中的 Pod: $PODS"
echo " 先执行 cordon + drain 驱逐任务"
kubectl cordon $NODE
kubectl drain $NODE --ignore-daemonsets --delete-emptydir-data --grace-period=300
echo " 等待驱逐完成..."
sleep 30
else
echo "✓ 节点上无运行中的 Pod"
fi
# Step 2: 检查并迁移本地数据
echo "--- Step 2: 检查本地数据 ---"
LOCAL_DATA=$(ssh $NODE "ls /local_storage/models/ 2>/dev/null | wc -l")
if [ "$LOCAL_DATA" -gt 0 ]; then
echo "⚠️ 发现 $LOCAL_DATA 个本地缓存文件,需要迁移"
echo " 迁移到共享存储..."
ssh $NODE "rsync -av /local_storage/models/ /shared_storage/models/"
echo "✓ 数据迁移完成"
else
echo "✓ 无本地数据需要迁移"
fi
# Step 3: GPU 状态最终确认
echo "--- Step 3: GPU 最终状态确认 ---"
ssh $NODE "nvidia-smi --query-gpu=utilization.gpu,memory.used --format=csv,noheader" | \
while read line; do
util=$(echo $line | cut -d',' -f1 | xargs)
mem=$(echo $line | cut -d',' -f2 | xargs)
if [ "$util" -gt 5 ] || [ "$mem" -gt 100 ]; then
echo "⚠️ GPU 仍有活动: util=$util%, mem=${mem}MB"
echo " 终止缩容!"
exit 1
fi
done
echo "✓ 所有 GPU 空闲"
# Step 4: 关机并从集群移除
echo "--- Step 4: 关机并移除 ---"
kubectl delete node $NODE
echo " 节点已从 K8s 集群移除"
ssh $NODE "sudo shutdown -h now"
echo " 节点已关机"
# Step 5: 记录缩容
echo "--- Step 5: 记录 ---"
echo "$(date): 缩容节点 $NODE" >> /var/log/scale-down.log
echo "✓ 缩容完成: $NODE"
缩容下来的 GPU 不是扔掉就行,需要合理处置以回收价值:
容量规划最终要落到钱上。每张 GPU 的 TCO(总拥有成本)是多少?单位算力成本是多少?利用率如何影响成本?扩容的 ROI 能否覆盖投入?自建还是上云?这些问题的答案决定了扩容方案能否获得管理层批准。
#!/usr/bin/env python3
"""GPU 集群 TCO (Total Cost of Ownership) 计算"""
def calculate_tco(params):
"""计算 3 年 TCO"""
# --- 硬件成本 ---
gpu_cost = params["gpu_price"] * params["gpu_count"]
node_cost = params["node_price"] * params["node_count"] # CPU/内存/主板/网卡
network_cost = params["switch_price"] * params["switch_count"] + params["cable_cost"]
rack_cost = params["rack_price"] * params["rack_count"]
capex = gpu_cost + node_cost + network_cost + rack_cost
# --- 运营成本 (3年) ---
years = 3
# 电力: GPU功耗 × 数量 × 利用率折算 × 电价 × 24h × 365天 × 3年
avg_power_kw = (params["gpu_tdp"] * params["gpu_count"] * 0.75) / 1000 # 0.75=平均负载
# 加上冷却开销 (PUE-1)
total_power_kw = avg_power_kw * params["pue"]
electricity_cost = total_power_kw * params["electricity_rate"] * 24 * 365 * years
# 机房分摊 (租金 + 设施折旧)
facility_cost = params["facility_monthly"] * 12 * years
# 人力运维
labor_cost = params["ops_salary"] * params["ops_headcount"] * years
# 软件 (驱动免费, 但可能有集群管理软件许可)
software_cost = params.get("software_annual", 0) * years
opex = electricity_cost + facility_cost + labor_cost + software_cost
tco = capex + opex
print("=== 3年 TCO 计算 ===")
print(f"--- CAPEX (一次性) ---")
print(f" GPU: {gpu_cost:>12,} 元 ({params['gpu_count']}×{params['gpu_price']})")
print(f" 节点: {node_cost:>12,} 元")
print(f" 网络: {network_cost:>12,} 元")
print(f" 机柜: {rack_cost:>12,} 元")
print(f" CAPEX合计: {capex:>12,} 元")
print(f"--- OPEX (3年) ---")
print(f" 电费: {electricity_cost:>12,.0f} 元 ({total_power_kw:.1f}kW × {params['electricity_rate']}元/kWh)")
print(f" 机房: {facility_cost:>12,} 元")
print(f" 人力: {labor_cost:>12,} 元")
print(f" 软件: {software_cost:>12,} 元")
print(f" OPEX合计: {opex:>12,.0f} 元")
print(f"---")
print(f" TCO: {tco:>12,.0f} 元")
print(f" 年均: {tco/years:>12,.0f} 元")
print(f" 单卡年均: {tco/years/params['gpu_count']:>12,.0f} 元")
return tco
# 64×H100 集群参数
params = {
"gpu_count": 64, "gpu_price": 220000, # H100 ~22万元/卡
"node_count": 8, "node_price": 150000, # CPU/内存/主板/网卡
"switch_count": 8, "switch_price": 200000, # IB 交换机
"cable_cost": 200000, # 线缆
"rack_count": 4, "rack_price": 50000,
"gpu_tdp": 700, # W
"pue": 1.25, # 数据中心 PUE
"electricity_rate": 0.8, # 元/kWh
"facility_monthly": 80000, # 机房月租
"ops_salary": 400000, "ops_headcount": 3, # 运维人力
"software_annual": 100000,
}
calculate_tco(params)
单位算力成本 = TCO / (GPU 数量 × 理论算力 × 利用率 × 时间)。利用率越高,单位算力成本越低——这就是为什么容量规划要追求"高但不爆"的利用率。
#!/usr/bin/env python3
"""不同利用率下的单位算力成本"""
tco_3year = 28_000_000 # 上例 TCO
gpu_count = 64
tflops_per_gpu = 989 # H100 FP16
hours_3year = 3 * 365 * 24
print(f"{'利用率':>8} {'有效算力(PetaFLOP·h)':>22} {'单位成本(元/PF·h)':>20}")
print("-" * 55)
for util in [30, 40, 50, 60, 70, 80, 85, 90, 95]:
# 有效算力 (PetaFLOP·h)
effective = gpu_count * tflops_per_gpu * (util/100) * hours_3year / 1e6
# 单位成本
unit_cost = tco_3year / effective
bar = "█" * int(util / 5)
print(f"{util:>7}% {effective:>20.1f} {unit_cost:>18.2f} {bar}")
print(f"\n结论: 利用率从 40% 提升到 80%, 单位成本降低 50%")
| 维度 | 自建 | 云上 (以 AWS p4d 为例) | 建议 |
|---|---|---|---|
| 初始投入 | 高(CAPEX 大) | 零 | 短期用云 |
| 3 年 TCO (64×H100) | ~2800 万 | ~4200 万 | 自建更优 |
| 启动时间 | 8-14 周 | 分钟级 | 云更快 |
| 弹性扩缩 | 差 | 极好 | 云更优 |
| 数据合规 | 完全可控 | 需评估 | 自建更优 |
| 运维负担 | 重 | 轻 | 云更优 |
| 利用率 > 70% 时 | 成本优势显著 | 昂贵 | 自建 |
| 利用率 < 40% 时 | 浪费严重 | 按需付费更省 | 云上 |
基线负载用自建集群覆盖(利用率 > 70%),峰值溢出部分用云上弹性实例承接。这样既享受自建的低单位成本,又利用云的弹性应对突发。关键是做好自建到云的任务调度和镜像同步。
某 AI 研究团队拥有一个 128×A100 集群,用于大模型训练和微调。2026 年 8-10 月,集群平均利用率连续 3 个月超过 85%,任务排队严重,SLA 违约率攀升。运维团队启动扩容评估流程。
运维团队运行扩容评估引擎(4.3 节),综合得分 1.181,5/6 条件触发,决策为"强烈建议扩容"。
# 案例参数
N_current = 128
U_current = 87.2
U_target = 70.0
frag_rate = 0.15
redundancy = 1.10
growth_monthly = 0.05
lead_time = 2.5 # 10 周交付
# 完整公式
import math
n_base = N_current * (U_current / U_target) # 159.3
n_frag = n_base * (1 + frag_rate) # 183.2
n_redundant = n_frag * redundancy # 201.5
n_future = n_redundant * (1 + growth_monthly) ** lead_time # 227.5
n_add = n_future - N_current # 99.5
# 分批策略: 首批 60%
n_batch1 = math.ceil(n_add * 0.6 / 8) * 8 # 64 卡
n_batch2 = math.ceil(n_add * 0.4 / 8) * 8 # 40 卡 → 取 40
print(f"计算需新增: {n_add:.1f} 卡")
print(f"分批策略:")
print(f" 首批: {n_batch1} 卡 (8 节点 × 8 卡)")
print(f" 二批: {n_batch2} 卡 (5 节点 × 8 卡)")
print(f" 合计: {n_batch1 + n_batch2} 卡")
print(f" 扩容后总规模: {N_current + n_batch1 + n_batch2} 卡")
# 首批上线后预估利用率
n_after_b1 = N_current + n_batch1
u_after_b1 = U_current * N_current / n_after_b1 / (1 + frag_rate)
print(f"\n首批上线后预估利用率: {u_after_b1:.1f}%")
| 项目 | 首批方案 | 预算 |
|---|---|---|
| GPU | 64 × A100 80G SXM4 | 960 万 |
| 节点 | 8 × 8卡节点 (2×AMD EPYC, 1TB DDR5) | 120 万 |
| 网络 | 4 × IB 交换机 + 线缆 | 100 万 |
| 电力改造 | 2 个机柜液冷改造 | 80 万 |
| 总计 | 1260 万 |
扩容实施时间线 (首批 64 卡)
============================
W1 (10/28): 扩容评估报告提交, 管理层审批通过
W2 (11/04): 供应商询价完成, 采购合同签订 (交期 8 周)
W2 (11/04): 机房液冷改造启动 (并行)
W6 (12/02): 机房改造完成, 电力/散热验收通过
W10 (12/30): 硬件到货, 开箱验收到货
W11 (01/06): 上架 + 布线完成
W12 (01/13): 系统配置完成 (Ansible 批量部署)
W13 (01/20): Burn-in 测试通过 (3 层测试全部绿灯)
W14 (01/27): 灰度上线, 放行 10% 任务
W15 (02/03): 全量上线, 正式承接生产流量
W16 (02/10): 上线后验证完成, 利用率降至 68%
关键里程碑:
✓ 12/30 到货验收
✓ 01/20 测试通过
✓ 02/03 全量上线
✓ 02/10 验证关闭
首批 64 卡上线后,集群平均利用率从 87.2% 降至 70%,排队时间从 42 分钟降至 8 分钟,SLA 违约率从 3.1% 降至 0.3%。二批 40 卡暂缓——当前容量已满足需求,待 3 个月后重新评估。
手动做容量规划费时费力且容易遗漏。把采集、分析、告警、建议、报表全部自动化,运维团队只需每周看一眼报告、每月做一次决策。
groups:
- name: gpu_capacity_recording
interval: 1h
rules:
# 集群级每小时利用率
- record: gpu:cluster:util_hourly
expr: avg(rate(DCGM_FI_DEV_GPU_UTIL[5m]))
# 按节点每小时利用率
- record: gpu:node:util_hourly
expr: avg by (node) (rate(DCGM_FI_DEV_GPU_UTIL[5m]))
# 按用户每小时利用率总和
- record: gpu:user:util_hourly
expr: sum by (user, team) (rate(DCGM_FI_DEV_GPU_UTIL[5m]))
# 空闲 GPU 计数 (每小时)
- record: gpu:idle:count_hourly
expr: count(rate(DCGM_FI_DEV_GPU_UTIL[5m]) < 5)
# 过载 GPU 计数
- record: gpu:overload:count_hourly
expr: count(rate(DCGM_FI_DEV_GPU_UTIL[5m]) > 90)
# 日均利用率 (每天聚合)
- record: gpu:cluster:util_daily
expr: avg_over_time(gpu:cluster:util_hourly[24h])
#!/usr/bin/env python3
"""自动化容量规划分析引擎 — 每日定时运行"""
import requests
import numpy as np
import json
from datetime import datetime, timedelta
PROM = "http://prometheus:9090"
REPORT_DIR = "/var/reports/capacity"
class CapacityAnalyzer:
def __init__(self):
self.report = {
"date": datetime.now().strftime("%Y-%m-%d"),
"sections": {}
}
def query(self, q):
resp = requests.get(f"{PROM}/api/v1/query", params={"query": q}).json()
if resp["data"]["result"]:
return float(resp["data"]["result"][0]["value"][1])
return 0.0
def query_range(self, q, days=30):
end = datetime.now()
resp = requests.get(f"{PROM}/api/v1/query_range", params={
"query": q, "start": int((end - timedelta(days=days)).timestamp()),
"end": int(end.timestamp()), "step": "86400s"
}).json()
if resp["data"]["result"]:
return [float(v[1]) for v in resp["data"]["result"][0]["values"]]
return []
def analyze_utilization(self):
"""利用率分析"""
avg_14d = self.query('avg_over_time(gpu:cluster:util_daily[14d])')
p95_7d = self.query('quantile_over_time(0.95, gpu:cluster:util_hourly[7d])')
idle_count = self.query('avg_over_time(gpu:idle:count_hourly[24h])')
overload_count = self.query('avg_over_time(gpu:overload:count_hourly[24h])')
self.report["sections"]["utilization"] = {
"avg_14d": round(avg_14d, 1),
"p95_7d": round(p95_7d, 1),
"idle_gpus": int(idle_count),
"overload_gpus": int(overload_count),
}
def analyze_trend(self):
"""趋势分析"""
daily = self.query_range('gpu:cluster:util_daily', 90)
if len(daily) > 7:
x = np.arange(len(daily))
slope, _ = np.polyfit(x, daily, 1)
days_to_85 = int((85 - daily[-1]) / slope) if slope > 0 else 999
self.report["sections"]["trend"] = {
"slope_per_day": round(slope, 3),
"current": round(daily[-1], 1),
"days_to_85": days_to_85,
}
def generate_recommendation(self):
"""自动生成建议"""
util = self.report["sections"].get("utilization", {})
trend = self.report["sections"].get("trend", {})
recs = []
if util.get("avg_14d", 0) > 85:
recs.append({
"level": "warning",
"action": "启动扩容评估",
"reason": f"14天平均利用率 {util['avg_14d']}% 超过 85% 阈值"
})
elif util.get("avg_14d", 0) < 40:
recs.append({
"level": "info",
"action": "考虑缩容评估",
"reason": f"14天平均利用率 {util['avg_14d']}% 低于 40%"
})
if util.get("idle_gpus", 0) > 10:
recs.append({
"level": "info",
"action": "排查空闲 GPU",
"reason": f"{util['idle_gpus']} 张 GPU 空闲,检查僵尸进程"
})
if trend.get("days_to_85", 999) < 30:
recs.append({
"level": "warning",
"action": "预启动扩容规划",
"reason": f"按当前趋势 {trend['days_to_85']} 天后达到 85%"
})
self.report["sections"]["recommendations"] = recs
def save_report(self):
"""保存报告"""
filename = f"{REPORT_DIR}/{self.report['date']}.json"
with open(filename, 'w') as f:
json.dump(self.report, f, indent=2, ensure_ascii=False)
print(f"报告已保存: {filename}")
print(json.dumps(self.report, indent=2, ensure_ascii=False))
if __name__ == "__main__":
analyzer = CapacityAnalyzer()
analyzer.analyze_utilization()
analyzer.analyze_trend()
analyzer.generate_recommendation()
analyzer.save_report()
# /etc/cron.d/gpu-capacity-planning
# 每小时: 预聚合指标 (由 Prometheus recording rule 自动完成, 无需 cron)
# 每日 08:00: 生成日报
0 8 * * * gpu-ops /opt/gpu-ops/capacity_daily_report.sh >> /var/log/capacity-daily.log 2>&1
# 每周一 09:00: 生成周报 + 发送邮件
0 9 * * 1 gpu-ops /opt/gpu-ops/capacity_weekly_report.sh --send-email >> /var/log/capacity-weekly.log 2>&1
# 每月 1 号 10:00: 扩容评估 + 生成月报
0 10 1 * * gpu-ops /opt/gpu-ops/expansion_evaluation.sh --full-report --notify=slack:#gpu-ops >> /var/log/expansion-eval.log 2>&1
# 每 15 分钟: 检查扩容触发条件, 触发则发告警
*/15 * * * * gpu-ops /opt/gpu-ops/check_expansion_triggers.sh >> /var/log/trigger-check.log 2>&1
| 项目 | 公式 / 阈值 | 说明 |
|---|---|---|
| 简单线性扩容 | N_new = N × (U_cur / U_tgt) | 最基础估算,不含碎片/冗余/增长 |
| 完整扩容公式 | N×(U_cur/U_tgt)×(1+F)×R×(1+G)^T − N | F=碎片率, R=冗余系数, G=月增长, T=交付月数 |
| 扩容触发: 利用率 | > 85% 持续 14 天 | 权重 0.30,最核心指标 |
| 扩容触发: P95 | > 95% 持续 7 天 | 权重 0.20 |
| 扩容触发: 排队 | 中位数 > 30min 持续 7 天 | 权重 0.20,用户体感指标 |
| 扩容触发: SLA | 违约率 > 2% | 权重 0.15 |
| 缩容触发: 利用率 | < 40% 持续 30 天 | 排除节假日 |
| 缩容触发: 空闲比 | > 30% 持续 14 天 | 大量卡长期空闲 |
| 目标利用率 | 70% ~ 75% | 兼顾效率和余量 |
| 冗余系数 | 1.10 ~ 1.15 | 应对故障和维护 |
| 交付周期 | 8 ~ 14 周 | 从下单到上线 |
| 单节点功耗 (8×H100) | ~6.4 kW | 需液冷 |
| 单节点功耗 (8×A100) | ~3.7 kW | 风冷可支持 |
| 云 vs 自建临界 | 利用率 50-60% | 高于此值自建更优 |
| PUE 目标 | < 1.20 (液冷) | 数据中心能效指标 |
| 指标 | PromQL | 用途 |
|---|---|---|
| 集群平均利用率 | avg(rate(DCGM_FI_DEV_GPU_UTIL[5m])) | 总览 |
| 节点级利用率 | avg by (node) (rate(DCGM_FI_DEV_GPU_UTIL[5m])) | 空间分布 |
| 空闲 GPU 数 | count(rate(DCGM_FI_DEV_GPU_UTIL[5m]) < 5) | 浪费检测 |
| 过载 GPU 数 | count(rate(DCGM_FI_DEV_GPU_UTIL[5m]) > 90) | 压力检测 |
| 显存使用率 | DCGM_FI_DEV_FB_USED / (DCGM_FI_DEV_FB_USED + DCGM_FI_DEV_FB_FREE) | OOM 预警 |
| Tensor 活跃度 | avg(DCGM_FI_PROF_PIPE_TENSOR_ACTIVE) | 真实计算强度 |
| 日均利用率 | avg_over_time(gpu:cluster:util_hourly[24h]) | 趋势分析 |
| 阶段 | 检查项 | 验收标准 |
|---|---|---|
| 采购 | 合同交期、违约条款 | 交期 ≤ 10 周 |
| 到货 | 序列号、型号、显存核对 | 与订单 100% 一致 |
| 上架 | 导轨锁定、水平度 | 无松动,前后通风无阻挡 |
| 布线 | IB 端口全 LinkUp | ibstat 无 Down 端口 |
| 配置 | 驱动版本、CUDA 版本一致 | 与现有集群版本对齐 |
| 测试 | gpu-burn 30min 无报错 | 无降频、无 ECC 错误 |
| 测试 | NCCL all-reduce 带宽 | ≥ 理论带宽 90% |
| 上线 | 灰度 10% 任务通过 | 成功率 ≥ 99% |
| 验证 | 7 天无硬件告警 | dmesg 无 GPU 相关错误 |