Tutorial6: qwen2-7b 推理和微调¶
本章旨在使用 Qwen2-7B-Instruct 模型展示模型对话、微调训练的过程。
分以下几步来实现:
环境安装与应用创建
下载模型
模型推理
模型微调
4.1 安装 LLaMA Factory
4.2 使用 LLaMA Factory 微调
合并 Lora 参数
加载合并后的模型
使用 Web UI
Qwen 系列模型是由阿里巴巴开发的。Qwen 模型系列包括不同规模的模型,参数范围从 0.5 到 720 亿,适用于各种应用场景,如文本生成、翻译、问答等。Qwen2-7B-Instruct 支持高达 131,072 个 token 的上下文长度,能够处理大量输入。
1. 环境安装与应用创建¶
首先在联网的命令行中创建conda环境:
conda create -n tutorial6 python=3.9
conda activate tutorial6
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
pip install notebook jupyterlab accelerate numpy==1.26.4 matplotlib==3.8.4 transformers==4.42.4
( pytorch 版本需与 cuda 版本对应,请查看版本对应网站:https://pytorch.org/get-started/previous-versions ,通过 nvidia-smi 命令可查看 cuda 版本)
然后创建JupyterLab应用, Conda环境名
请填写tutorial6
, 硬件资源建议使用一张A100或V100 32G。创建应用后, 进入应用并打开本文件。
CUDA Version: 12.1; Torch Version: 2.3.1
2. 下载模型¶
在联网的命令行中下载模型:
执行命令的路径为本文件所在文件夹下。
# 如果以下目录存在, 可以直接复制:
cp -r /lustre/public/tutorial/models/models--Qwen--Qwen2-7B-Instruct/ ./
# 否则请下载:
export HF_ENDPOINT=https://hf-mirror.com
huggingface-cli download --resume-download Qwen/Qwen2-7B-Instruct --local-dir models--Qwen--Qwen2-7B-Instruct
(建议使用 tmux 工具进行数据下载。tmux(Terminal Multiplexer)是一个终端复用器,它允许用户在一个单一终端会话中运行多个终端会话,并且它的会话可以在不同的时间和地点断开和重新连接,非常适合远程工作和需要长时间运行的任务。关于 tmux 的安装和介绍参考:https://tmuxcheatsheet.com/how-to-install-tmux ; 使用参考: https://tmuxcheatsheet.com)
3. 模型推理¶
运行以下代码:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# 加载模型和分词器
# VAR_PLACEHOLDER
model_path = "models--Qwen--Qwen2-7B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype="auto",
device_map="auto"
)
model.eval()
# 移动模型到 GPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# prompt
prompt = "介绍一下大模型"
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
# 对话
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(device)
generated_ids = model.generate(
model_inputs.input_ids,
max_new_tokens=512
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(
model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(
generated_ids, skip_special_tokens=True)[0]
print(response)
4. 模型微调¶
4.1 安装 LLaMA Factory¶
使用 LLaMA Factory 进行微调。
在联网的命令行中下载并安装LLaMA Factory:
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e ".[torch,metrics,deepspeed,qwen]"
4.2 使用 LLaMA Factory 微调¶
运行以下命令解压数据集并创建配置文件,再执行微调:
%%bash
tar -xzf data.tar.gz
echo "# 模型相对路径
model_name_or_path: models--Qwen--Qwen2-7B-Instruct
### method
stage: sft
do_train: true
finetuning_type: lora
lora_target: all
### dataset
dataset_dir: data/
dataset: my_identity
template: qwen
cutoff_len: 1024
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16
### output
output_dir: saves/Qwen2-7B-adapter # 微调参数保存路径
logging_steps: 10
save_steps: 500
plot_loss: true
overwrite_output_dir: true
### train
per_device_train_batch_size: 4
gradient_accumulation_steps: 8
learning_rate: 1.0e-4
num_train_epochs: 70.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
### eval
val_size: 0.1
per_device_eval_batch_size: 4
eval_strategy: steps
eval_steps: 500
" > qwen_finetune.yaml
llamafactory-cli train qwen_finetune.yaml
5. 合并 Lora 参数¶
创建配置文件并执行模型参数合并
%%bash
echo "model_name_or_path: models--Qwen--Qwen2-7B-Instruct
adapter_name_or_path: saves/Qwen2-7B-adapter # 微调参数路径
template: qwen
finetuning_type: lora
## export
export_dir: outputs/Qwen2-7B-Finetuned # 模型合并后导出路径
export_size: 2
export_device: auto
export_legacy_format: false" > qwen_merge.yaml
llamafactory-cli export qwen_merge.yaml
6. 加载合并后的模型¶
创建配置文件并进行微调后的模型的推理
%%bash
echo "# 模型路径
model_name_or_path: outputs/Qwen2-7B-Finetuned
template: qwen" > qwen-chat.yaml
llamafactory-cli chat qwen-chat.yaml
7. 使用 Web UI¶
上述过程也可以使用图形化的 webui 界面进行。执行下面命令,即可打开 webui 界面。为了避免路径错误,建议在加载模型、导出模型时使用绝对路径。
llamafactory-cli webui
作者: 黎颖; 龙汀汀
联系方式: yingliclaire@pku.edu.cn; l.tingting@pku.edu.cn