# ExLlamaV2

使用 ExLlamaV2 以最大速度运行大型语言模型。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行： [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问您的服务器

* 在以下位置查找连接详情： **我的订单**
* Web 界面：使用 HTTP 端口的 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 ExLlamaV2？

ExLlamaV2 是用于大型语言模型的最快推理引擎：

* 比其他引擎快 2-3 倍
* 出色的量化（EXL2）
* 较低的显存使用
* 支持推测解码

## 要求

| 模型大小 | 最小显存 | 推荐      |
| ---- | ---- | ------- |
| 7B   | 6GB  | 按小时费率   |
| 13B  | 10GB | 速度      |
| 34B  | 20GB | 512x512 |
| 70B  | 40GB | 2s      |

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel
```

**端口：**

```
22/tcp
8080/http
```

**命令：**

```bash
pip install exllamav2 && \
huggingface-cli download turboderp/Llama2-7B-exl2 --local-dir ./model && \
python -m exllamav2.server --model_dir ./model --host 0.0.0.0 --port 8080
```

## 访问您的服务

部署后，在以下位置查找您的 `http_pub` URL： **我的订单**:

1. 前往 **我的订单** 页面
2. 单击您的订单
3. 查找 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 而不是 `localhost` 在下面的示例中。

## 安装

```bash

# 从 PyPI 安装
pip install exllamav2

# 或从源码安装（最新功能）
git clone https://github.com/turboderp/exllamav2
cd exllamav2
pip install .
```

## 下载模型

### EXL2 量化模型

```bash

# Llama 3.1 8B（4.0 bpw）
huggingface-cli download turboderp/Llama2-7B-exl2 \
    --revision 4.0bpw \
    --local-dir ./llama2-7b-exl2

# Llama 3.1 8B（4.0 bpw）
huggingface-cli download turboderp/Llama2-13B-exl2 \
    --revision 4.0bpw \
    --local-dir ./llama2-13b-exl2

# Mistral 7B（4.0 bpw）
huggingface-cli download turboderp/Mistral-7B-instruct-exl2 \
    --revision 4.0bpw \
    --local-dir ./mistral-7b-exl2

# Mixtral 8x7B
huggingface-cli download turboderp/Mixtral-8x7B-instruct-exl2 \
    --revision 4.0bpw \
    --local-dir ./mixtral-exl2
```

### 每权重位数（bpw）

| BPW | 质量      | 显存（7B） |
| --- | ------- | ------ |
| 2.0 | 低       | \~3GB  |
| 3.0 | 良好      | \~4GB  |
| 4.0 | 很棒      | \~5GB  |
| 5.0 | 优秀      | \~6GB  |
| 6.0 | 接近 FP16 | \~7GB  |

## Python API

### 基础生成

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config, ExLlamaV2Cache, ExLlamaV2Tokenizer
from exllamav2.generator import ExLlamaV2StreamingGenerator, ExLlamaV2Sampler

# 加载模型
config = ExLlamaV2Config()
config.model_dir = "./llama2-7b-exl2"
config.prepare()

model = ExLlamaV2(config)
model.load()

tokenizer = ExLlamaV2Tokenizer(config)
cache = ExLlamaV2Cache(model, lazy=True)

# 创建生成器
generator = ExLlamaV2StreamingGenerator(model, cache, tokenizer)

# 设置采样参数
settings = ExLlamaV2Sampler.Settings()
settings.temperature = 0.7
settings.top_k = 50
settings.top_p = 0.9

# 生成
prompt = "The future of artificial intelligence is"
output = generator.generate_simple(prompt, settings, num_tokens=200)
print(output)
```

### 流式生成

```python
from exllamav2.generator import ExLlamaV2StreamingGenerator

generator = ExLlamaV2StreamingGenerator(model, cache, tokenizer)

prompt = "Write a short story about a robot:"
input_ids = tokenizer.encode(prompt)

generator.set_stop_conditions([tokenizer.eos_token_id])
generator.begin_stream(input_ids, settings)

while True:
    chunk, eos, _ = generator.stream()
    if eos:
        break
    print(chunk, end="", flush=True)
```

### 聊天格式

```python
def format_chat(messages):
    text = ""
    for msg in messages:
        role = msg["role"]
        content = msg["content"]
        if role == "system":
            text += f"[INST] <<SYS>>\n{content}\n<</SYS>>\n\n"
        elif role == "user":
            text += f"{content} [/INST]"
        elif role == "assistant":
            text += f" {content}</s><s>[INST] "
    return text

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is Python?"}
]

prompt = format_chat(messages)
output = generator.generate_simple(prompt, settings, num_tokens=300)
```

## 服务器模式

### 启动服务器

```bash
python -m exllamav2.server \
    --model_dir ./llama2-7b-exl2 \
    --host 0.0.0.0 \
    --port 8080 \
    --max_seq_len 4096 \
    --cache_size 4096
```

### API 使用

```python
import requests

response = requests.post(
    "http://localhost:8080/v1/completions",
    json={
        "prompt": "Hello, how are you?",
        "max_tokens": 100,
        "temperature": 0.7
    }
)

print(response.json()["choices"][0]["text"])
```

### 聊天补全

```python
import openai

client = openai.OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="not-needed"
)

response = client.chat.completions.create(
    model="llama2-7b",
    messages=[{"role": "user", "content": "Hello!"}],
    temperature=0.7
)

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

## TabbyAPI（推荐的服务器）

TabbyAPI 提供功能丰富的 ExLlamaV2 服务器：

```bash

# 克隆 TabbyAPI
git clone https://github.com/theroyallab/tabbyAPI
cd tabbyAPI

# 安装
pip install -r requirements.txt

# 配置

# 在 config.yml 中编辑您的模型路径

# 运行
python main.py
```

### TabbyAPI 功能

* 兼容 OpenAI 的 API
* 支持多模型
* LoRA 热插拔
* 流式传输
* 函数调用
* 管理 API

## 预测性解码

使用更小的模型来加速生成：

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config, ExLlamaV2Cache

# 加载主模型（13B）
main_config = ExLlamaV2Config()
main_config.model_dir = "./llama2-13b-exl2"
main_config.prepare()
main_model = ExLlamaV2(main_config)
main_model.load()

# 加载草稿模型（7B）
draft_config = ExLlamaV2Config()
draft_config.model_dir = "./llama2-7b-exl2"
draft_config.prepare()
draft_model = ExLlamaV2(draft_config)
draft_model.load()

# 创建推测生成器
from exllamav2.generator import ExLlamaV2DraftGenerator

generator = ExLlamaV2DraftGenerator(
    main_model, draft_model,
    cache_main, cache_draft,
    tokenizer
)

# 生成（使用推测更快）
output = generator.generate_simple(prompt, settings, num_tokens=500)
```

## 对您自己的模型进行量化

### 转换为 EXL2

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config
from exllamav2.conversion import convert_model

# 来源：HuggingFace 模型

# 目标：EXL2 量化

convert_model(
    input_dir="./llama-3.1-8b-hf",
    output_dir="./llama-3.1-8b-exl2-4bpw",
    cal_dataset="wikitext",  # 校准数据集
    bits=4.0,  # 每权重位数
    head_bits=6,  # 注意力使用更高精度
)
```

### 命令行

```bash
python convert.py \
    -i ./llama-3.1-8b-hf \
    -o ./llama-3.1-8b-exl2 \
    -cf ./llama-3.1-8b-exl2 \
    -b 4.0 \
    -hb 6
```

## 内存管理

### 缓存分配

```python

# 固定缓存大小
cache = ExLlamaV2Cache(model, max_seq_len=4096)

# 动态缓存
cache = ExLlamaV2Cache(model, lazy=True)
cache.current_seq_len = 0  # 根据需要增长
```

### 多 GPU

```python
config = ExLlamaV2Config()
config.model_dir = "./large-model"

# 在多个 GPU 间拆分
config.set_auto_split([0.5, 0.5])  # 每个 GPU 各 50%

model = ExLlamaV2(config)
model.load()
```

## 性能比较

| A100         | 引擎        | GPU | 每秒标记数 |
| ------------ | --------- | --- | ----- |
| Llama 3.1 8B | ExLlamaV2 | 速度  | \~150 |
| Llama 3.1 8B | llama.cpp | 速度  | \~100 |
| Llama 3.1 8B | vLLM      | 速度  | \~120 |
| Llama 3.1 8B | ExLlamaV2 | 速度  | \~90  |
| Mixtral 8x7B | ExLlamaV2 | 2s  | \~70  |

## 高级设置

### 采样参数

```python
settings = ExLlamaV2Sampler.Settings()
settings.temperature = 0.7
settings.top_k = 50
settings.top_p = 0.9
settings.token_repetition_penalty = 1.1
settings.token_frequency_penalty = 0.0
settings.token_presence_penalty = 0.0
settings.mirostat = False
settings.mirostat_tau = 5.0
settings.mirostat_eta = 0.1
```

### 批量生成

```python
prompts = [
    "The meaning of life is",
    "Artificial intelligence will",
    "Climate change is"
]

outputs = []
for prompt in prompts:
    output = generator.generate_simple(prompt, settings, num_tokens=100)
    outputs.append(output)
```

## # 使用固定种子以获得一致结果

### CUDA 显存不足

```python

# 使用更小的缓存
cache = ExLlamaV2Cache(model, max_seq_len=2048)

# 或使用更低 bpw 的模型（使用 3.0 而不是 4.0）
```

### 加载缓慢

```python

# 启用快速加载
config.fasttensors = True
```

### 未找到模型

```bash

# 检查模型文件是否存在
ls ./model/

# 应包含：config.json、*.safetensors、tokenizer.json
```

## 与 LangChain 集成

```python
from langchain.llms.base import LLM
from typing import Optional, List

class ExLlamaV2LLM(LLM):
    model: ExLlamaV2
    tokenizer: ExLlamaV2Tokenizer
    generator: ExLlamaV2StreamingGenerator
    settings: ExLlamaV2Sampler.Settings

    @property
    def _llm_type(self) -> str:
        return "exllamav2"

    def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        return self.generator.generate_simple(prompt, self.settings, num_tokens=500)

# 用法
llm = ExLlamaV2LLM(model=model, tokenizer=tokenizer, generator=generator, settings=settings)
result = llm("What is quantum computing?")
```

## 下载所有所需的检查点

检查文件完整性

| GPU     | 验证 CUDA 兼容性 | 费用估算    | CLORE.AI 市场的典型费率（截至 2024 年）： |
| ------- | ----------- | ------- | ---------------------------- |
| 按小时费率   | \~$0.03     | \~$0.70 | \~$0.12                      |
| 速度      | \~$0.06     | \~$1.50 | \~$0.25                      |
| 512x512 | \~$0.10     | \~$2.30 | \~$0.40                      |
| 按日费率    | \~$0.17     | \~$4.00 | \~$0.70                      |
| 4 小时会话  | \~$0.25     | \~$6.00 | \~$1.00                      |

*RTX 3060* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

**A100 80GB**

* 使用 **竞价** 价格随提供商和需求而异。请查看
* 以获取当前费率。 **CLORE** 节省费用：
* 市场用于灵活工作负载（通常便宜 30-50%）

## 使用以下方式支付

* vLLM 推理 - 高吞吐量服务
* [llama.cpp 服务器](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/llamacpp-server) - 跨平台
* [文本生成 WebUI](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/text-generation-webui) - Web 界面


---

# Agent Instructions: 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:

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

The question should be specific, self-contained, and written in natural language.
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.
