greenai.guide

首页 › 绿色 AI 工程 › 如何对 CPU 与 GPU 推理的能耗进行基准测试

绿色 AI 工程

如何对 CPU 与 GPU 推理的能耗进行基准测试

更新于 · 阅读约需 9 分钟

简而言之

在推理上,CPU 和 GPU 都不是天生更绿色的:GPU 在保持忙碌时每焦耳能完成多得多的工作,但它在等待时也在耗电。请用您自己的模型、提示词和流量对两者进行基准测试:固定工作负载,检查答案质量,在包括空闲在内的多个稳定负载水平下测量能耗,并报告每个成功请求的能耗。决定性的数字是 GPU 额外的空闲功耗得以收回时的流量水平。

要点

  • 在您真实的流量水平下比较每个成功请求的能耗,而不是峰值每秒 token 数。
  • 测量加载了模型时的空闲功耗:在低流量或流量不规律时,它可能在每个请求的能耗中占主导地位。
  • 对于小模型或量化模型、批大小为 1 和稀疏流量,CPU 值得测试;当流量足以进行批处理时,GPU 通常胜出。
  • NVML 在 Volta 及更新的 GPU 上提供能耗计数器,但功率读数是采样值或平均值,一项研究发现 nvidia-smi 在 A100 和 H100 上只对约 25% 的运行时间进行了采样。
  • 每个结果都要说明边界(CPU 封装、DRAM、GPU,还是墙插处的整个节点)、软件版本和设置。

CPU 什么时候能在能耗上胜过 GPU?

当模型较小或经过量化、请求逐个到达或很少到达,而且 CPU 服务器本来就因其他原因在运行时,CPU 每个请求的能耗可能更低。在这些情况下,GPU 大部分时间都在等待,而它的空闲功耗要由它所服务的少数请求来分摊。

原因是机制性的,与品牌无关:

  • 批大小为 1 时加速器利用不足。一次生成一个 token 的文本生成,受内存带宽的限制大于受算力的限制。Fernandez 等人在 NVIDIA A6000、A6000 Ada 和 A100 GPU 上测量 LLM 推理,把解码描述为受内存限制、GPU 利用不足,并发现在短长度和小批次下预填充(prefill)能耗基本持平,因为加速器远未饱和。
  • 空闲功耗不会消失。无论是否有请求在处理,GPU 服务器都要为其加速器、主机处理器、内存和风扇供电。如果流量稀疏,空闲能耗就会占主导地位。
  • 量化对 CPU 也有帮助。ONNX Runtime 的文档介绍了 CPU 上的 8 位整数量化,并预计在带有 VNNI 指令的 x86-64 处理器和带有点积指令的 Arm 处理器上收益更大。它还提醒,没有这类指令的旧硬件运行量化模型可能反而更慢。llama.cpp 的 quantize 工具把模型转换为精度更低的 GGUF 文件,这会缩小模型并可能加快推理,但会损失一些准确性。参见如何量化模型。
  • 小模型放得下。分类、抽取和简短回答模型,以及小语言模型,往往能在 CPU 服务器的内存和延迟预算内运行。在确定硬件规模之前,先试试更小的模型。

这些都不能证明 CPU 在您的场景中会胜出。它们只是告诉您什么时候值得去测试。

GPU 什么时候胜出?

一旦有足够的并发流量可以批量处理请求,GPU 通常就会胜出;对于太大或太慢、无法在延迟目标内用 CPU 提供服务的模型,也是如此。批处理把加速器的固定成本分摊到许多请求上。

  • 批处理和连续批处理。Kwon 等人报告称,借助 PagedAttention 管理 KV 缓存的 vLLM,在相同延迟下的吞吐量是 FasterTransformer 和 Orca 等早期系统的 2 至 4 倍。在同样的通电时间内完成更多有用的工作,意味着每个请求的能耗更低。
  • 各项优化会叠加。Fernandez 等人发现,与未经优化的基线相比,采用合适的推理优化最多可将总能耗降低 73%,而收益在很大程度上取决于工作负载形态、软件栈和硬件。请用您实际会使用的服务功能对 GPU 进行基准测试。
  • 大模型和长输出。更大的模型和更长的生成会使每个请求的计算量成倍增加,而这正是加速器设计上高效的地方。

同一篇论文发现,基于 FLOPs 或理论 GPU 利用率的简单能耗估算,会严重低估实际能耗。这就是要测量而不是计算的理由。

什么样的比较才公平?

除硬件外保持一切不变,并在质量和延迟相当的条件下进行比较。答案更差的 CPU 结果,或者您从未遇到过的流量水平下的 GPU 结果,都说明不了任何问题。

  1. 固定模型及其版本,并写下每个平台上的精度或量化格式。如果 CPU 运行的是 4 位版本,而 GPU 运行的是半精度,那您比较的就是两个模型;这可能正是您要问的问题,但请加以说明,并检查两者的质量。
  2. 固定提示词。使用几百条真实的、经过匿名化的请求,保留其自然的输入长度分布,放在版本控制下的一个文件中。
  3. 固定生成设置:最大输出 token 数、温度(为了可重复,设为 0)、停止序列和随机种子。
  4. 检查每个响应的质量。为每个提示词设定一个通过测试(预期标签、正则表达式、schema 检查),只把通过的答案算作成功。又快又错的答案不算节省。
  5. 使用相同的服务接口。两边都使用兼容 OpenAI 的端点,可以让客户端保持完全相同。llama.cpp 的服务器在这样的 API 后面,在 CPU 和 GPU 上运行 F16 和量化模型,支持连续批处理和并行解码;vLLM 提供了一个在 GPU 上实现 OpenAI Completions 和 Chat API 的 HTTP 服务器。
  6. 设定延迟目标,例如第 95 百分位的响应时间,并舍弃任何未达到目标的配置。

应该如何施加负载?

先预热,然后在几个稳定的请求速率下各保持足够长的时间以覆盖许多次电表读数,并把空闲作为一个单独的负载水平来测量。真实的服务很少处于峰值,所以低速率和高速率同样重要。

  • 加载模型后的空闲。在服务器运行、没有流量的情况下测量几分钟。这个数字决定了盈亏平衡点。
  • 预热。在测量之前先发送一批请求,让缓存、已编译的内核和时钟频率稳定下来。
  • 稳定的负载水平。以固定的平均速率发送请求,例如从您最空闲的时段到最繁忙的时段取五个速率,到达时间采用随机(泊松)分布,而不是整齐划一。舍弃每个水平开始时的爬升阶段,测量几分钟的窗口。
  • 批处理设置。在支持连续批处理的服务器上,批大小随并发而变化;记录服务器的最大批次或槽位设置(对于 llama.cpp,是并行槽位的数量),并尝试两三种设置。对于离线任务,还要直接测试固定的批大小;批量处理可以等待的工作往往是最大的节省。
  • 重复。每个水平至少运行三次,报告平均值和范围。llama.cpp 自带的基准测试工具 llama-bench 默认把每项测试重复五次并运行预热轮次,这是一个明智的习惯。
  • 找到上限。提高速率,直到延迟超出目标,或实际吞吐量不再跟随所施加的速率。这就是该平台的容量,超过这一点就需要第二个节点。

如何测量能耗?

在每个窗口的开始和结束时读取累计能耗计数器,只在没有计数器的地方才使用采样功率。然后在每个平台上用整个节点的读数核对一次软件电表。

CPU 封装和内存:RAPL

Linux 通过 powercap 接口提供 Intel 的运行平均功率限制(RAPL)计数器。/sys/class/powercap/ 下的每个区域都有一个 name、一个以微焦耳计的 energy_uj 计数器和一个 max_energy_range_uj,即计数器回绕到零之前的范围。RAPL 不提供瞬时功率值,所以您要计算两次读数之差并处理回绕。

  • 把哪些区域加起来。使用 package-N 区域,在存在时再加上 dram。封装已经包含了 core 和 uncore 子区域,Kepler 项目提醒这些区域相互重叠,不应盲目相加;psys(如果存在)与封装重叠。
  • DRAM 往往缺失。Kepler 的文档指出,许多客户端 CPU 和 AMD 处理器不提供 DRAM 域,而虚拟机通常根本不提供任何 RAPL 域。在云虚拟机上,您可能只能估算;参见如何测量 AI 能耗。
  • 权限。在 PLATYPUS 功耗侧信道攻击(CVE-2020-8694 和 CVE-2020-8695)之后,Linux 把 RAPL 读数设为需要特权,所以请以 root 身份运行电表,或有意识地授予读取权限。

GPU:NVML

NVIDIA 的管理库 NVML 提供两种途径:

  • 能耗计数器。在 Volta 或更新的 GPU 上,nvmlDeviceGetTotalEnergyConsumption 返回自驱动程序上次重新加载以来的总能耗(毫焦耳)。在窗口的开始和结束时读取它。这是更好的选择。
  • 采样功率。nvmlDeviceGetPowerUsage 返回 GPU 及其相关电路的功率(毫瓦)。NVIDIA 的文档说明,在 Ampere(GA100 除外)及更新的 GPU 上,它是一秒内的平均值,而在 GA100 及更早的 GPU 上是瞬时值。在短窗口内对采样功率积分是不可靠的:Yang 等人发现,在 A100 和 H100 GPU 上,nvidia-smi 只对约 25% 的运行时间进行了功率采样,而对照外部电表进行校正后,能耗测量误差平均降低了 35%,在某些情况下最多降低了 65%。
  • 利用率很粗略。NVML 的 GPU 利用率是采样周期内有一个或多个内核在执行的时间百分比,所以 100% 并不意味着 GPU 的计算单元被充分使用。

整个节点

GPU 服务器的能耗不只是其 GPU 的能耗。在可能的情况下,请用带计量功能的电源插排或功率分析仪在墙插处测量节点,或者读取服务器的基板管理控制器(BMC):在支持 DCMI 的服务器上,ipmitool dcmi power reading 会返回平台的功率读数。BMC 读数比较粗略,所以要在长窗口内每隔几秒采样一次。MLPerf 的推理功耗规则也持同样观点:功率在系统层面(“在墙插处”)用 SPEC PTDaemon 支持的分析仪测量。一篇论文介绍了基于这些规则的 MLPerf Power 方法,分析了来自 60 个系统的 1,841 项可重复测量,范围从微瓦级设备到数据中心集群。

冷却等数据中心开销甚至在墙插读数之外;如果它属于您的边界,请单独应用 PUE。

应该计算什么?

在每个负载水平下计算每个成功请求的能耗、每个输出 token 的能耗、空闲功耗、利用率、延迟和成本。也要保留总数,以便他人重新计算。

指标 计算方法 为什么
每个成功请求的能耗(J) 窗口能耗 ÷ 已完成且通过质量检查的请求数 决策指标;失败和错误的答案同样耗能
每个输出 token 的能耗(J) 窗口能耗 ÷ 已完成的输出 token 数 用于比较答案长度不同的运行
空闲功耗(W) 空闲窗口的能耗 ÷ 窗口时长 决定盈亏平衡点
每个请求的动态能耗(J) (窗口能耗 − 空闲功耗 × 时长)÷ 成功数 显示工作本身增加了多少
利用率(%) CPU 忙碌占比取自 /proc/stat;GPU 取自 NVML 用于解释结果;不能替代能耗
延迟(s) 成功请求的中位数和第 95 百分位 排除未达到目标的配置
每个成功请求的成本 每节点小时价格 × 窗口小时数 ÷ 成功数 把能耗与金钱并列;自有设备还要加上硬件折旧

用能耗除以 token 数暗藏一个陷阱:当某个平台产生更长的答案时,它看起来每个 token 更便宜,而每个请求更昂贵。请以每个成功请求的能耗为主,用每个 token 的数据作交叉核对。

盈亏平衡点在哪里?

流量高于某个水平时,GPU 能收回其额外的空闲功耗;低于这个水平时,CPU 每个请求的能耗更低。这个水平要从您的测量中得出,而不是从数据表中得出。

在每秒 λ 个请求的稳定速率下(低于每个平台的容量),平均功率大致为:

P(λ) = Pidle + λ × e(λ)

其中 Pidle 是加载模型后的空闲功耗,e(λ) 是该速率下每个请求的额外能耗。于是每个请求的能耗为 Pidle ÷ λ + e(λ):空闲项随流量增长而缩小。在以下情况下,GPU 方案每个请求的能耗更低:

λ > (Pidle, GPU − Pidle, CPU) ÷ (eCPU − eGPU)

有三件事让它变得复杂,这就是为什么要绘制实测曲线并读取交点,而不是代入一个数字:

  • e(λ) 不是常数。在 GPU 上,它随负载上升而下降,因为批次变得更满。
  • 容量是阶梯式的。一旦流量超过一个 CPU 节点的上限,您就需要两个节点,它们的空闲功耗也会翻倍。
  • 真正计算的是预置时间。如果在流量停止时可以释放 GPU 或将其缩容到零,它的空闲项只涵盖它实际运行的那些小时。参见如何避免 GPU 闲置。

要同类比较:整个 CPU 节点对整个 GPU 节点,或者新增的 GPU 对“什么都不加”,而不是用 GPU 自己的读数去比 CPU 的整个节点。然后只比较达到延迟目标的点。如果盈亏平衡点高于您最繁忙的时段,那么对于这个工作负载,CPU 是能耗更低的选择;如果低于您最空闲的时段,GPU 就是。处于两者之间时,可以考虑把空闲时段的流量路由到 CPU,或者让 GPU 在多个服务之间共享以保持忙碌。

报告里应该写什么?

足以让别人重复这次运行并得到相似答案的信息。请把以下内容与数字一起发布:

workload:
  model: name, version, licence; precision or quantisation on each platform (e.g. GGUF Q4_K_M, FP16)
  prompts: file name and hash; count; input-token median and range
  generation: max_tokens, temperature, seed, stop sequences
  quality_check: method and pass rate on each platform
hardware:
  cpu_node: CPU model and count, memory, BIOS power profile, OS and kernel
  gpu_node: GPU model and count, driver, CUDA or ROCm version, host CPU and memory
  location: on-premises or cloud instance type and region
software:
  server: name and version (e.g. llama.cpp build, vLLM version), launch flags, batch or slot settings
  benchmark_script: version, client concurrency limit, host it ran on
method:
  load_levels: rates tested, ramp and window length, repeats
  meters: RAPL zones used, NVML counter or sampled power, wall meter or BMC model and interval
  boundary: CPU package + DRAM + GPU, or whole node at the wall; PUE applied or not
results_per_level:
  achieved_rate, successes, errors, quality_failures, energy_J, mean_power_W, idle_W,
  J_per_successful_request, J_per_output_token, latency_p50_s, latency_p95_s,
  cpu_util_pct, gpu_util_pct, cost_per_successful_request
uncertainty:
  mean and range across repeats; meter accuracy if known; software meters checked against the wall: yes/no

只有在说明的情况下才可以不计隐含碳。为节省运行能耗而购买 GPU,本身也有制造足迹;参见计算 AI 硬件的隐含碳。

一个示意性的基准测试脚本

下面的脚本针对任何兼容 OpenAI 的端点,从头到尾执行上述方法。它是供改编的示例,而不是成品工具:在信任它的数字之前,请先对照您自己的硬件和墙插电表进行检查。

它测量空闲功耗,进行预热,在每个速率下按泊松时间间隔发送请求,并为每个负载水平和每次重复输出一行 JSON。它读取 RAPL 的封装和 DRAM 区域(轮询频率足以捕捉计数器回绕)、NVML 能耗计数器或采样功率,还可以选择从 ipmitool dcmi power reading 这样的命令读取整个节点的数据。提示词文件的每一行是 {"prompt": "...", "expect": "regular expression"}。

#!/usr/bin/env python3
"""Illustrative CPU-versus-GPU inference energy benchmark. Adapt it before you rely on it.

Sends a fixed prompt set to an OpenAI-compatible chat endpoint (llama-server, vLLM and
others expose one) at fixed request rates, and reports energy per successful request and
per output token at each rate, next to the idle power of the same machine.

Meters: Linux powercap (RAPL package and DRAM zones), NVIDIA NVML (energy counter, or
sampled power when the counter is not supported) and, optionally, a whole-node reading
from a command such as `ipmitool dcmi power reading`.

Needs: Python 3.9+, httpx; nvidia-ml-py for GPUs. Reading RAPL usually needs root.
"""
import argparse
import asyncio
import glob
import json
import os
import random
import re
import shlex
import statistics
import subprocess
import threading
import time

import httpx

try:
    import pynvml  # provided by the nvidia-ml-py package
except ImportError:
    pynvml = None


class RaplMeter(threading.Thread):
    """Cumulative CPU package and DRAM energy from Linux powercap, in joules.

    A background thread polls the counters often enough to catch every wrap-around.
    """

    def __init__(self, root, interval=1.0):
        super().__init__(daemon=True)
        self.zones, self.interval, self.lock = [], interval, threading.Lock()
        for path in sorted(glob.glob(os.path.join(root, "intel-rapl:*"))):
            with open(os.path.join(path, "name")) as f:
                name = f.read().strip()
            # Package zones already contain core and uncore; psys overlaps the package.
            if name.startswith("package") or name == "dram":
                with open(os.path.join(path, "max_energy_range_uj")) as f:
                    wrap = int(f.read())
                kind = "dram" if name == "dram" else "cpu_package"
                self.zones.append((kind, os.path.join(path, "energy_uj"), wrap))
        self.last = [self._raw(z) for z in self.zones]
        self.totals = [0.0] * len(self.zones)
        if self.zones:
            self.start()

    @staticmethod
    def _raw(zone):
        with open(zone[1]) as f:
            return int(f.read())

    def _poll(self):
        with self.lock:
            for i, zone in enumerate(self.zones):
                now = self._raw(zone)
                delta = now - self.last[i]
                if delta < 0:  # the counter wrapped at max_energy_range_uj
                    delta += zone[2]
                self.totals[i] += delta / 1e6
                self.last[i] = now
            return list(self.totals)

    def run(self):
        while True:
            time.sleep(self.interval)
            self._poll()

    def read(self):
        return self._poll()

    def joules(self, start, end):
        totals = {}
        for (kind, _, _), a, b in zip(self.zones, start, end):
            totals[kind] = totals.get(kind, 0.0) + (b - a)
        return totals


class Sampler(threading.Thread):
    """Calls fn() every interval seconds and keeps (time, value) pairs."""

    def __init__(self, fn, interval):
        super().__init__(daemon=True)
        self.fn, self.interval, self.samples = fn, interval, []
        self._halt = threading.Event()

    def run(self):
        while not self._halt.is_set():
            try:
                value = self.fn()
            except Exception:
                value = None
            if value is not None:
                self.samples.append((time.time(), value))
            self._halt.wait(self.interval)

    def stop(self):
        self._halt.set()

    def window(self, t0, t1):
        return [(t, v) for t, v in self.samples if t0 <= t <= t1]

    def mean(self, t0, t1):
        values = [v for _, v in self.window(t0, t1)]
        return statistics.fmean(values) if values else None

    def integrate(self, t0, t1):
        """Energy in joules over the window from a sampled power series in watts."""
        pts = self.window(t0, t1)
        if len(pts) < 2:
            return None
        area = sum((tb - ta) * (va + vb) / 2 for (ta, va), (tb, vb) in zip(pts, pts[1:]))
        # Scale the mean power of the sampled span to the whole window.
        return area / (pts[-1][0] - pts[0][0]) * (t1 - t0)


class NvmlMeter:
    """GPU energy from NVML: the energy counter (Volta and newer) or sampled power."""

    def __init__(self, interval):
        pynvml.nvmlInit()
        self.handles = [pynvml.nvmlDeviceGetHandleByIndex(i)
                        for i in range(pynvml.nvmlDeviceGetCount())]
        try:
            for h in self.handles:
                pynvml.nvmlDeviceGetTotalEnergyConsumption(h)
            self.has_counter = True
        except pynvml.NVMLError:
            self.has_counter = False
        self.power = Sampler(lambda: sum(pynvml.nvmlDeviceGetPowerUsage(h)
                                         for h in self.handles) / 1000.0, interval)
        self.util = Sampler(lambda: statistics.fmean(pynvml.nvmlDeviceGetUtilizationRates(h).gpu
                                                     for h in self.handles), interval)
        self.power.start()
        self.util.start()

    def read(self):
        if not self.has_counter:
            return None
        return [pynvml.nvmlDeviceGetTotalEnergyConsumption(h) for h in self.handles]  # mJ

    def joules(self, start, end, t0, t1):
        if self.has_counter:
            return sum(b - a for a, b in zip(start, end)) / 1000.0
        return self.power.integrate(t0, t1)  # less accurate: see the sampling caveats


def cpu_util_sampler():
    """Busy share of all CPUs from /proc/stat, as a percentage, between calls."""
    previous = {}

    def sample():
        with open("/proc/stat") as f:
            fields = [int(x) for x in f.readline().split()[1:]]
        idle = fields[3] + fields[4]  # idle + iowait
        total = sum(fields[:8])       # user..steal; guest time is already in user
        if not previous:
            previous.update(idle=idle, total=total)
            return None
        d_total, d_idle = total - previous["total"], idle - previous["idle"]
        previous.update(idle=idle, total=total)
        return 100.0 * (d_total - d_idle) / d_total if d_total else None

    return sample


def node_power_sampler(command):
    """Whole-node watts from a command; the default pattern fits `ipmitool dcmi power reading`."""
    argv = shlex.split(command)
    pattern = re.compile(r"Instantaneous power reading:\s*([\d.]+)\s*Watts|([\d.]+)\s*W\b")

    def sample():
        out = subprocess.run(argv, capture_output=True, text=True, timeout=10).stdout
        m = pattern.search(out)
        return float(m.group(1) or m.group(2)) if m else None

    return sample


async def one_request(client, args, item, records):
    started = time.time()
    record = {"start": started, "ok": False, "quality_ok": False, "out_tokens": 0, "in_tokens": 0}
    try:
        r = await client.post("/v1/chat/completions", json={
            "model": args.model,
            "messages": [{"role": "user", "content": item["prompt"]}],
            "max_tokens": args.max_tokens,
            "temperature": 0,
            "seed": 1,
        })
        r.raise_for_status()
        body = r.json()
        text = body["choices"][0]["message"]["content"] or ""
        usage = body.get("usage") or {}
        record.update(ok=True,
                      quality_ok=bool(re.search(item["expect"], text, re.IGNORECASE)),
                      out_tokens=usage.get("completion_tokens", 0),
                      in_tokens=usage.get("prompt_tokens", 0))
    except (httpx.HTTPError, KeyError, ValueError, IndexError):
        pass
    record["end"] = time.time()
    records.append(record)


async def run_rate(client, args, prompts, rate, meters):
    """Poisson arrivals at `rate` req/s; measure only the steady-state window after the ramp."""
    rapl, nvml, cpu, node = meters
    records, tasks = [], []
    start = time.time()
    t0, t1 = start + args.ramp, start + args.ramp + args.window
    marks = {}

    async def mark(name, at):
        await asyncio.sleep(max(0.0, at - time.time()))
        marks[name] = (time.time(), rapl.read() if rapl else None, nvml.read() if nvml else None)

    markers = [asyncio.create_task(mark("t0", t0)), asyncio.create_task(mark("t1", t1))]
    rng = random.Random(42)
    i = 0
    while time.time() < t1:
        tasks.append(asyncio.create_task(one_request(client, args, prompts[i % len(prompts)], records)))
        i += 1
        await asyncio.sleep(rng.expovariate(rate))
    await asyncio.gather(*markers)
    await asyncio.gather(*tasks)  # drain; requests that finish after t1 are not counted

    (a_t, a_rapl, a_nvml), (b_t, b_rapl, b_nvml) = marks["t0"], marks["t1"]
    seconds = b_t - a_t
    done = [r for r in records if a_t <= r["end"] <= b_t]
    good = [r for r in done if r["ok"] and r["quality_ok"]]
    energy = rapl.joules(a_rapl, b_rapl) if rapl else {}
    if nvml:
        energy["gpu"] = nvml.joules(a_nvml, b_nvml, a_t, b_t)
    if node:
        energy["node"] = node.integrate(a_t, b_t)
    # Boundary: the whole node if metered, otherwise CPU package + DRAM + GPU.
    boundary = "node" if energy.get("node") is not None else "cpu_package+dram+gpu"
    measured = [v for v in energy.values() if v is not None]
    total = energy["node"] if boundary == "node" else (sum(measured) if measured else None)
    out_tokens = sum(r["out_tokens"] for r in done)
    latencies = sorted(r["end"] - r["start"] for r in good)

    def per(x, n):
        return x / n if (x is not None and n) else None

    return {
        "target_rps": rate,
        "achieved_rps": len(done) / seconds,
        "window_s": round(seconds, 2),
        "completed": len(done),
        "errors": sum(1 for r in done if not r["ok"]),
        "quality_failures": sum(1 for r in done if r["ok"] and not r["quality_ok"]),
        "successful": len(good),
        "input_tokens": sum(r["in_tokens"] for r in done),
        "output_tokens": out_tokens,
        "boundary": boundary,
        "energy_j": {k: round(v, 1) for k, v in energy.items() if v is not None},
        "mean_power_w": per(total, seconds),
        "j_per_successful_request": per(total, len(good)),
        "j_per_output_token": per(total, out_tokens),
        "dynamic_j_per_successful_request": (per(total - args.idle_w * seconds, len(good))
                                             if None not in (total, args.idle_w) else None),
        "latency_p50_s": statistics.median(latencies) if latencies else None,
        "latency_p95_s": statistics.quantiles(latencies, n=20)[18] if len(latencies) >= 2 else None,
        "cpu_util_pct": cpu.mean(a_t, b_t),
        "gpu_util_pct": nvml.util.mean(a_t, b_t) if nvml else None,
        "cost_per_successful_request": (per(args.hourly_price * seconds / 3600, len(good))
                                        if args.hourly_price else None),
    }


def measure_idle(args, meters):
    rapl, nvml, cpu, node = meters
    a = (time.time(), rapl.read() if rapl else None, nvml.read() if nvml else None)
    time.sleep(args.idle)
    b = (time.time(), rapl.read() if rapl else None, nvml.read() if nvml else None)
    energy = rapl.joules(a[1], b[1]) if rapl else {}
    if nvml:
        energy["gpu"] = nvml.joules(a[2], b[2], a[0], b[0])
    if node:
        energy["node"] = node.integrate(a[0], b[0])
    seconds = b[0] - a[0]
    watts = {k: v / seconds for k, v in energy.items() if v is not None}
    total = watts["node"] if "node" in watts else sum(watts.values())
    return {"idle_s": round(seconds, 1), "idle_w": watts, "idle_total_w": total if watts else None}


async def main_async(args):
    with open(args.prompts) as f:
        prompts = [json.loads(line) for line in f if line.strip()]
    rapl = RaplMeter(args.rapl_root)
    rapl = rapl if rapl.zones else None
    nvml = None
    if pynvml and not args.no_gpu:
        try:
            nvml = NvmlMeter(args.sample_interval)
        except pynvml.NVMLError:
            print(json.dumps({"warning": "NVML found no usable GPU; measuring CPU only"}))
    cpu = Sampler(cpu_util_sampler(), args.sample_interval)
    cpu.start()
    node = None
    if args.node_power_cmd:
        node = Sampler(node_power_sampler(args.node_power_cmd), args.node_interval)
        node.start()
    meters = (rapl, nvml, cpu, node)
    if not (rapl or nvml or node):
        print(json.dumps({"warning": "no energy meter found; only throughput and latency are reported"}))

    limits = httpx.Limits(max_connections=args.max_in_flight)
    async with httpx.AsyncClient(base_url=args.url, timeout=args.timeout, limits=limits) as client:
        # Model loaded, no traffic: this is the idle power the break-even depends on.
        idle = await asyncio.to_thread(measure_idle, args, meters)
        if args.idle_w is None:
            args.idle_w = idle["idle_total_w"]
        print(json.dumps({"phase": "idle", **idle}))

        warm = []
        for item in prompts[: args.warmup]:
            await one_request(client, args, item, warm)
        print(json.dumps({"phase": "warmup", "requests": len(warm),
                          "quality_pass_rate": per_rate(warm)}))

        for rate in args.rates:
            for repeat in range(args.repeats):
                result = await run_rate(client, args, prompts, rate, meters)
                print(json.dumps({"phase": "load", "repeat": repeat, **result}))


def per_rate(records):
    ok = [r for r in records if r["ok"]]
    return sum(r["quality_ok"] for r in ok) / len(ok) if ok else None


def main():
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("--url", required=True, help="server base URL, e.g. http://127.0.0.1:8080")
    p.add_argument("--model", default="local")
    p.add_argument("--prompts", required=True, help='JSONL lines of {"prompt": ..., "expect": regex}')
    p.add_argument("--rates", type=float, nargs="+", default=[0.2, 0.5, 1, 2, 4])
    p.add_argument("--repeats", type=int, default=3)
    p.add_argument("--max-tokens", type=int, default=256)
    p.add_argument("--warmup", type=int, default=20)
    p.add_argument("--idle", type=float, default=120, help="seconds of idle measurement")
    p.add_argument("--idle-w", type=float, default=None, help="override measured idle watts")
    p.add_argument("--ramp", type=float, default=60, help="seconds before each measured window")
    p.add_argument("--window", type=float, default=300, help="seconds per measured window")
    p.add_argument("--sample-interval", type=float, default=0.1)
    p.add_argument("--node-power-cmd", default=None, help='e.g. "ipmitool dcmi power reading"')
    p.add_argument("--node-interval", type=float, default=2.0)
    p.add_argument("--rapl-root", default="/sys/class/powercap")
    p.add_argument("--no-gpu", action="store_true")
    p.add_argument("--max-in-flight", type=int, default=256)
    p.add_argument("--timeout", type=float, default=120)
    p.add_argument("--hourly-price", type=float, default=None, help="price per node-hour")
    asyncio.run(main_async(p.parse_args()))


if __name__ == "__main__":
    main()

用相同的提示词文件和速率,分别对 CPU 服务器和 GPU 服务器各运行一次:

sudo .venv/bin/python bench_energy.py --url http://127.0.0.1:8080 --prompts prompts.jsonl \
  --rates 0.1 0.25 0.5 1 2 4 --node-power-cmd "ipmitool dcmi power reading" > cpu-node.jsonl

已知的局限,您应该修正或在报告中说明:

  • 窗口边缘。请求在窗口内完成时才被计数,而能耗是整个窗口的总量。在稳定状态下,边缘效应大致相互抵消;在非常低的速率下,请延长窗口。
  • 负载生成器与被测机器共用一台机器,除非您在别处运行它。请从另一台主机运行,以免它的 CPU 使用被计入 CPU 节点的数据。
  • RAPL 轮询的频率必须高于计数器回绕所需的时间。请对照您的封装功率检查 max_energy_range_uj。
  • 采样的 GPU 功率只是后备方案;请优先使用带能耗计数器的 GPU。
  • 用正则表达式进行质量检查适合简短答案。对于开放式输出,请在离线状态下对保存的响应进行更严格的检查。

下一步做什么

  1. 选择一个推理工作负载,保存几百条带通过测试的匿名提示词,并设定延迟目标。
  2. 在您已有的 CPU 服务器上用模型的量化版本运行基准测试脚本,再在一个开启了连续批处理的 GPU 配置上运行。
  3. 在两边测量加载模型后的空闲功耗,并用墙插电表或 BMC 核对一次软件电表。
  4. 绘制每个成功请求的能耗随请求速率变化的曲线,标出延迟上限和容量,并读出盈亏平衡点。
  5. 把盈亏平衡点与您按一天中各时段统计的真实流量进行比较;考虑把空闲时段路由到 CPU,或把 GPU 缩容到零。参见如何降低模型服务的能耗。
  6. 借助 AI 能耗可观测性在生产环境中持续测量,并在更换硬件之前设定基线。

常见问题

CPU 推理比 GPU 推理更节能吗?

有时是。对于流量低或不规律的小模型或量化模型,您已经在运行的 CPU 服务器每个请求的能耗可能更低,因为它不会增加加速器的空闲功耗。当流量足以批量处理请求时,GPU 通常每焦耳能完成更多工作。请在您自己的工作负载上测量两者。

我能只比较每秒 token 数吗?

不能。峰值负载下的吞吐量完全不能说明硬件处于空闲或半忙状态的那些时间,也不能说明答案质量。请在您实际遇到的流量水平下、在延迟目标之内比较每个成功请求的能耗。

用 nvidia-smi 测量 GPU 能耗有多准确?

要谨慎对待。NVML 在 Volta 及更新的 GPU 上有累计能耗计数器,这比采样功率更好。在较新的 GPU 上,功率读数是一秒内的平均值,在较旧的 GPU 上是瞬时值;研究人员发现,nvidia-smi 在 A100 和 H100 GPU 上只对约 25% 的运行时间进行了采样。请在每个平台上用墙插电表核对一次。

什么是 RAPL?

运行平均功率限制(Running Average Power Limit):许多 Intel 和 AMD 处理器中的能耗计数器,Linux 通过 powercap 接口以微焦耳为单位提供。它们涵盖 CPU 封装,在某些机器上还涵盖 DRAM,但不包括服务器的其余部分,而且通常需要 root 权限才能读取。

基准测试应该包括整台服务器吗?

如果可以,应该包括。GPU 服务器还运行着主机 CPU、内存、风扇和电源。请用墙插电表或服务器的管理控制器测量整个节点,或者清楚地说明您的数据只涵盖部件。

来源

  1. Power Capping Framework, The Linux kernel documentation (2026)
  2. PLATYPUS: software-based power side-channel attacks on x86 (CVE-2020-8694, CVE-2020-8695), Lipp et al. (2020)
  3. Kepler metrics (v0.14.0): energy zones and DRAM energy, Kepler project, CNCF (2026)
  4. NVML API reference: device queries, NVIDIA (2026)
  5. NVML API reference: nvmlUtilization_t, NVIDIA (2026)
  6. Part-time power measurements: nvidia-smi's lack of attention, Yang et al. (arXiv 2312.02741) (2023)
  7. ipmitool manual page (dcmi power reading), ipmitool project (2023)
  8. MLPerf Inference power measurement rules, MLCommons (2022)
  9. MLPerf Power: benchmarking the energy efficiency of machine learning systems from microwatts to megawatts for sustainable AI, Tschand et al. (arXiv 2410.12032) (2025)
  10. Quantize ONNX models, ONNX Runtime documentation (2026)
  11. llama.cpp HTTP server, llama.cpp project (2026)
  12. llama-bench, llama.cpp project (2026)
  13. llama.cpp quantize tool, llama.cpp project (2026)
  14. OpenAI-compatible server, vLLM documentation (2026)
  15. Energy considerations of large language model inference and efficiency optimizations, Fernandez et al. (arXiv 2504.17674) (2025)
  16. Efficient memory management for large language model serving with PagedAttention, Kwon et al. (arXiv 2309.06180) (2023)

加入我们

帮助减少 AI 对地球的影响

通过电子邮件获取新指南、资助征集和名录收录信息,大约每月一次。您也可以将您的产品、课程、博士岗位或研究添加到名录中。

不做跟踪。一键退订。 其他加入方式 · 隐私