# Gemma-2
## 论文
- [Gemma 2: Improving Open Language Models at a Practical Size](https://storage.googleapis.com/deepmind-media/gemma/gemma-2-report.pdf)
## 模型结构
Gemma 2 与第一代有许多相似之处,使用transformer decoder结构进行训练。它有 8192 Tokens 的上下文长度,并使用旋转位置嵌入 (RoPE)。在7B模型中,Gemma 2使用了multi-head attention;而在2B模型中,它使用了multi-query attention(具有num_kv_heads = 1)。这种注意力机制有助于模型在处理文本数据时更好地捕捉相关信息。
Gemma 2不使用绝对位置编码,而是在每一层前加入RoPE Embedding,并共享输入与输出层的embedding权重。这种方法提高了模型的性能,并减少了计算量。
Gemma 2将ReLU的激活替换为GeGLU的激活。GeGLU是一种基于门控线性单元(GLU)的改进技术,具有更好的性能表现。
在transformer的每一层layer的前后都进行规一化,Gemma 2使用RMSNorm作为规一化层。这种规一化策略有助于提高模型的稳定性和性能。
## 算法原理
Gemma 2是由Google推出的一系列轻量级、最先进的开放模型,旨在推动负责任的AI创新。它基于与创建Gemini模型相同的研究和技术进行构建,提供了27B(270亿)参数大小的版本,具有出色的性能和效率。与原始 Gemma 相比,Gemma 2 的主要进展有四点:
+ 滑动窗口注意力: 交替使用滑动窗口和全二次注意力以提高生成质量。
+ Logit 软上限: 通过将 logits 缩放到固定范围来防止其过度增长,从而改进训练。
+ 知识蒸馏: 利用较大的教师模型来训练较小的模型(适用于 90 亿模型)。
+ 模型合并: 将两个或多个大语言模型合并成一个新的模型。
Gemma 2 Instruct 已针对对话应用进行了优化,并使用监督微调 (SFT)、大模型蒸馏、人类反馈强化学习 (RLHF) 和模型合并 (WARP) 来提高整体性能。
## 环境配置
### Docker(方法一)
提供[光源](https://www.sourcefind.cn/#/image/dcu/custom)拉取推理的docker镜像:
```
docker pull image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.3.0-py3.10-dtk24.04.3-ubuntu20.04-vllm0.6
# 用上面拉取docker镜像的ID替换
# 主机端路径
# 容器映射路径
# 若要在主机端和容器端映射端口需要删除--network host参数
docker run -it --name gemma2_vllm --privileged --shm-size=64G --device=/dev/kfd --device=/dev/dri/ --cap-add=SYS_PTRACE --security-opt seccomp=unconfined --ulimit memlock=-1:-1 --ipc=host --network host --group-add video -v /opt/hyhal:/opt/hyhal -v : /bin/bash
```
`Tips:若在K100/Z100L上使用,使用定制镜像docker pull image.sourcefind.cn:5000/dcu/admin/base/custom:vllm0.5.0-dtk24.04.1-ubuntu20.04-py310-zk-v1,K100/Z100L不支持awq量化`
### Dockerfile(方法二)
```
# 主机端路径
# 容器映射路径
docker build -t gemma2:latest .
docker run -it --name gemma2_vllm --privileged --shm-size=64G --device=/dev/kfd --device=/dev/dri/ --cap-add=SYS_PTRACE --security-opt seccomp=unconfined --ulimit memlock=-1:-1 --ipc=host --network host --group-add video -v /opt/hyhal:/opt/hyhal -v : gemma2:latest /bin/bash
```
### Anaconda(方法三)
```
conda create -n gemma2_vllm python=3.10
```
关于本项目DCU显卡所需的特殊深度学习库可从[光合](https://developer.hpccube.com/tool/)开发者社区下载安装。
* DTK驱动:dtk24.04.3
* Pytorch: 2.3.0
* triton: 2.1.0
* lmslim: 0.1.2
* flash_attn: 2.6.1
* vllm: 0.6.2
* python: python3.10
`Tips:需先安装相关依赖,最后安装vllm包`
## 数据集
无
## 推理
### 模型下载
**快速下载通道:**
| 基座模型 | SCnet快速下载链接 |
| ------- | ------- |
| [gemma-2-2b]| (http://113.200.138.88:18080/aimodels/gemma-2-2b)|
| [gemma-2-2b-it]| (http://113.200.138.88:18080/aimodels/gemma-2-2b-it)|
| [gemma-2-9b]| (http://113.200.138.88:18080/aimodels/gemma-2-9b)|
| [gemma-2-9b-it]| (http://113.200.138.88:18080/aimodels/gemma-2-9b-it)|
| [gemma-2-27b]| (http://113.200.138.88:18080/aimodels/google/gemma-2-27b)|
| [gemma-2-27b-it]| (http://113.200.138.88:18080/aimodels/gemma-2-27b-it)|
| 注 | 需要修改相应模型的config.json中"attn_logit_softcapping": null ;"final_logit_softcapping": null |
### 离线批量推理
```bash
python examples/offline_inference.py
```
其中,`prompts`为提示词;`temperature`为控制采样随机性的值,值越小模型生成越确定,值变高模型生成更随机,0表示贪婪采样,默认为1;`max_tokens=16`为生成长度,默认为1;
`model`为模型路径;`tensor_parallel_size=1`为使用卡数,默认为1;`dtype="float16"`为推理数据类型,如果模型权重是bfloat16,需要修改为float16推理,`quantization="gptq"`为使用gptq量化进行推理,需下载以上GPTQ模型。`quantization="awq"`为使用awq量化进行推理,需下载以上AWQ模型。
### 离线批量推理性能测试
1、指定输入输出
```bash
python benchmarks/benchmark_throughput.py --num-prompts 1 --input-len 32 --output-len 128 --model gemma-2-9b-it -tp 1 --trust-remote-code --enforce-eager --dtype float16
```
其中`--num-prompts`是batch数,`--input-len`是输入seqlen,`--output-len`是输出token长度,`--model`为模型路径,`-tp`为使用卡数,`dtype="float16"`为推理数据类型,如果模型权重是bfloat16,需要修改为float16推理。若指定`--output-len 1`即为首字延迟。`-q gptq`为使用gptq量化模型进行推理。
2、使用数据集
下载数据集:
```bash
wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
wget http://113.200.138.88:18080/aidatasets/anon8231489123/ShareGPT_Vicuna_unfiltered.git
```
```bash
python benchmarks/benchmark_throughput.py --num-prompts 1 --model gemma-2-9b-it --dataset ShareGPT_V3_unfiltered_cleaned_split.json -tp 1 --trust-remote-code --enforce-eager --dtype float16
```
其中`--num-prompts`是batch数,`--model`为模型路径,`--dataset`为使用的数据集,`-tp`为使用卡数,`dtype="float16"`为推理数据类型,如果模型权重是bfloat16,需要修改为float16推理。`-q gptq`为使用gptq量化模型进行推理。
### openAI api服务推理性能测试
1、启动服务端:
```bash
python -m vllm.entrypoints.openai.api_server --model gemma-2-9b-it --dtype float16 --enforce-eager -tp 1
```
2、启动客户端:
```bash
python benchmarks/benchmark_serving.py --model gemma-2-9b-it --dataset ShareGPT_V3_unfiltered_cleaned_split.json --num-prompts 1 --trust-remote-code
```
参数同使用数据集,离线批量推理性能测试,具体参考[benchmarks/benchmark_serving.py](benchmarks/benchmark_serving.py)
### OpenAI兼容服务
启动服务:
```bash
vllm serve gemma-2-9b-it --enforce-eager --dtype float16 --trust-remote-code --chat-template examples/template_gemma-it.jinja
```
这里serve之后为加载模型路径,`--dtype`为数据类型:float16,默认情况使用tokenizer中的预定义聊天模板,`--chat-template`可以添加新模板覆盖默认模板,`-q gptq`为使用gptq量化模型进行推理。
列出模型型号:
```bash
curl http://localhost:8000/v1/models
```
### OpenAI Completions API和vllm结合使用
```bash
curl http://localhost:8000/v1/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gemma-2-9b-it",
"prompt": "I believe the meaning of life is",
"max_tokens": 20,
"temperature": 0
}'
```
### OpenAI Chat API和vllm结合使用
```bash
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gemma-2-9b-it",
"messages": [
{"role": "system", "content": "I believe the meaning of life is"},
{"role": "user", "content": "I believe the meaning of life is"}
]
}'
```
### **gradio和vllm结合使用**
1.安装gradio
```
pip install gradio
```
2.安装必要文件
2.1 启动gradio服务,根据提示操作
```
python examples/gradio_openai_chatbot_webserver.py --model "gemma-2-9b-it" --model-url http://localhost:8000/v1 --temp 0.8 --stop-token-ids ""
```
2.2 更改文件权限
打开提示下载文件目录,输入以下命令给予权限
```
chmod +x frpc_linux_amd64_v0.*
```
2.3 端口映射
```
ssh -L 8000:计算节点IP:8000 -L 8001:计算节点IP:8001 用户名@登录节点 -p 登录节点端口
```
3.启动OpenAI兼容服务
```
vllm serve gemma-2-9b-it --enforce-eager --dtype float16 --trust-remote-code --port 8000 --host "0.0.0.0"
```
4.启动gradio服务
```
python examples/gradio_openai_chatbot_webserver.py --model "gemma-2-9b-it" --model-url http://localhost:8000/v1 --temp 0.8 --stop-token-ids --host "0.0.0.0" --port 8001
```
5.使用对话服务
在浏览器中输入本地 URL,可以使用 Gradio 提供的对话服务。
## result
使用的加速卡:1张 DCU-K100_AI-64G
```
Prompt: 'I believe the meaning of life is', Generated text: ' to find your purpose and live it to the fullest.\n\nThis purpose can be anything that brings you '
```
### 精度
无
## 应用场景
### 算法类别
对话问答
### 热点应用行业
金融,科研,教育
## 源码仓库及问题反馈
* [https://developer.hpccube.com/codes/modelzoo/gemma2_vllm](https://developer.hpccube.com/codes/modelzoo/gemma2_vllm)
## 参考资料
* [https://github.com/vllm-project/vllm](https://github.com/vllm-project/vllm)
* [https://github.com/chujiezheng/chat_templates/blob/main/chat_templates](https://github.com/chujiezheng/chat_templates/blob/main/chat_templates)