> 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/mlc-llm.md).

# MLC-LLM

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

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

***

## 什么是 MLC-LLM？

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

### 主要能力

* **通用硬件支持** — NVIDIA CUDA、AMD ROCm、Apple Metal、Vulkan、WebGPU
* **兼容 OpenAI 的 REST API** — 可直接替代现有工作流
* **多种模型格式** — Llama、Mistral、Gemma、Phi、Qwen、Falcon 等更多
* **4 位 / 8 位量化** — 在消费级 GPU 上运行大型模型
* **聊天界面** — 内置 Web 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 VRAM** （7B+ 模型建议 16GB+）
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.8.1-devel-ubuntu22.04` 作为你在 Clore.ai 上的基础镜像。
{% endhint %}

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

```
Docker 镜像：nvidia/cuda:12.8.1-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": "写一个关于人工智能的短故事。"}],
    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+ VRAM 或多 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 支持多种量化方案。请根据你的 VRAM 预算进行选择：

| 量化        | 位数          | 质量    | VRAM（7B） | VRAM（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" %}
**VRAM 建议：** 始终为 CUDA 开销和 KV 缓存预留 2–3GB 余量。一个带有 `q4f16_1` 的 7B 模型在典型负载下总共需要约 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 包含内置 Web UI，服务器运行后即可访问：

```bash
# 启用 Web 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
# 增大批大小以提高吞吐量（需要更多 VRAM）
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 time
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/秒")
```

***

## Docker Compose 设置

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

```yaml
version: '3.8'
services:
  mlc-llm:
    image: nvidia/cuda:12.8.1-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.8 服务器，安装：
pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cu121 mlc-ai-nightly-cu121

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

{% hint style="danger" %}
**常见陷阱：** MLC-LLM 的 pip 轮子与 CUDA 版本相关。请务必安装与你服务器 CUDA 版本匹配的正确变体。可在以下位置查看可用轮子 [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       | 显存    | Clore.ai 价格                       | 最适合             | 吞吐量（Llama 3 8B Q4） |
| --------- | ----- | --------------------------------- | --------------- | ------------------ |
| RTX 3090  | 24 GB | $0.07–0.21/小时                     | 7B–13B 模型，经济型服务 | \~85 tok/s         |
| RTX 4090  | 24 GB | $0.14–0.42/小时                     | 7B–34B 模型，快速服务  | \~140 tok/s        |
| A100 40GB | 40 GB | [裸机](https://clore.ai/bare-metal) | 34B–70B，生产级 API | \~110 tok/s        |
| A100 80GB | 80 GB | [裸机](https://clore.ai/bare-metal) | 70B+，多模型服务      | \~130 tok/s        |
| H100 SXM  | 80 GB | \~$1.04/小时                        | 最高吞吐量，FP8       | 约280 tok/s         |

**推荐起点：** 以 $0.07–0.21/小时的价格，RTX 3090 是通过 MLC-LLM 提供 Llama 3 8B 和 Mistral 7B 服务的最佳性价比选择。编译后的内核能从消费级 GPU 中提取接近最大化的利用率。

对于 70B 模型（例如 Llama 3 70B Q4）：使用 A100 40GB（[裸机](https://clore.ai/bare-metal)）或通过张量并行使用两张 RTX 3090。

***

## 资源

* 📦 **Pip 轮子：** [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)


---

# 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/mlc-llm.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.
