# MLC-LLM

**通过机器学习编译实现通用的 LLM 部署** — 使用机器学习编译在任何硬件上以最高性能运行任何大型语言模型。

> 🌟 **20,000+ GitHub 收藏星** | 由 MLC AI 团队维护 | Apache-2.0 许可证

***

## 什么是 MLC-LLM？

MLC-LLM（用于大型语言模型的机器学习编译）是一个通用框架，可实现大型语言模型在多种硬件后端上的高效部署。通过利用 **TVM（Tensor Virtual Machine）** 作为其编译后端，MLC-LLM 将 LLM 模型直接编译为本地硬件代码——在无需针对特定硬件进行工程优化的情况下实现接近最优的性能。

### 关键能力

* **通用硬件支持** — NVIDIA CUDA、AMD ROCm、Apple Metal、Vulkan、WebGPU
* **兼容 OpenAI 的 REST API** — 可作为现有工作流的无缝替代
* **多种模型格式** — Llama、Mistral、Gemma、Phi、Qwen、Falcon 等等
* **4 位 / 8 位 量化** — 在消费级 GPU 上运行大型模型
* **聊天界面** — 内置网页 UI 以便立即测试
* **Python 与 CLI 工具** — 灵活的集成选项

### 为什么在 Clore.ai 上使用 MLC-LLM？

Clore.ai GPU 市场为您提供具有竞争租金价格的高性能 NVIDIA GPU。MLC-LLM 的编译方法能从每块 GPU 中榨取最大吞吐量——使其非常适合于：

* 规模化的生产 API 推理
* 跨模型规模的研究与基准测试
* 使用量化模型的成本高效服务
* 在单个 GPU 实例上部署多模型

***

## 在 Clore.ai 上快速开始

### 步骤 1：查找 GPU 服务器

1. 前往 [clore.ai](https://clore.ai) 市场
2. 筛选服务器： **NVIDIA GPU**，最少 **8GB 显存** （建议 16GB+ 以运行 7B+ 模型）
3. 为获得最佳性能：RTX 3090、RTX 4090、A100 或 H100

### 步骤 2：部署 MLC-LLM

{% hint style="info" %}
**注意：** MLC-LLM 未在 Docker Hub 发布官方预构建的 Docker 镜像。推荐的部署方式是使用 NVIDIA CUDA 基础镜像并通过 pip 安装 MLC-LLM。使用 `nvidia/cuda:12.1.0-devel-ubuntu22.04` 作为您在 Clore.ai 上的基础镜像。
{% endhint %}

在您的 Clore.ai 订单配置中使用 NVIDIA CUDA 基础镜像：

```
Docker 镜像：nvidia/cuda:12.1.0-devel-ubuntu22.04
```

**端口映射：**

| 容器端口   | 用途           |
| ------ | ------------ |
| `22`   | SSH 访问       |
| `8000` | REST API 服务器 |

**推荐的环境变量：**

```
MLC_MODEL=HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC
MLC_HOST=0.0.0.0
MLC_PORT=8000
```

**启动脚本** （SSH 登录后运行）：

```bash
pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cu121 mlc-ai-nightly-cu121
```

### 步骤 3：通过 SSH 连接

```bash
ssh root@<clore-node-ip> -p <assigned-ssh-port>
```

***

## 安装与设置

### 选项 A：使用预编译模型（最快）

MLC-AI 在 Hugging Face 上维护着一库预编译模型。无需编译：

```bash
# 拉取并运行预编译的 Llama 3 8B（4 位量化）
python -m mlc_llm serve HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC \
  --host 0.0.0.0 \
  --port 8000
```

### 选项 B：编译您自己的模型

对于自定义模型或特定的量化需求：

```bash
# 第 1 步：转换模型权重
python -m mlc_llm convert_weight \
  ./path/to/model \
  --quantization q4f16_1 \
  --output ./compiled/model-q4f16_1

# 第 2 步：生成模型配置
python -m mlc_llm gen_config \
  ./path/to/model \
  --quantization q4f16_1 \
  --conv-template llama-3 \
  --output ./compiled/model-q4f16_1

# 第 3 步：编译模型
python -m mlc_llm compile \
  ./compiled/model-q4f16_1/mlc-chat-config.json \
  --device cuda \
  --output ./compiled/model-q4f16_1/lib.so
```

{% hint style="info" %}
**编译时间：** 在第一次运行时编译一个 7B 模型通常需要 10–30 分钟。编译产物会被缓存并在后续启动中重复使用。
{% endhint %}

***

## 运行 API 服务器

### 启动兼容 OpenAI 的服务器

```bash
python -m mlc_llm serve \
  HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC \
  --host 0.0.0.0 \
  --port 8000 \
  --max-batch-size 4 \
  --max-total-sequence-length 8192
```

### 服务器启动输出

```
[2024-01-01 12:00:00] INFO: 正在从 HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC 加载模型
[2024-01-01 12:00:15] INFO: 模型加载成功
[2024-01-01 12:00:15] INFO: 服务器已在 0.0.0.0:8000 启动
[2024-01-01 12:00:15] INFO: 兼容 OpenAI 的 API 可在 http://0.0.0.0:8000/v1 使用
```

### 可用的 API 端点

| 端点                           | 方法   | 描述              |
| ---------------------------- | ---- | --------------- |
| `/v1/chat/completions`       | POST | 聊天补全（OpenAI 格式） |
| `/v1/completions`            | POST | 文本补全            |
| `/v1/models`                 | GET  | 列出可用模型          |
| `/v1/debug/dump_event_trace` | GET  | 性能调试            |

***

## API 使用示例

### 聊天补全（Python）

```python
from openai import OpenAI

# 指向您的 Clore.ai 服务器
client = OpenAI(
    base_url="http://<clore-node-ip>:<api-port>/v1",
    api_key="none"  # 默认情况下 MLC-LLM 不要求身份验证
)

response = client.chat.completions.create(
    model="Llama-3-8B-Instruct-q4f16_1-MLC",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "用简单的语言解释量子计算。"}
    ],
    temperature=0.7,
    max_tokens=512
)

print(response.choices[0].message.content)
```

### 流式响应

```python
stream = client.chat.completions.create(
    model="Llama-3-8B-Instruct-q4f16_1-MLC",
    messages=[{"role": "user", "content": "写一个关于 AI 的短篇故事。"}],
    stream=True,
    max_tokens=1024
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

### cURL 示例

```bash
curl http://<clore-node-ip>:<api-port>/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Llama-3-8B-Instruct-q4f16_1-MLC",
    "messages": [
      {"role": "user", "content": "2+2 等于多少？"}
    ],
    "temperature": 0.7,
    "max_tokens": 100
  }'
```

***

## 可用的预编译模型

MLC-AI 在 Hugging Face 上提供可直接使用的已编译模型：

### Llama 3 系列

```bash
# 8B Instruct（推荐用于大多数使用场景）
HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC

# 70B Instruct（需要 40GB+ 显存或多 GPU）
HF://mlc-ai/Llama-3-70B-Instruct-q4f16_1-MLC
```

### Mistral / Mixtral

```bash
HF://mlc-ai/Mistral-7B-Instruct-v0.3-q4f16_1-MLC
HF://mlc-ai/Mixtral-8x7B-Instruct-v0.1-q4f16_1-MLC
```

### Gemma

```bash
HF://mlc-ai/gemma-2b-it-q4f16_1-MLC
HF://mlc-ai/gemma-7b-it-q4f16_1-MLC
```

### Phi

```bash
HF://mlc-ai/phi-2-q4f16_1-MLC
HF://mlc-ai/Phi-3-mini-4k-instruct-q4f16_1-MLC
```

{% hint style="success" %}
**完整模型列表：** 在以下地址浏览所有预编译模型： [huggingface.co/mlc-ai](https://huggingface.co/mlc-ai)
{% endhint %}

***

## 量化选项

MLC-LLM 支持多种量化方案。根据您的显存预算选择：

| 量化        | 位数          | 速度    | 显存（7B） | 显存（13B） |
| --------- | ----------- | ----- | ------ | ------- |
| `q4f16_1` | 4 位         | ★★★★☆ | ≈4GB   | \~7GB   |
| `q4f32_1` | 4 位（f32 累加） | ★★★★☆ | ≈4GB   | \~7GB   |
| `q8f16_1` | 8 位         | ★★★★★ | ≈8GB   | ≈14GB   |
| `q0f16`   | 16 位（无量化）   | ★★★★★ | ≈14GB  | \~26GB  |
| `q0f32`   | 32 位（无量化）   | ★★★★★ | \~28GB | \~52GB  |

{% hint style="warning" %}
**显存建议：** 始终留出 2–3GB 的余量以应对 CUDA 开销和 KV 缓存。带有 `q4f16_1` 在典型工作负载下大约需要 \~6–7GB 的总显存。
{% endhint %}

***

## 多 GPU 部署

对于需要多 GPU 的大型模型（70B+）：

```bash
# 在 2 块 GPU 上启用张量并行
python -m mlc_llm serve \
  HF://mlc-ai/Llama-3-70B-Instruct-q4f16_1-MLC \
  --host 0.0.0.0 \
  --port 8000 \
  --tensor-parallel-shards 2
```

在部署前检查 GPU 拓扑：

```bash
nvidia-smi topo -m  # 检查 NVLink/PCIe 互联
```

{% hint style="info" %}
**最佳性能：** 多 GPU 在 NVLink 互联的显卡（例如 A100 80GB SXM 配对）上表现最佳。通过 PCIe 互联的 GPU 在大型模型上会出现瓶颈。
{% endhint %}

***

## 网页聊天界面

MLC-LLM 包含一个内置网页 UI，服务器运行后可访问：

```bash
# 启用网页 UI 启动服务器
python -m mlc_llm serve \
  HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC \
  --host 0.0.0.0 \
  --port 8000 \
  --enable-debug  # 可选：启用调试端点
```

在以下地址访问 UI： `http://<clore-node-ip>:<api-port>`

***

## 性能调优

### 优化批量大小

```bash
# 增大批量大小以提高吞吐量（需要更多显存）
python -m mlc_llm serve \
  HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC \
  --host 0.0.0.0 \
  --port 8000 \
  --max-batch-size 8 \
  --max-total-sequence-length 16384 \
  --prefill-chunk-size 2048
```

### 监控 GPU 使用率

```bash
# 在另一个终端中
watch -n 1 nvidia-smi

# 更详细的监控
nvidia-smi dmon -s u  # 流式利用率指标
```

### 基准吞吐量测试

```python
import base64
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="none")

start = time.time()
response = client.chat.completions.create(
    model="Llama-3-8B-Instruct-q4f16_1-MLC",
    messages=[{"role": "user", "content": "从 1 数到 100"}],
    max_tokens=512
)
elapsed = time.time() - start

tokens = response.usage.completion_tokens
print(f"吞吐量: {tokens/elapsed:.1f} tokens/sec")
```

***

## Docker Compose 设置

对于在 Clore.ai 上使用 NVIDIA CUDA 基础镜像并通过 pip 安装 MLC-LLM 的生产就绪部署：

```yaml
version: '3.8'
services:
  mlc-llm:
    image: nvidia/cuda:12.1.0-devel-ubuntu22.04
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=all
    ports:
      - "8000:8000"
    volumes:
      - ./models:/root/models
      - mlc-cache:/root/.cache/mlc_llm
    command: >
      bash -c "pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cu121 mlc-ai-nightly-cu121 &&
      python -m mlc_llm serve
      HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC
      --host 0.0.0.0
      --port 8000
      --max-batch-size 4"
    restart: unless-stopped

volumes:
  mlc-cache:
```

***

## 故障排除

### 模型下载失败

```bash
# 检查网络连接
curl -I https://huggingface.co

# 使用 huggingface-cli 手动下载
pip install huggingface_hub
huggingface-cli download mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC
```

### 显存不足（OOM）

```bash
# 减少上下文长度
python -m mlc_llm serve MODEL \
  --max-total-sequence-length 4096  # 从默认值减少

# 使用更激进的量化
# 从 q8f16_1 切换到 q4f16_1
```

### CUDA 版本不匹配

```bash
# 检查 CUDA 版本
nvcc --version
nvidia-smi | grep CUDA

# 对于 CUDA 12.1 的服务器，安装：
pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cu121 mlc-ai-nightly-cu121

# 对于 CUDA 12.2+ 的服务器，安装：
pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cu122 mlc-ai-nightly-cu122
```

{% hint style="danger" %}
**常见陷阱：** MLC-LLM 的 pip wheel 与 CUDA 版本相关。请确保安装与服务器 CUDA 版本匹配的变体。可在以下位置查看可用的 wheel： [mlc.ai/wheels](https://mlc.ai/wheels).
{% endhint %}

### 服务器无法访问

```bash
# 验证端口是否在监听
ss -tlnp | grep 8000

# 检查防火墙
iptables -L -n | grep 8000

# 先在本地测试
curl http://localhost:8000/v1/models
```

***

## Clore.ai 的 GPU 建议

MLC-LLM 的编译方法能在所有 GPU 级别上提供接近最优的吞吐量。根据模型大小和预算进行选择：

| GPU               | 显存（VRAM） | Clore.ai 价格 | 适合用于            | 吞吐量（Llama 3 8B Q4） |
| ----------------- | -------- | ----------- | --------------- | ------------------ |
| RTX 3090          | 24 GB    | \~$0.12/小时  | 7B–13B 模型，预算型服务 | \~85 令牌/秒          |
| RTX 4090          | 24 GB    | \~$0.70/小时  | 7B–34B 模型，快速服务  | \~140 tok/s        |
| A100 40GB         | 40 GB    | \~$1.20/小时  | 34B–70B，生产 API  | \~110 tok/s        |
| 💡 本指南中的所有示例均可部署在 | 80 GB    | \~$2.00/小时  | 70B+，多模型服务      | \~130 tok/s        |
| H100 SXM          | 80 GB    | \~$3.50/小时  | 最大吞吐量，FP8       | \~280 令牌/秒         |

**推荐起点：** 对于通过 MLC-LLM 提供 Llama 3 8B 和 Mistral 7B 服务，RTX 3090（约 $0.12/小时）在性价比上表现最佳。已编译的内核能从消费级 GPU 中提取接近最大利用率。

对于 70B 模型（例如 Llama 3 70B Q4）：使用 A100 40GB（约 $1.20/小时）或通过张量并行使用两块 RTX 3090。

***

## 资源

* 📦 **Pip Wheels：** [mlc.ai/wheels](https://mlc.ai/wheels) （通过 pip 安装，未提供 Docker Hub 镜像）
* 🐙 **GitHub：** [github.com/mlc-ai/mlc-llm](https://github.com/mlc-ai/mlc-llm)
* 📚 **文档：** [llm.mlc.ai/docs](https://llm.mlc.ai/docs)
* 🤗 **预编译模型：** [huggingface.co/mlc-ai](https://huggingface.co/mlc-ai)
* 💬 **Discord：** [discord.gg/9Xpy2HGBuD](https://discord.gg/9Xpy2HGBuD)
