# W8A8 LLM 模型部署

LMDeploy 提供了使用 8 bit 整数对神经网络模型进行量化和推理的功能。

在开始推理前，需要确保已经正确安装了 lmdeploy 和 openai/triton。可以通过以下命令进行安装：

```shell
pip install lmdeploy
pip install triton>=2.1.0
```

## 8bit 权重模型推理

如果你需要进行 8 bit 权重模型推理，可以直接从 LMDeploy 的 [model zoo](https://huggingface.co/lmdeploy) 下载已经量化好的 8bit 权重模型。以8bit 的 Internlm-chat-7B 模型为例，可以从 model zoo 直接下载：

```shell
git-lfs install
git clone https://huggingface.co/lmdeploy/internlm-chat-7b-w8 (coming soon)
```

你也可以参考["8bit 权重量化"](#8bit-权重量化)章节的内容手动将原 16bit 权重量化为 8bit，并保存至 `internlm-chat-7b-w8` 目录下，操作命令如下：

```shell
lmdeploy lite smooth_quant internlm/internlm-chat-7b --work-dir ./internlm-chat-7b-w8
```

然后，执行以下命令，即可在终端与模型对话：

```shell
lmdeploy chat ./internlm-chat-7b-w8 --backend pytorch
```

## 启动 gradio 服务

Coming soon...

## 推理速度

Coming soon...

## 8bit 权重量化

进行 8bit 权重量化需要经历以下三步：

1. **权重平滑**：首先对语言模型的权重进行平滑处理，以便更好地进行量化。
2. **模块替换**：使用 `QRSMNorm` 和 `QLinear` 模块替换原模型 `DecoderLayer` 中的 `RSMNorm` 模块和 `nn.Linear` 模块。`lmdeploy/pytorch/models/q_modules.py` 文件中定义了这些量化模块。
3. **保存量化模型**：完成上述必要的替换后，我们即可保存新的量化模型。

我们在`lmdeploy/lite/api/smooth_quantity.py`脚本中已经实现了以上三个步骤。例如，可以通过以下命令得到量化后的 Internlm-chat-7B 模型的模型权重：

```shell

lmdeploy lite smooth_quant internlm/internlm-chat-7b --work-dir ./internlm-chat-7b-w8
```

保存之后，你就可以通过调用from_pretrained接口来实例化你的量化模型。
