# ModelLink
**Repository Path**: gitjunc/ModelLink
## Basic Information
- **Project Name**: ModelLink
- **Description**: 昇腾大模型仓库 LLM
- **Primary Language**: Python
- **License**: MIT
- **Default Branch**: modellink
- **Homepage**: https://gitee.com/ascend/ModelLink/
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1133
- **Created**: 2024-03-01
- **Last Updated**: 2024-05-29
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
简体中文 |
English
ModelLink旨在为华为 [昇腾芯片](https://open.codehub.huawei.com/OpenBaize/Ascend/ascendspeed/files?ref=master&filePath=examples%2Fbaichuan%2Fpretrain_baichuan_zero_7B.sh&isFile=true) 上的大语言模型提供端到端的解决方案, 包含模型,算法,算子,以及下游任务。
## ModelLink解决方案概览
---
### 大语言模型
当前ModelLink支持下列模型的预训练以及全参微调:
* Aquila-[[使用说明: 7B]](examples/aquila/README.md)
* Baichuan-[[使用说明: 7B/13B]](examples/baichuan/README.md)
* Bloom-[[使用说明: 7B/176B]](examples/bloom/README.md)
* InternLM-[[使用说明: 7B/65B]](examples/intern/README.md)
* LLaMA-[[使用说明: 7B/13B/33B/65B]](examples/llama/README.md)
* LLaMA2-[[使用说明: 7B/13B/34B/70B]](examples/llama2/README.md)
* Baichuan2-[[使用说明: 7B/13B]](examples/baichuan2/README.md)
* Qwen-[[使用说明: 7B/14B]](examples/qwen/README.md)
### 下游任务
当前ModelLink为大模型提供以下周边应用:
* [指令/预训练数据集](#jump11)
* [低参微调方法](#jump12)
* [推理:人机对话](#jump13)
* [基线数据集评估](#jump14)
强化学习,多专家网络等特性持续研发中....
### 融合算子
即将上线 ...
## 大语言模型
---
### 模型性能
### 模型训练软件配套
| 软件 | [版本](https://www.hiascend.com/zh/) |
|:-------------------------:|:------------------------------------------------------------------------------------------------------------------------------------:|
| Python | 3.8.18 |
| driver | 2023Q4商发 |
| firmware | 2023Q4商发 |
| CANN | 2023Q4商发 |
| binary arithmetic package | 2023Q4商发 |
| torch | 2.1.0 |
| torch_npu | 2023Q4商发 |
## 下游任务
---
### 内容列表
### 指令/预训练数据集
#### 快速开始
```bash
# 对于llama, 可以下载alpaca数据集, 比如
wget https://huggingface.co/datasets/tatsu-lab/alpaca/resolve/main/data/train-00000-of-00001-a09b74b3ef9c3b56.parquet
# 下载 tokenizer 配置, 地址:
# https://huggingface.co/yahma/llama-7b-hf/tree/main
# 这里要将tokenizer_config.json中的"LLaMATokenizer"修改为"LlamaTokenizer"(这是huggingface的一个bug)
mkdir dataset
python tools/preprocess_data.py --input train-00000-of-00001-a09b74b3ef9c3b56.parquet \
--output-prefix dataset/alpaca \
--tokenizer-type PretrainedFromHF \
--tokenizer-name-or-path llama-7b-hf \
--tokenizer-not-use-fast \
--handler-name GeneralInstructionHandler
```
#### 处理预训练数据集
##### wikipedia 数据集
+ 下载 [wikipedia](https://huggingface.co/datasets/wikipedia/tree/main) 数据集到 WORKSPACE/wikipedia 目录
+ 下载 [llama tokenizer](https://huggingface.co/yahma/llama-7b-hf/tree/main) 配置到 WORKSPACE/llama-7b-hf 目录
+ 再使用如下脚本处理数据集
```shell
# 这里认为 数据集 和 tokenizer 已经下载放到了 WORKSPACE.
cd WORKSPACE
mkdir wikipedia_preprocessed
hf_config_json="./hf_config_json.json"
cat < $hf_config_json
{
"path": "WORKSPACE/wikipedia",
"name": "20220301.en",
"streaming: True,
"split": "train"
}
EOT
python tools/preprocess_data.py \
--input "WORKSPACE/wikipedia" \
--hf-datasets-params ${hf_config_json} \
--output-prefix WORKSPACE/wikipedia_preprocessed/wikipedia \
--dataset-impl mmap \
--tokenizer-type PretrainedFromHF \
--tokenizer-name-or-path WORKSPACE/llama-7b-hf \
--tokenizer-not-use-fast \
--streaming \
--workers 8
```
处理完后, `WORKSPACE/wikipedia_preprocessed` 文件夹下会有 `wikipedia_text_document.bin` 和 `wikipedia_text_document.idx` 文件, 我们便可以使用 `--data-path WORKSPACE/wikipedia_preprocessed/wikipedia_text_document` 标志训练模型了
请注意huggingface中的数据集格式是[这样](https://huggingface.co/datasets/wikipedia/viewer/20220301.en/train)的. 我们处理数据时利用的数据列可以通过 `--json-key` 标志设置,默认为 `text`,
比如,wikipedia数据集有四列, 包括 `id`, `url`, `title` 和 `text`, 我们就可以通过 `--json-key` 标志选择一列处理该数据集
##### alpaca 数据集
此外, 我们也可以使用 [alpaca](https://huggingface.co/datasets/tatsu-lab/alpaca/resolve/main/data/train-00000-of-00001-a09b74b3ef9c3b56.parquet) 数据集用于预训练如下:
```shell
python tools/preprocess_data.py --input WORKSPACE/train-00000-of-00001-a09b74b3ef9c3b56.parquet \
--output-prefix WORKSPACE/alpaca_preprocessed/alpaca \
--tokenizer-type PretrainedFromHF \
--tokenizer-name-or-path WORKSPACE/llama-7b-hf \
--tokenizer-not-use-fast \
--json-key text
```
#### 处理指令微调数据集
##### alpaca 数据集
```bash
# 数据集:wget https://huggingface.co/datasets/tatsu-lab/alpaca/resolve/main/data/train-00000-of-00001-a09b74b3ef9c3b56.parquet
cd WORKSPACE
mkdir alpaca_preprocessed
python tools/preprocess_data.py --input WORKSPACE/alpaca/train-00000-of-00001-a09b74b3ef9c3b56.parquet \
--output-prefix WORKSPACE/alpaca_preprocessed/alpaca \
--tokenizer-type PretrainedFromHF \
--tokenizer-name-or-path WORKSPACE/llama-7b-hf \
--tokenizer-not-use-fast \
--handler-name GeneralInstructionHandler \
--append-eod
```
在处理后,`WORKSPACE/alpaca_preprocessed` 文件夹下会有3个 `bin` 文件 和 3个 `idx` 文件,我们便可以通过添加 `--data-path WORKSPACE/alpaca_preprocessed/alpaca` 和 `--is-instruction-dataset` 标志来进行指令微调。
此外,基于指令数据集,我们还可以通过加上 `--variable-seq-lengths` 标志使用动态序列长度训练模型。
请注意,使用 `--handler-name GeneralInstructionHandler` 标志的指令数据集,在处理时会从 `modellink/data/data_handler.py` 中选择 `GeneralInstructionHandler` 类来制作prompt。如果你处理的是 alpaca 格式风格的数据集,即包含 `instruction`, `input` 和 `output` 列的数据集,可以直接使用 `--handler-name GeneralInstructionHandler` 标志。
此外,`BelleMultiTurnInstructionHandler` 可以被用于处理 [belle](https://huggingface.co/datasets/BelleGroup/multiturn_chat_0.8M) 格式的数据集,`MOSSInstructionHandler` 可以被用于处理 [MOSS](https://huggingface.co/datasets/fnlp/moss-003-sft-data) 格式的数据集,`LeetcodePythonInstructionHandler` 可以被用于处理 [Leetcode](https://huggingface.co/datasets/mhhmm/leetcode-solutions-python) 风格的数据集
### 低参微调
#### Lora
当前 ModelLink基于 peft 仓库支持对大模型的 Lora 微调功能:
```shell
pip install peft==0.4.0
```
当torch==1.11.0的时候,你也可以选择直接从它Github仓库的 [源码安装](https://github.com/huggingface/peft/archive/refs/tags/v0.4.0.tar.gz), 通过修改它的setup.py文件来回避一些依赖问题。
之后,你仅仅只需要在启动脚本中使能如下标志便可以启动lora微调训练:
```shell
# Llama example
--lora-target-modules query_key_value dense gate_proj dense_h_to_4h dense_4h_to_h \
```
Lora有一些相关参数,在 [PEFT](https://github.com/huggingface/peft) 仓库中有详细介绍,比如:
```shell
# Llama example
--lora-r 64 \
--lora-alpha 128 \
--lora-modules-to-save word_embeddings output_layer \
--lora-register-forward-hook word_embeddings input_layernorm \
```
在这些参数中,标志 `--lora-register-forward-hook` 被用于修复由PP造成的梯度链中断,它仅仅只需要在每一个PP阶段的输入层设置,并不会增加训练参数。 标志 `--lora-modules-to-save` 被用于扩展词表时的微调,若没此需求则无需传入此参数。
最后,Lora微调后保存的权重仅仅只会包含新增的Lora权重。相似的,当你加载一个Lora模型时,除了原始权重路径需要设置,还需要设置一个加载Lora权重的路径,如下:
```shell
--load ${ORIGIN_CHECKPOINT} \
--lora-load ${LORA_CHECKPOINT} \
```
这个 [例子](examples/llama/tune_llama_ptd_13b.sh) 可以用于参考。
在使用 Lora 微调 Llama 模型以后,指令对话的效果如下:
```shell
You >> Give three tips for staying healthy.
ModelLink:
- Start exercising regularly and eat healthy food.
- Get a good eight hours of sleep each night.
- Take medications regularly.
```
如果在完成lora微调后,需要一个不带lora结构的模型,那么我们只需运行这个 [脚本](tools/lora/merge_lora_llama_ptd_13B.sh),即可将`--load`和`--lora-load`这两个模型文件合并,生成的不带lora结构的新权重模型文件存在`--save`路径里。
### 推理: 人机对话
当前,我们支持使用如下并行策略训练的模型进行推理:
- 仅仅使用 PTD 策略训练的模型
- 使用 Lora 策略微调的模型
#### 快速开始
这里有一些使用不同模式的样例脚本可以尝试运行,***请注意:***
1. 如果你尝试使用 huggingface 的模型权重,请首先进行权重转换, 以 Llama-7B 为例:
- PTD 策略的转换
```bash
python tools/checkpoint/util.py --model-type GPT \
--loader llama2_hf \
--saver megatron \
--target-tensor-parallel-size 2 \
--target-pipeline-parallel-size 2 \
--load-dir ./model_from_hf/llama-7b-hf \
--save-dir ./model_weights/llama-7b-tp2-pp2 \
--tokenizer-model ./model_from_hf/llama-7b-hf/tokenizer.model
```
5. 下面脚本中的一些路径需要修改,比如:模型权重路径 和 词表路径.
- 仅仅使用 PTD 策略训练的模型:在这种模式下,模型以 Megatron-LM 的风格被 流水并行 和 张量并行 切分
```bash
sh tasks/inference/generate_llama_7B_ptd.sh
```
- 如果你仅仅使用 Lora, 可以参考:
```bash
sh tasks/inference/generate_llama_7b_lora_ptd.sh
```
#### 使用手册
这里列举了一些使用 [Chinese-LLaMA-Alpaca-13B](https://github.com/ymcui/Chinese-LLaMA-Alpaca) 权重进行推理的例子,
同时依据下列步骤可以写出你自己的推理例子:
##### 初始化分布式环境
```python
initialize_megatron(args_defaults={'no_load_rng': True, 'no_load_optim': True})
```
##### 初始化模型和权重
```python
from modellink import get_args
from modellink.model import GPTModel
from modellink.arguments import core_transformer_config_from_args
def model_provider(pre_process=True, post_process=True):
"""Build the model."""
config = core_transformer_config_from_args(get_args())
init_model = GPTModel(
config,
num_tokentypes=0,
parallel_output=False,
return_moe_loss=False,
pre_process=pre_process,
post_process=post_process
)
return init_model
model = GPTModel.from_pretrained(
model_provider=model_provider,
pretrained_model_name_or_path="your model weight path"
)
"""
This is an API for initializing model and loading weight.
Parameters:
----------
model_provider(`func`):
Function used to generate model objects which is similar to the training define.
pretrained_model_name_or_path(`str`, *optional*, defaults to None):
File path of Model weight in megatron format (TP, PP may be used).
If it is None, the random initialized weights will be used.
"""
```
##### 以 HuggingFace 的风格生成文本
- Greedy Search
```python
responses = model.generate(
"Write quick sort code in python",
max_new_tokens=512
)
```
- Do sample with top-k and top-p
```python
responses = model.generate(
"Write quick sort code in python",
do_sample=True,
temperature=1.0,
top_k=50,
top_p=0.95,
max_new_tokens=512
)
```
- Beam search with top-k and top-p
```python
responses = model.generate(
"Write quick sort code in python",
num_beams=4,
top_k=50,
top_p=0.95,
max_new_tokens=512
)
```
- Beam search with top-k and top-p sampling
```python
responses = model.generate(
"Write quick sort code in python",
do_sample=True,
temperature=0.6,
num_beams=4,
top_k=50,
top_p=0.95,
max_new_tokens=512
)
```
### 使用基线数据集进行评估
#### 评估样例
#### 快速开始
```bash
# 配置模型和词表路径
# 词表路径地址:https://huggingface.co/yahma/llama-7b-hf
CHECKPOINT=../models/llama-7b-tp2-pp4/
VOCAB_FILE=../models/llama7b-hf/
# 配置任务和数据路径
DATA_PATH="dataset/boolq/test"
TASK="boolq"
# 配置生成参数
python -m torch.distributed.launch $DISTRIBUTED_ARGS evaluation_llama.py \
--task-data-path $DATA_PATH \
--task $TASK\
--seq-length 512 \
--max-new-tokens 1 \
--evaluation-batch-size 1 \
--max-position-embeddings 512 \
--tensor-model-parallel-size 2 \
--pipeline-model-parallel-size 4 \
--num-layers 32 \
--hidden-size 4096 \
--ffn-hidden-size 11008 \
--load ${CHECKPOINT[images](sources%2Fimages)} \
--num-attention-heads 32 \
--tokenizer-type PretrainedFromHF \
--tokenizer-name-or-path $VOCAB_FILE \
--tokenizer-not-use-fast \
--fp16 \
--micro-batch-size 1 \
--seed 42 | tee logs/train.log
# 开启评估
bash tasks/evaluation/eval_llama.sh
```
#### 任务介绍
最重要的评估参数是 `--max-new-tokens`, 它表示模型输出的生成长度,比如,多项选择问题的输出长度就会明显比编码任务的输出长度小,该参数也很大程度上影响了模型的生成速度。
```bash
python -m torch.distributed.launch $DISTRIBUTED_ARGS evaluation_llama.py \
--task-data-path $DATA_PATH \
--task $TASK\
--seq-length 512 \
--max-new-tokens 1 \
--evaluation-batch-size 1 \
--max-position-embeddings 512 \
--tensor-model-parallel-size 2 \
--pipeline-model-parallel-size 4 \
--num-layers 32 \
--hidden-size 4096 \
--ffn-hidden-size 11008 \
--load ${CHECKPOINT} \
--num-attention-heads 32 \
--tokenizer-type PretrainedFromHF \
--tokenizer-name-or-path $VOCAB_FILE \
--tokenizer-not-use-fast \
--fp16 \
--micro-batch-size 1 \
--seed 42 | tee logs/train.log
```
##### BoolQ
BoolQ 是一个 yes/no 的问答数据集, 每一个问题包含了一个(问题,文章,答案)三元组,同时有文章的标题作为额外的选择性输入。BoolQ 数据集的评估相对简单,只需要配置 `TASK="boolq"`, `--seq-length=512`, `--max-position-embeddings=512`, `--max-new-token=1`。
零样本评估的结果通常会被给定的 prompt 影响,可以尝试通过在 `tasks/evaluation/evaluation.py` 中设置合适的 prompt 得到更高的分数,
```bash
# 通过修改 template 更新prompt
template = {instruction}
```
##### MMLU
由于 MMLU 是一项多学科任务,并且需要进行 5-shot 评估,因此每个学科问题的长度差异很大。如果你想同时跑57个学科任务,可以尝试设置 `TASK="mmlu"`, `--seq-length=2048`, `--max-position-embeddings=2048`, `--max-new-token=1` 。
在很多网站,MMLU 的精度会依据学科进行评估,57个学科主要属于四个大类, 因此该数据集也可以基于四个大类进行打分,[网站](https://github.com/hendrycks/test/blob/master/categories.py) 给出了具体的57个类别。
##### GSM8K
GSM8K 是一个有8.5k高质量小学数学应用题文本的数据集,每一个问题的回答是具体的数字。由于该数据集通常采用 few-shot 的形式进行评估,GSM8K的问题长度相对是比较长的,输出答案包含一整个思维链路,相关入参应该设置为 `TASK="gsm8k"`, `--seq-length=2048`, `--max-position-embeddings=2048`, `--max-new-token=200`.
##### HumanEval
HumanEval 是一个用于挑战代码生成问题的数据集,具有164个编程问题,包含函数签名,文档,函数主体和单元测试等。该数据的所有问题都是手写的,以确保它们不在训练集中,由于答案包含长代码,相关参数可以设置为 `TASK="human_eval"`, `--seq-length=2048`,
`--max-position-embeddings=2048`, `--max-new-token=200`。
##### AGIEval
AGIEval 是一个用于评估大模型在人类认知和问题解决能力方面生成能力的基准数据集,它源于20个面向普通考生的官方、公开和高标准的入学和资格考试,相关参数可以设置为 `TASK="agieval"`, `--seq-length=2048`, `--max-position-embeddings=2048`, `--max-new-token=5`。
##### Big-Bench-Hard
Big-bench-hard 数据集是 BIG-Bench 的一个子集,专注于有挑战性的23个 BIG-Bench 任务, 涵盖文本理解、推理、逻辑推理、数学推理和常识推理等多个领域,相关参数可以设置为 `TASK="bbh"`, `--seq-length=2048`, `--max-position-embeddings=2048`, `--max-new-token=32`,`--evaluation-batch-size=4`。
##### CEval
如 [C-Eval](https://cevalbenchmark.com/) 展示的, C-Eval 是一个针对大模型的综合中文评估数据集, 它由13948道多项选择题组成,涵盖52个不同学科和4个难度级别,划分为验证和测试集,验证集包含标签用于个人评估,测试集合的标签没有公开,如果想要知道模型得分,需要将结果 邮件发送给 [C-Eval](https://cevalbenchmark.com/),相关参数可以设置为 `TASK="ceval"`, `--seq-length=2048`, `--max-position-embeddings=2048`, `--max-new-token=1`。
## 致谢
---
ModelLink由华为公司的下列部门联合贡献
:
- 昇腾计算产品线
- 计算算法部
- 计算研究部
- 开源计算工具部
- 公共开发部
- 全球技术服务部
感谢来自社区的每一个PR,欢迎贡献 ModelLink
## 备注
---
- 内部函数说明: [内部函数](https://gitee.com/ascend/AscendSpeed/wikis/Inner%20API%20Description/Some%20inner%20interface%20description?sort_id=8824096)
- 参数说明: [参数说明](https://gitee.com/ascend/AscendSpeed/wikis/Home)
- 许可描述: 在运行程序之前,建议您对训练所需的文件(如ckpt、日志等)采取权限控制(普通用户而不是root权限)等安全措施
- 路径描述: 当你使用 `torch.load` 接口时,除非 weights_only 参数被设置为 True, 否则请隐式的使用 pickle 模块,我们不建议您加载和使用任何来源未知或不可信任的数据
- 通信矩阵: [通信矩阵](https://gitee.com/ascend/AscendSpeed/wikis/Communition%20Matrix/AscendSpeed%20Communication%20Matrix?sort_id=8855822)
- 公网地址: [公网地址](public_address_statement.md)