> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/powerinfer.md).

# PowerInfer

**利用激活局部性的 CPU/GPU 混合 LLM 推理** —— 通过智能地在 CPU 和 GPU 之间分配计算，在单块消费级 GPU 上运行 70B 参数模型。

> 🌟 **8,000+ GitHub 星标** | 由 SJTU IPADS 开发 | MIT 许可证

***

## 什么是 PowerInfer？

PowerInfer 是一款面向大语言模型的高性能推理引擎，它利用了一个关键洞见： **LLM 具有很强的激活局部性** —— 一小部分神经元（“热点神经元”）会在大多数推理步骤中持续被激活，而其余大多数保持不活跃。

PowerInfer 利用这一特性来：

1. **将热点神经元保留在 GPU 上** 以便快速计算
2. **将冷门神经元卸载到 CPU/RAM** 而不会显著损失质量
3. **动态路由** 根据激活模式在 CPU 和 GPU 之间分配计算

结果是：你只需 **16GB VRAM** 就能运行一个 70B 模型，而不需要 140GB+ 全部放在 GPU 上。

### 核心能力

* **支持消费级 GPU** —— RTX 3090/4090 可以运行 70B 模型
* **神经元感知调度** —— 预测器为每次推理决定 CPU 与 GPU 的路由
* **极小的质量损失** —— 保持超过 95% 的全精度质量
* **兼容 llama.cpp** —— 支持 GGUF 格式
* **NUMA 感知的 CPU 卸载** —— 针对高核心数 CPU 进行了优化

### 为什么要在 Clore.ai 上使用 PowerInfer？

Clore.ai 的 GPU 租用成本远低于云厂商替代方案。使用 PowerInfer：

* 运行 **Llama 2 70B** 在 **单块 RTX 4090** （24GB VRAM）
* 相比多 GPU 方案，大幅降低 GPU 租用成本
* 使用 CPU RAM 作为溢出空间处理长上下文窗口
* 运行此前需要昂贵 A100/H100 实例的模型

***

## 硬件要求

| 模型大小 | 最低显存 | 推荐内存  | 性能  |
| ---- | ---- | ----- | --- |
| 7B   | 4GB  | 16GB  | 优秀  |
| 13B  | 6GB  | 32GB  | 非常好 |
| 34B  | 12GB | 64GB  | 好   |
| 70B  | 16GB | 128GB | 中等  |

{% hint style="info" %}
**CPU 很重要：** PowerInfer 会将冷门神经元卸载到 CPU。具备高核心数（AMD EPYC、Intel Xeon）且内存带宽较快的 CPU 会显著提升大模型吞吐量。
{% endhint %}

***

## 在 Clore.ai 上快速开始

### 步骤 1：选择你的服务器

在 [clore.ai](https://clore.ai) 市场中，筛选以下条件：

* **NVIDIA GPU** 具备 16GB+ VRAM（RTX 3090、RTX 4090、A100）
* **高 CPU 核心数** （16 核以上更理想）
* **64GB+ RAM** 70B 模型建议 64GB，13B 模型建议 32GB

### 步骤 2：创建自定义 Docker 镜像

PowerInfer 需要自定义的 Docker 配置。使用这个 `Dockerfile`:

```dockerfile
FROM nvidia/cuda:12.8.1-devel-ubuntu22.04

# 安装依赖
RUN apt-get update && apt-get install -y \
    git \
    cmake \
    build-essential \
    python3 \
    python3-pip \
    curl \
    wget \
    openssh-server \
    && rm -rf /var/lib/apt/lists/*

# 配置 SSH
RUN mkdir /var/run/sshd && \
    echo 'root:powerinfer' | chpasswd && \
    sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# 克隆并构建 PowerInfer
RUN git clone https://github.com/SJTU-IPADS/PowerInfer.git /app/PowerInfer
WORKDIR /app/PowerInfer

RUN mkdir build && cd build && \
    cmake .. -DLLAMA_CUBLAS=ON && \
    cmake --build . --config Release -j$(nproc)

# 安装 solver 的 Python 依赖
RUN pip3 install torch numpy scipy

EXPOSE 22

CMD ["/bin/bash", "-c", "service ssh start && tail -f /dev/null"]
```

构建并推送到 Docker Hub，或在 Clore.ai 中内联使用：

```bash
docker build -t yourname/powerinfer:latest .
docker push yourname/powerinfer:latest
```

### 步骤 3：在 Clore.ai 上部署

在你的 Clore.ai 订单中，设置：

* **Docker 镜像：** `yourname/powerinfer:latest`
* **端口：** `22` （SSH）
* **环境变量：** `NVIDIA_VISIBLE_DEVICES=all`

***

## 从源码构建 PowerInfer

如果你更愿意在容器内构建：

```bash
# SSH 登录你的 Clore.ai 服务器
ssh root@<clore-node-ip> -p <ssh-port>

# 安装前置依赖
apt-get update && apt-get install -y git cmake build-essential python3 python3-pip

# 克隆 PowerInfer
git clone https://github.com/SJTU-IPADS/PowerInfer.git
cd PowerInfer

# 使用 CUDA 支持进行构建
mkdir build && cd build
cmake .. -DLLAMA_CUBLAS=ON -DCMAKE_BUILD_TYPE=Release
cmake --build . --config Release -j$(nproc)

echo "构建完成！"
ls -la bin/
```

### 验证构建

```bash
./build/bin/main --help
# 应输出 PowerInfer CLI 帮助信息
```

***

## 获取模型

### 下载 GGUF 模型

PowerInfer 使用 GGUF 格式（与 llama.cpp 相同）：

```bash
# 安装 HuggingFace CLI
pip3 install huggingface_hub

# 下载 Llama 2 7B Q4（建议用于测试）
huggingface-cli download TheBloke/Llama-2-7B-Chat-GGUF \
  llama-2-7b-chat.Q4_K_M.gguf \
  --local-dir ./models

# 下载 Llama 2 70B Q4（需要 16GB+ VRAM）  
huggingface-cli download TheBloke/Llama-2-70B-Chat-GGUF \
  llama-2-70b-chat.Q4_K_M.gguf \
  --local-dir ./models
```

### 生成神经元预测器（PowerInfer 必需）

PowerInfer 需要为每个模型生成神经元激活预测器。这是与 llama.cpp 的关键区别：

```bash
# 安装 Python solver 依赖
pip3 install torch numpy scipy

# 为你的模型生成预测器
python3 PowerInfer/solver/solve.py \
  --model ./models/llama-2-7b-chat.Q4_K_M.gguf \
  --output ./predictors/llama-2-7b-chat \
  --target-gpu-layers 20 \
  --gpu-memory-gb 16

# 这会在 ./predictors/ 中创建预测器文件
ls ./predictors/llama-2-7b-chat/
```

{% hint style="warning" %}
**预测器生成时间：** 创建神经元预测器可能需要 30–60 分钟，具体取决于模型大小。这是一次性操作——预测器会在后续运行中复用。
{% endhint %}

***

## 运行推理

### 基础推理（无预测器）

用于在不生成预测器的情况下测试（标准 GPU/CPU 切分）：

```bash
./build/bin/main \
  -m ./models/llama-2-7b-chat.Q4_K_M.gguf \
  --gpu-layers 20 \
  -p "告诉我量子计算" \
  -n 256
```

### PowerInfer 模式（带预测器）

带神经元感知路由的完整 PowerInfer 模式：

```bash
./build/bin/main \
  -m ./models/llama-2-7b-chat.Q4_K_M.gguf \
  --predictor-path ./predictors/llama-2-7b-chat \
  --gpu-layers 20 \
  --n-gpu-layers 20 \
  -p "生命的意义是什么？" \
  -n 512 \
  --ctx-size 4096
```

### 交互式聊天模式

```bash
./build/bin/main \
  -m ./models/llama-2-7b-chat.Q4_K_M.gguf \
  --predictor-path ./predictors/llama-2-7b-chat \
  --gpu-layers 20 \
  -i \
  --ctx-size 4096 \
  --temp 0.7 \
  --top-p 0.9 \
  --repeat-penalty 1.1 \
  --color
```

### 服务器模式（兼容 OpenAI API）

```bash
./build/bin/server \
  -m ./models/llama-2-7b-chat.Q4_K_M.gguf \
  --predictor-path ./predictors/llama-2-7b-chat \
  --gpu-layers 20 \
  --host 0.0.0.0 \\
  --port 8080 \
  --ctx-size 4096
```

***

## 优化 GPU 层切分

该 `--gpu-layers` 参数决定要在 GPU 上保留多少个 Transformer 层。请根据你的 VRAM 进行调优：

```bash
# 检查可用 VRAM
nvidia-smi --query-gpu=memory.free,memory.total --format=csv

# Q4 模型的经验法则：
# 7B：每层约 0.13GB → 24GB 显卡 = 约 184 层（全部）
# 13B：每层约 0.18GB → 24GB 显卡 = 约 133 层
# 70B：每层约 0.23GB → 24GB 显卡 = 约 104 层（总共 80 层）
```

**层分配指南：**

| GPU 显存 | 7B 模型  | 13B 模型 | 34B 模型 | 70B 模型 |
| ------ | ------ | ------ | ------ | ------ |
| 8GB    | 全部（32） | 20 层   | 10 层   | 4 层    |
| 16GB   | 全部（32） | 全部（40） | 25 层   | 10 层   |
| 24GB   | 全部（32） | 全部（40） | 全部（60） | 20 层   |
| 48GB   | 全部（32） | 全部（40） | 全部（60） | 全部（80） |

***

## 性能基准

### 吞吐量对比（Llama 2 70B，RTX 3090）

| 引擎               | GPU 层数          | 每秒 Token 数   |
| ---------------- | --------------- | ------------ |
| llama.cpp（仅 GPU） | 20/80           | 约 4 t/s      |
| llama.cpp（仅 CPU） | 0/80            | 约 1 t/s      |
| **PowerInfer**   | **20/80 + 预测器** | **约 12 t/s** |

{% hint style="success" %}
**3 倍加速** 对于在消费级 GPU 上进行大模型推理，借助 PowerInfer 的神经元感知调度，通常可比标准 llama.cpp 快 3 倍。
{% endhint %}

***

## 作为服务运行

创建一个 systemd 服务以持续提供 API：

```bash
cat > /etc/systemd/system/powerinfer.service << 'EOF'
[Unit]
Description=PowerInfer LLM 服务器
After=network.target

[Service]
Type=simple
WorkingDirectory=/app/PowerInfer
ExecStart=/app/PowerInfer/build/bin/server \
  -m /models/llama-2-13b-chat.Q4_K_M.gguf \
  --predictor-path /predictors/llama-2-13b-chat \
  --gpu-layers 30 \
  --host 0.0.0.0 \\
  --port 8080 \
  --ctx-size 4096
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable powerinfer
systemctl start powerinfer
systemctl status powerinfer
```

***

## API 使用

服务器运行后，使用任何兼容 OpenAI 的客户端：

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://<clore-node-ip>:<port>/v1",
    api_key="none"
)

response = client.chat.completions.create(
    model="local-model",
    messages=[
        {"role": "user", "content": "简要解释一下神经网络"}
    ],
    max_tokens=256
)
print(response.choices[0].message.content)
```

***

## 故障排查

### CUDA 显存不足

```bash
# 减少 GPU 层数
./build/bin/main -m model.gguf --gpu-layers 10  # 从 20 减少

# 检查哪些进程在使用 VRAM
nvidia-smi

# 清理 GPU 内存
sudo fuser -v /dev/nvidia*  # 查看进程
```

### CPU 推理速度慢

```bash
# 启用 CPU 线程优化
./build/bin/main -m model.gguf --threads $(nproc) --gpu-layers 20

# 检查 NUMA 拓扑
numactl --hardware

# 绑定到最靠近 GPU 的 NUMA 节点
numactl --cpunodebind=0 --membind=0 ./build/bin/main -m model.gguf
```

### 构建失败

```bash
# 确保已安装 CUDA 工具包
nvcc --version

# 检查 CMake 版本（需要 3.14+）
cmake --version

# 清理后重新构建
rm -rf build && mkdir build
cd build && cmake .. -DLLAMA_CUBLAS=ON -DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda
```

{% hint style="danger" %}
**常见问题：** 如果 `cmake` 找不到 CUDA，请设置 `CUDA_HOME` 环境变量： `export CUDA_HOME=/usr/local/cuda` 然后再运行 cmake。
{% endhint %}

***

## Clore.ai GPU 推荐

PowerInfer 的 CPU/GPU 混合设计改变了运行大模型的经济性。具有高 VRAM GPU 且 CPU 速度快的 Clore.ai 服务器是理想选择。

| GPU       | 显存    | Clore.ai 价格                       | 最大模型（Q4）        | 吞吐量（Llama 2 70B Q4） |
| --------- | ----- | --------------------------------- | --------------- | ------------------- |
| RTX 3090  | 24 GB | $0.07–0.21/小时                     | 70B（64GB+ RAM）  | 约 8–12 tok/s        |
| RTX 4090  | 24 GB | $0.14–0.42/小时                     | 70B（更快的 CPU 卸载） | 约 12–18 tok/s       |
| A100 40GB | 40 GB | [裸机](https://clore.ai/bare-metal) | 70B（最小卸载）       | 约 35–45 tok/s       |
| A100 80GB | 80 GB | [裸机](https://clore.ai/bare-metal) | 70B 全精度         | 约 50–60 tok/s       |

{% hint style="info" %}
**PowerInfer 的最佳场景：** 以 0.07–0.21 美元/小时的价格租用 RTX 3090 来运行 Llama 2 70B Q4，对预算有限的用户来说是一次突破。你能以比 A100 租用成本低 10–12 倍的价格获得一个 70B 模型。吞吐量较低（约 10 tok/s），但对于研究或低流量推理而言，其价值无可匹敌。
{% endhint %}

**CPU 和 GPU 一样重要：** PowerInfer 会将“冷”神经元卸载到 CPU。配备 AMD EPYC 或 Intel Xeon CPU（多核心、高内存带宽）的 Clore.ai 服务器会显著优于单路消费级 CPU。租用大模型工作负载前，请检查服务器规格。

**内存带宽瓶颈：** 对于 70B 模型，在冷神经元计算期间，CPU RAM 带宽是限制因素。配备 DDR5 ECC RAM 或接近 HBM 架构的服务器会获得更好的吞吐量。

***

## 资源

* 🐙 **GitHub：** [github.com/SJTU-IPADS/PowerInfer](https://github.com/SJTU-IPADS/PowerInfer)
* 📄 **研究论文：** [PowerInfer：使用消费级 GPU 实现大语言模型快速服务](https://arxiv.org/abs/2312.12456)
* 🤗 **GGUF 模型：** [huggingface.co/TheBloke](https://huggingface.co/TheBloke)
* 🧩 **SJTU IPADS 实验室：** [ipads.se.sjtu.edu.cn](https://ipads.se.sjtu.edu.cn)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/powerinfer.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
