DeepSeek-7B-chat 4bits量化 QLora 微调

概述

本节我们简要介绍如何基于 transformers、peft 等框架,对 DeepSeek-7B-chat 模型进行 Lora 微调。Lora
是一种高效微调方法,深入了解其原理可参见博客:知乎|深入浅出Lora
本手册参考 https://github.com/datawhalechina/self-llm/blob/master/models/DeepSeek/

通过这种方式训练,可以用6G显存轻松训练一个7B的模型。

环境配置

在完成基本环境配置和本地模型部署的情况下,你还需要安装一些第三方库,可以使用以下命令:

pip install transformers==4.35.2
pip install peft==0.4.0
pip install datasets==2.10.1
pip install accelerate==0.20.3
pip install tiktoken
pip install transformers_stream_generator
pip install bitsandbytes==0.41.1

Deepseek-7B-Chat 模型下载指南

下载方式对比

方式优势适用场景
命令行下载支持增量更新完整模型部署
SDK下载自动依赖管理开发环境集成
Git LFS版本控制友好协同开发环境

1.命令行下载(推荐)

1.1 安装前置工具

pip install modelscope --upgrade

1.2 完整模型库下载

modelscope download --model deepseek-ai/deepseek-llm-7b-chat

1.3 单文件下载(示例:下载README)

modelscope download --model deepseek-ai/deepseek-llm-7b-chat README.md --local_dir ./target_folder

2.SDK集成下载

# 模型下载
from modelscope import snapshot_download

model_dir = snapshot_download('deepseek-ai/deepseek-llm-7b-chat')

3.Git LFS 下载

请确保 lfs 已经被正确安装

git lfs install
git clone https://www.modelscope.cn/deepseek-ai/deepseek-llm-7b-chat.git
cd deepseek-llm-7b-chat

指令集构建

LLM 的微调一般指指令微调过程。所谓指令微调,是说我们使用的微调数据形如:

{
  "instruction": "任务指令描述",
  "input": "任务输入内容",
  "output": "期望输出结果"
}

其中,instruction 是用户指令,告知模型其需要完成的任务;input 是用户输入,是完成用户指令所必须的输入内容;output是模型应该给出的输出。

即我们的核心训练目标是让模型具有理解并遵循用户指令的能力。因此,在指令集构建时,我们应针对我们的目标任务,针对性构建任务指令集。

数据格式化

Lora 训练的数据是需要经过格式化、编码之后再输入给模型进行训练的,如果是熟悉 Pytorch 模型训练流程的同学会知道,我们一般需要将输入文本编码为 input_ids,将输出文本编码为 labels,编码之后的结果都是多维的向量。我们首先定义一个预处理函数,这个函数用于对每一个样本,编码其输入、输出文本并返回一个编码后的字典:

def process_func(example):
    MAX_LENGTH = 384  # Llama分词器会将一个中文字切分为多个token,因此需要放开一些最大长度,保证数据的完整性
    input_ids, attention_mask, labels = [], [], []
    instruction = tokenizer(f"User: {example['instruction'] + example['input']}\n\n",
                            add_special_tokens=False)  # add_special_tokens 不在开头加 special_tokens
    response = tokenizer(f"Assistant: {example['output']}<|end▁of▁sentence|>", add_special_tokens=False)
    input_ids = instruction["input_ids"] + response["input_ids"] + [tokenizer.pad_token_id]
    attention_mask = instruction["attention_mask"] + response["attention_mask"] + [1]  # 因为eos token咱们也是要关注的所以 补充为1
    labels = [-100] * len(instruction["input_ids"]) + response["input_ids"] + [tokenizer.pad_token_id]
    if len(input_ids) > MAX_LENGTH:  # 做一个截断
        input_ids = input_ids[:MAX_LENGTH]
        attention_mask = attention_mask[:MAX_LENGTH]
        labels = labels[:MAX_LENGTH]
    return {
        "input_ids": input_ids,
        "attention_mask": attention_mask,
        "labels": labels
    }

这里的格式化输入参考了, DeepSeek 官方github仓库中readme的指令介绍。

User: {messages[0]['content']}

Assistant: {messages[1]['content']}<|end▁of▁sentence|>User: {messages[2]['content']}

Assistant:

加载tokenizer和半精度模型

模型以半精度形式加载,如果你的显卡比较新的话,可以用torch.bfolat形式加载。对于自定义的模型一定要指定trust_remote_code
参数为True

tokenizer = AutoTokenizer.from_pretrained('./deepseek-ai/deepseek-llm-7b-chat/', use_fast=False, trust_remote_code=True)
tokenizer.padding_side = 'right'  # padding在右边

model = AutoModelForCausalLM.from_pretrained(
    '/root/model/deepseek-ai/deepseek-llm-7b-chat/',
    trust_remote_code=True,
    torch_dtype=torch.half,
    device_map="auto",
    low_cpu_mem_usage=True,  # 是否使用低CPU内存
    load_in_4bit=True,  # 是否在4位精度下加载模型。如果设置为True,则在4位精度下加载模型。
    bnb_4bit_compute_dtype=torch.half,  # 4位精度计算的数据类型。这里设置为torch.half,表示使用半精度浮点数。
    bnb_4bit_quant_type="nf4",  # 4位精度量化的类型。这里设置为"nf4",表示使用nf4量化类型。
    bnb_4bit_use_double_quant=True  # 是否使用双精度量化。如果设置为True,则使用双精度量化。
)
model.generation_config = GenerationConfig.from_pretrained('/root/model/deepseek-ai/deepseek-llm-7b-chat/')
model.generation_config.pad_token_id = model.generation_config.eos_token_id

定义LoraConfig

LoraConfig这个类中可以设置很多参数,但主要的参数没多少,简单讲一讲,感兴趣的同学可以直接看源码。

  • task_type:模型类型
  • target_modules:需要训练的模型层的名字,主要就是attention部分的层,不同的模型对应的层的名字不同,可以传入数组,也可以字符串,也可以正则表达式。
  • rlora的秩,具体可以看Lora原理
  • lora_alphaLora alaph,具体作用参见 Lora 原理

Lora的缩放是啥嘞?当然不是r(秩),这个缩放就是lora_alpha/r, 在这个LoraConfig中缩放就是4倍。

config = LoraConfig(
    task_type=TaskType.CAUSAL_LM,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    inference_mode=False,  # 训练模式
    r=8,  # Lora 秩
    lora_alpha=32,  # Lora alaph,具体作用参见 Lora 原理
    lora_dropout=0.1  # Dropout 比例
)

自定义 TrainingArguments 参数

TrainingArguments这个类的源码也介绍了每个参数的具体作用,当然大家可以来自行探索,这里就简单说几个常用的。

  • output_dir:模型的输出路径
  • per_device_train_batch_size:顾名思义 batch_size
  • gradient_accumulation_steps: 梯度累加,如果你的显存比较小,那可以把 batch_size 设置小一点,梯度累加增大一些。
  • logging_steps:多少步,输出一次log
  • num_train_epochs:顾名思义 epoch
  • gradient_checkpointing:梯度检查,这个一旦开启,模型就必须执行model.enable_input_require_grads()
    ,这个原理大家可以自行探索,这里就不细说了。
  • optim="paged_adamw_32bit" 使用QLora的分页器加载优化器
args = TrainingArguments(
    output_dir="./output/DeepSeek",
    per_device_train_batch_size=8,
    gradient_accumulation_steps=2,
    logging_steps=10,
    num_train_epochs=3,
    save_steps=100,
    learning_rate=1e-4,
    save_on_each_node=True,
    gradient_checkpointing=True,
    optim="paged_adamw_32bit"  # 优化器类型
)

使用 Trainer 训练

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=tokenized_id,
    data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True),
)
trainer.train()

模型推理

可以用这种比较经典的方式推理:

text = ""  # 填写测试数据
inputs = tokenizer(f"User: {text}\n\n", return_tensors="pt")
outputs = model.generate(**inputs.to(model.device), max_new_tokens=100)

result = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(result)

写在最后

欢迎访问我们的项目Gitee仓库https://gitee.com/elon_z/HarmonySmartCoding以获取最新的进展和更新。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐