当前位置:   article > 正文

【机器学习】QLoRA:基于PEFT亲手量化微调Qwen2大模型_qlora微调

qlora微调

目录

一、引言

二、量化与微调—原理剖析

2.1 为什么要量化微调?

2.2 量化(Quantization)

2.2.1 量化原理

2.2.2 量化代码

2.3 微调(Fine-Tuning)

2.3.1 LoRA

2.3.2 QLoRA

三、量化与微调—实战演练:以Qwen2为例,亲手微调你的第一个AI大模型

3.1 模型预处理—依赖安装、库包导入、模型下载

3.2 模型预处理—加载量化模型

3.3 模型预处理—加载LoRA网络

3.4 数据预处理—下载、处理数据 

3.5 模型训练 

3.6 模型合并及推理

四、总结


一、引言

之前陆续写了Qwen1.5Qwen2.0GLM-4等国产开源大模型的原理、训练及推理相关的文章,每一篇都拿到了热榜第一,但其中训练部分均基于Llama-factory框架,对于工程师而言,最喜欢的就是刨根问底,使用中间层的训练框架,还是少一些“安全感”。今天我们抛开中间框架,深入底层,一步一步带大家微调一个大模型。

二、量化与微调—原理剖析

2.1 为什么要量化微调?

量化微调要解决的问题:全参数、高比特(32bit或16bit)微调训练需要大量的GPU显存资源,于是通过缩减参数位数(Quantization)以及缩减可训练参数规模(LoRA)等策略降低训练成本,达到全参数微调同等的效果。

如上图,针对一个7B的模型,全参数16位微调,需要60G显存,QLoRA4位微调仅需6GB,仅需要1/10。面对昂贵的GPU资源,量化微调技术真的是“知识解放生产力”的典范。下面分别讲解量化和微调的原理。

2.2 量化(Quantization)

2.2.1 量化原理

向量量化:int8/int4

通俗将就是将float16位浮点型转换为int8位整型,可以分为“0点量化zero-point”和“最大绝对值absmax”量化,下图是“最大绝对值absmax”量化的示例。

我们计划量化至int8的范围为[-127,127]:

  1. 取fp16向量的最大值5.4,127除以5.4得到23.5,作为缩放因子
  2. fp16向量的所有数乘以23.5得到int8的向量

反量化为FP16:

  1. 将int8的向量除以缩放因子23.5

矩阵量化(0退化)

经过证明,量化的损失是由离群点(偏离整体分布的点)特征导致的,于是设定一个异常阈值,将大于阈值的列抽离出来维持fp16,对小于异常阈值的矩阵进行量化计算,可以保证精度不丢失。动图演示如下:

抽取线性矩阵W、X的非离群值量化为int8:

  1. 从输入的隐含状态中,按列提取异常值 (即大于某个阈值的值)。
  2. 对 FP16 离群值矩阵和 Int8 非离群值矩阵分别作矩阵乘法。

反量化为FP16:

  1. 反量化非离群值的矩阵乘结果并其与离群值矩阵乘结果相加,获得最终的 FP16 结果。 

2.2.2 量化代码

bitsandbytes库:量化任何模型的最简单方法之一,与GGUF均属于零样本量化,不需要量化校准数据及校准过程(而AWQ和GPTQ等量化方啊均需要少量样本进行校准) 。任何模型只要含有 torch.nn.Linear 模块,就可以对其进行开箱即用的量化。

nf4/fp4量化代码,很简单,仅需要一个BitsAndBytesConfig配置即可使用。

  1. from transformers import AutoTokenizer, AutoModelForCausalLM,BitsAndBytesConfig
  2. ###int4量化配置
  3. quantization_config = BitsAndBytesConfig(
  4. load_in_4bit=True, # 或者 load_in_8bit=True,根据需要设置
  5. #llm_int8_threshold=6.0,
  6. #llm_int8_has_fp16_weight=False,
  7. bnb_4bit_compute_dtype=torch.float16,
  8. bnb_4bit_quant_type="nf4",#添加nf4配置,去掉为fp4
  9. bnb_4bit_use_double_quant=True,#添加nf4配置,去掉为fp4
  10. )
  11. model = AutoModelForCausalLM.from_pretrained(model_dir,device_map=device,trust_remote_code=True,torch_dtype=torch.float16,quantization_config=quantization_config)
  12. print(model)

输出模型结构,可以看到Attention和MLP层中的Linear线性层全部变成了linear4bit:

  1. Qwen2ForCausalLM(
  2. (model): Qwen2Model(
  3. (embed_tokens): Embedding(152064, 3584)
  4. (layers): ModuleList(
  5. (0-27): 28 x Qwen2DecoderLayer(
  6. (self_attn): Qwen2SdpaAttention(
  7. (q_proj): Linear4bit(in_features=3584, out_features=3584, bias=True)
  8. (k_proj): Linear4bit(in_features=3584, out_features=512, bias=True)
  9. (v_proj): Linear4bit(in_features=3584, out_features=512, bias=True)
  10. (o_proj): Linear4bit(in_features=3584, out_features=3584, bias=False)
  11. (rotary_emb): Qwen2RotaryEmbedding()
  12. )
  13. (mlp): Qwen2MLP(
  14. (gate_proj): Linear4bit(in_features=3584, out_features=18944, bias=False)
  15. (up_proj): Linear4bit(in_features=3584, out_features=18944, bias=False)
  16. (down_proj): Linear4bit(in_features=18944, out_features=3584, bias=False)
  17. (act_fn): SiLU()
  18. )
  19. (input_layernorm): Qwen2RMSNorm()
  20. (post_attention_layernorm): Qwen2RMSNorm()
  21. )
  22. )
  23. (norm): Qwen2RMSNorm()
  24. )
  25. (lm_head): Linear(in_features=3584, out_features=152064, bias=False)
  26. )

2.3 微调(Fine-Tuning

2.3.1 LoRA

核心思想:通过低秩分解来模拟参数的改变量,以极小的参数来实现大模型的间接训练。

如下图,涉及到矩阵相乘的模块,比如transformers中的Q、K、V线性模块,在原始的权重旁边增加两个低维度的小矩阵A、B,通过前后两个矩阵A、B相乘,第一个矩阵A负责降维,第二个矩阵B负责升维,中间层维度为r,为了将维度还原。

假设原始维度为d,这样就将d*d降为d*r+r*d

  • 训练:只更新新增的A、B两个小矩阵参数
  • 推理:将原矩阵W与A、B两个小矩阵乘积BA加起来作为结果h=Wx+BAx=(W+BA)x,对于推理来说,不增加额外资源

代码很简单,还是一个配置文件LoraConfig:

  1. from peft import LoraConfig,get_peft_model
  2. config = LoraConfig(
  3. r=32,
  4. lora_alpha=16,
  5. target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj","down_proj"],
  6. lora_dropout=0.05,
  7. bias="none",
  8. task_type="CAUSAL_LM",
  9. )
  10. model = get_peft_model(model, config)
  11. print(model)
  1. 引用peft(Parameter-Efficient Fine-Tuning)库
  2. 配置Lora配置文件LoraConfig
  3. 通过peft封装的get_peft_model方法将LoraConfig应用于model

查看模型结构会发现原有的Linear4bit结构,如q_proj:

(q_proj): Linear4bit(in_features=3584, out_features=3584, bias=True)

变成了:

  1. (q_proj): lora.Linear4bit(
  2. (base_layer): Linear4bit(in_features=3584, out_features=3584, bias=True)
  3. (lora_dropout): ModuleDict(
  4. (default): Dropout(p=0.05, inplace=False)
  5. )
  6. (lora_A): ModuleDict(
  7. (default): Linear(in_features=3584, out_features=32, bias=False)
  8. )
  9. (lora_B): ModuleDict(
  10. (default): Linear(in_features=32, out_features=3584, bias=False)
  11. )
  12. (lora_embedding_A): ParameterDict()
  13. (lora_embedding_B): ParameterDict()
  14. )

在Linear4bit基础上,新增了

  • lora_dropout:用于防止过拟合
  • Lora_A和Lora_B的ModuleDict:其中A的out_features与B的in_features相同,都为r=32
  • Lora_A和Lora_B的embedding层

对["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj","down_proj"]等7个Linear4bit量化后的完整模型结构如下

  1. PeftModelForCausalLM(
  2. (base_model): LoraModel(
  3. (model): Qwen2ForCausalLM(
  4. (model): Qwen2Model(
  5. (embed_tokens): Embedding(152064, 3584)
  6. (layers): ModuleList(
  7. (0-27): 28 x Qwen2DecoderLayer(
  8. (self_attn): Qwen2SdpaAttention(
  9. (q_proj): lora.Linear4bit(
  10. (base_layer): Linear4bit(in_features=3584, out_features=3584, bias=True)
  11. (lora_dropout): ModuleDict(
  12. (default): Dropout(p=0.05, inplace=False)
  13. )
  14. (lora_A): ModuleDict(
  15. (default): Linear(in_features=3584, out_features=32, bias=False)
  16. )
  17. (lora_B): ModuleDict(
  18. (default): Linear(in_features=32, out_features=3584, bias=False)
  19. )
  20. (lora_embedding_A): ParameterDict()
  21. (lora_embedding_B): ParameterDict()
  22. )
  23. (k_proj): lora.Linear4bit(
  24. (base_layer): Linear4bit(in_features=3584, out_features=512, bias=True)
  25. (lora_dropout): ModuleDict(
  26. (default): Dropout(p=0.05, inplace=False)
  27. )
  28. (lora_A): ModuleDict(
  29. (default): Linear(in_features=3584, out_features=32, bias=False)
  30. )
  31. (lora_B): ModuleDict(
  32. (default): Linear(in_features=32, out_features=512, bias=False)
  33. )
  34. (lora_embedding_A): ParameterDict()
  35. (lora_embedding_B): ParameterDict()
  36. )
  37. (v_proj): lora.Linear4bit(
  38. (base_layer): Linear4bit(in_features=3584, out_features=512, bias=True)
  39. (lora_dropout): ModuleDict(
  40. (default): Dropout(p=0.05, inplace=False)
  41. )
  42. (lora_A): ModuleDict(
  43. (default): Linear(in_features=3584, out_features=32, bias=False)
  44. )
  45. (lora_B): ModuleDict(
  46. (default): Linear(in_features=32, out_features=512, bias=False)
  47. )
  48. (lora_embedding_A): ParameterDict()
  49. (lora_embedding_B): ParameterDict()
  50. )
  51. (o_proj): lora.Linear4bit(
  52. (base_layer): Linear4bit(in_features=3584, out_features=3584, bias=False)
  53. (lora_dropout): ModuleDict(
  54. (default): Dropout(p=0.05, inplace=False)
  55. )
  56. (lora_A): ModuleDict(
  57. (default): Linear(in_features=3584, out_features=32, bias=False)
  58. )
  59. (lora_B): ModuleDict(
  60. (default): Linear(in_features=32, out_features=3584, bias=False)
  61. )
  62. (lora_embedding_A): ParameterDict()
  63. (lora_embedding_B): ParameterDict()
  64. )
  65. (rotary_emb): Qwen2RotaryEmbedding()
  66. )
  67. (mlp): Qwen2MLP(
  68. (gate_proj): lora.Linear4bit(
  69. (base_layer): Linear4bit(in_features=3584, out_features=18944, bias=False)
  70. (lora_dropout): ModuleDict(
  71. (default): Dropout(p=0.05, inplace=False)
  72. )
  73. (lora_A): ModuleDict(
  74. (default): Linear(in_features=3584, out_features=32, bias=False)
  75. )
  76. (lora_B): ModuleDict(
  77. (default): Linear(in_features=32, out_features=18944, bias=False)
  78. )
  79. (lora_embedding_A): ParameterDict()
  80. (lora_embedding_B): ParameterDict()
  81. )
  82. (up_proj): lora.Linear4bit(
  83. (base_layer): Linear4bit(in_features=3584, out_features=18944, bias=False)
  84. (lora_dropout): ModuleDict(
  85. (default): Dropout(p=0.05, inplace=False)
  86. )
  87. (lora_A): ModuleDict(
  88. (default): Linear(in_features=3584, out_features=32, bias=False)
  89. )
  90. (lora_B): ModuleDict(
  91. (default): Linear(in_features=32, out_features=18944, bias=False)
  92. )
  93. (lora_embedding_A): ParameterDict()
  94. (lora_embedding_B): ParameterDict()
  95. )
  96. (down_proj): lora.Linear4bit(
  97. (base_layer): Linear4bit(in_features=18944, out_features=3584, bias=False)
  98. (lora_dropout): ModuleDict(
  99. (default): Dropout(p=0.05, inplace=False)
  100. )
  101. (lora_A): ModuleDict(
  102. (default): Linear(in_features=18944, out_features=32, bias=False)
  103. )
  104. (lora_B): ModuleDict(
  105. (default): Linear(in_features=32, out_features=3584, bias=False)
  106. )
  107. (lora_embedding_A): ParameterDict()
  108. (lora_embedding_B): ParameterDict()
  109. )
  110. (act_fn): SiLU()
  111. )
  112. (input_layernorm): Qwen2RMSNorm()
  113. (post_attention_layernorm): Qwen2RMSNorm()
  114. )
  115. )
  116. (norm): Qwen2RMSNorm()
  117. )
  118. (lm_head): Linear(in_features=3584, out_features=152064, bias=False)
  119. )
  120. )
  121. )

2.3.2 QLoRA

聪明的人已经想到了,将上文讲到的Quantization与Lora结合,不就是QLoRA吗。

  • 在训练模型的时候,将Linear层转换为Linear4bit
  • 对Linear4bit量化层添加A、B两个低秩为r的小矩阵
  • 这两个小矩阵的权重通过量化权重的反向传播梯度进行微调

在LoRA的基础上,QLoRA关键做了3点创新:

  • NF4(4bit NormalFloat):改进的4位量化法,确保每个量化箱中的值数量相等。
  • 双量化:对第一次量化后的那些常量再进行一次量化,减少存储空间。
  • 分页优化器:使用Nvidia内存分页,在GPU资源不足的情况下,使用CPU计算

回忆一下上面量化部分BitsAndBytesConfig的代码,是不是很熟悉:

  1. quantization_config = BitsAndBytesConfig(
  2. load_in_4bit=True, # 或者 load_in_8bit=True,根据需要设置
  3. #llm_int8_threshold=6.0,
  4. #llm_int8_has_fp16_weight=False,
  5. llm_int8_enable_fp32_cpu_offload=True,
  6. bnb_4bit_compute_dtype=torch.float16,
  7. bnb_4bit_quant_type="nf4",#添加nf4配置,去掉为fp4
  8. bnb_4bit_use_double_quant=True,#添加nf4配置,去掉为fp4
  9. )

三、量化与微调—实战演练:以Qwen2为例,亲手微调你的第一个AI大模型

3.1 模型预处理—依赖安装、库包导入、模型下载

  1. from modelscope import snapshot_download
  2. model_dir = snapshot_download('qwen/Qwen2-7B-Instruct')
  3. import torch
  4. import torch.nn as nn
  5. import transformers
  6. from datasets import load_dataset,load_from_disk
  7. from transformers import AutoTokenizer, AutoModelForCausalLM,BitsAndBytesConfig
  8. from peft import LoraConfig,get_peft_model,prepare_model_for_kbit_training

这里还是

  • 使用modelscope下载模型,
  • 使用transformers的自动分词器(AutoTokenizer)、自动模型库(AutoModelForCausalLM)、量化配置(BitsAndBytesConfig)等处理模型,
  • 使用dataset处理数据,
  • 使用peft加载lora配置并进行微调
  • 以及离不开的torch。

回忆一下安装conda环境以及pip依赖包的方法

  1. conda create -n train_llm python
  2. conda activate train_llm
  3. pip install transformers,modelscope,peft,torch,datasets,accelerate,bitsandbytes -i https://mirrors.cloud.tencent.com/pypi/simple

3.2 模型预处理—加载量化模型

采用BitsAndBytesConfig配置量化参数,采用AutoModelForCausalLM加载量化参数

  1. device = "auto" # the value needs to be a device name (e.g. cpu, cuda:0) or 'auto', 'balanced', 'balanced_low_0', 'sequential'
  2. ###int4量化配置
  3. quantization_config = BitsAndBytesConfig(
  4. load_in_4bit=True, # 或者 load_in_8bit=True,根据需要设置
  5. #llm_int8_threshold=6.0,
  6. #llm_int8_has_fp16_weight=False,
  7. llm_int8_enable_fp32_cpu_offload=True,
  8. bnb_4bit_compute_dtype=torch.float16,#虽然我们以4位加载和存储模型,但我们在需要时会部分反量化他,并以16位精度进行计算
  9. bnb_4bit_quant_type="nf4",#nf量化类型
  10. bnb_4bit_use_double_quant=True,#双重量化,量化一次后再量化,进一步解决显存
  11. )
  12. model = AutoModelForCausalLM.from_pretrained(model_dir,device_map=device,trust_remote_code=True,torch_dtype=torch.float16,quantization_config=quantization_config)
  13. tokenizer = AutoTokenizer.from_pretrained(model_dir,trust_remote_code=True,padding_side="right",use_fast=False)
  14. print(model)

3.3 模型预处理—加载LoRA网络

  1. from peft import LoraConfig,get_peft_model,prepare_model_for_kbit_training
  2. model = prepare_model_for_kbit_training(model)
  3. config = LoraConfig(
  4. r=32,
  5. lora_alpha=16,
  6. target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj","down_proj"],
  7. lora_dropout=0.05,
  8. bias="none",
  9. task_type="CAUSAL_LM",
  10. )
  11. model = get_peft_model(model, config)
  12. print(model)
  • 采用prepare_model_for_kbit_training对norm和LM head层进行处理,提升训练稳定性(非常必要,否则会报显存不足的错误):
    • layer norm 层保留 FP32 精度
    • embedding层以及 LM head 输出层保留 FP32 精度 
  • 采用get_peft_model为模型添加lora层

3.4 数据预处理—下载、处理数据 

这里采用huggingface上的Abirate/english_quotes数据集,我这里由于网络环境原因,手动下载保存至./目录。

  1. data = load_dataset('json',data_files="./quotes.jsonl")
  2. data = data.map(lambda samples: tokenizer(samples["quote"]), batched=True)
  3. print(data)

数据集样例(这里为例调试,实际请替换自己的数据集。): 

通过tokenizer和data.map将每一行quote中的数据分词处理为input_ids。输出为

3.5 模型训练 

经过包导入、模型量化、模型lora、数据预处理,重要到了第5步:模型训练

  1. trainer = transformers.Trainer(
  2. model=model,
  3. train_dataset=data["train"],
  4. args=transformers.TrainingArguments(
  5. per_device_train_batch_size=4,
  6. gradient_accumulation_steps=4,
  7. warmup_steps=10,
  8. max_steps=50,
  9. learning_rate=3e-4,
  10. fp16=True,
  11. logging_steps=1,
  12. output_dir="outputs/checkpoint-1"+time_str,
  13. optim="paged_adamw_8bit",
  14. save_strategy = 'steps',
  15. save_steps = 10,
  16. ),
  17. data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
  18. )
  19. model.config.use_cache = False # silence the warnings. Please re-enable for inference!
  20. trainer.train()
  21. trainer.save_model(trainer.args.output_dir)

采用transformers的训练器Trainer,输入qlora模型、数据、训练参数、数据收集器等参数,启动训练。

Qwen2-7B-Instruct模型按以上参数训练占用显存约20G。 

3.6 模型合并及推理

以上是一段模型合并推理测试代码,主要包括

  1. 导入peft内的PeftModel模型类和PeftConfig配置类
  2. 通过trainer.args.output_dir获取微调模型目录peft_model_dir
  3. 获取微调后的模型配置config
  4. 加载基座模型
  5. 通过PeftModel.from_pretrained(model,peft_model_dir)将基座模型与微调模型合并
  6. 模型推理,同使用基座模型一样!
  1. import torch
  2. from peft import PeftModel, PeftConfig
  3. from transformers import AutoModelForCausalLM, AutoTokenizer
  4. peft_model_dir = trainer.args.output_dir
  5. config = PeftConfig.from_pretrained(peft_model_dir)
  6. print(config)
  7. model = AutoModelForCausalLM.from_pretrained(
  8. config.base_model_name_or_path, return_dict=True, device_map=device,
  9. torch_dtype=torch.float16, quantization_config=quantization_config
  10. )
  11. tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
  12. # Load the Lora model
  13. model = PeftModel.from_pretrained(model, peft_model_dir)
  14. print(model)
  15. # 模拟对话
  16. prompt = "详细介绍一下大语言模型,评价下与深度学习的差异"
  17. messages = [
  18. {"role": "system", "content": "你是一个智能助理."},
  19. {"role": "user", "content": prompt}
  20. ]
  21. text = tokenizer.apply_chat_template(
  22. messages,
  23. tokenize=False,
  24. add_generation_prompt=True
  25. )
  26. model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
  27. gen_kwargs = {"max_length": 512, "do_sample": True, "top_k": 1}
  28. with torch.no_grad():
  29. outputs = model.generate(**model_inputs, **gen_kwargs)
  30. outputs = outputs[:, model_inputs['input_ids'].shape[1]:] #切除system、user等对话前缀
  31. print(tokenizer.decode(outputs[0], skip_special_tokens=True))

推理所用显存:约15G

推理结果(本文仅为跑通流程,不提供涉及业务的任何相关数据,各位可以根据自己实际情况替换3.4的数据部分):

3.7 附:完整代码

  1. from datetime import datetime
  2. now = datetime.now()
  3. time_str = now.strftime('%Y-%m-%d %H:%M:%S')
  4. print(time_str)
  5. from modelscope import snapshot_download
  6. model_dir = snapshot_download('qwen/Qwen2-7B-Instruct')
  7. import torch
  8. import torch.nn as nn
  9. import transformers
  10. from datasets import load_dataset,load_from_disk
  11. from transformers import AutoTokenizer, AutoModelForCausalLM,BitsAndBytesConfig
  12. device = "auto" # the value needs to be a device name (e.g. cpu, cuda:0) or 'auto', 'balanced', 'balanced_low_0', 'sequential'
  13. ###int4量化配置
  14. quantization_config = BitsAndBytesConfig(
  15. load_in_4bit=True, # 或者 load_in_8bit=True,根据需要设置
  16. #llm_int8_threshold=6.0,
  17. #llm_int8_has_fp16_weight=False,
  18. llm_int8_enable_fp32_cpu_offload=True,
  19. bnb_4bit_compute_dtype=torch.float16,#虽然我们以4位加载和存储模型,但我们在需要时会部分反量化他,并以16位精度进行计算
  20. bnb_4bit_quant_type="nf4",#nf量化类型
  21. bnb_4bit_use_double_quant=True,#双重量化,量化一次后再量化,进一步解决显存
  22. )
  23. model = AutoModelForCausalLM.from_pretrained(model_dir,device_map=device,trust_remote_code=True,torch_dtype=torch.float16,quantization_config=quantization_config)
  24. tokenizer = AutoTokenizer.from_pretrained(model_dir,trust_remote_code=True,padding_side="right",use_fast=False)
  25. model.gradient_checkpointing_enable
  26. print(model)
  27. def print_trainable_parameters(model):
  28. """
  29. Prints the number of trainable parameters in the model.
  30. """
  31. trainable_params = 0
  32. all_param = 0
  33. for _, param in model.named_parameters():
  34. all_param += param.numel()
  35. if param.requires_grad:
  36. trainable_params += param.numel()
  37. print(
  38. f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}"
  39. )
  40. from peft import LoraConfig,get_peft_model,prepare_model_for_kbit_training
  41. model = prepare_model_for_kbit_training(model)
  42. config = LoraConfig(
  43. r=32,
  44. lora_alpha=16,
  45. target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj","down_proj"],
  46. lora_dropout=0.05,
  47. bias="none",
  48. task_type="CAUSAL_LM",
  49. )
  50. model = get_peft_model(model, config)
  51. print(model)
  52. print_trainable_parameters(model)
  53. # Verifying the datatypes.
  54. dtypes = {}
  55. for _, p in model.named_parameters():
  56. dtype = p.dtype
  57. if dtype not in dtypes:
  58. dtypes[dtype] = 0
  59. dtypes[dtype] += p.numel()
  60. total = 0
  61. for k, v in dtypes.items():
  62. total += v
  63. for k, v in dtypes.items():
  64. print(k, v, v / total)
  65. """### Training"""
  66. data = load_dataset('json',data_files="./quotes.jsonl")
  67. data = data.map(lambda samples: tokenizer(samples["quote"]), batched=True)
  68. print(data)
  69. trainer = transformers.Trainer(
  70. model=model,
  71. train_dataset=data["train"],
  72. args=transformers.TrainingArguments(
  73. per_device_train_batch_size=4,
  74. gradient_accumulation_steps=4,
  75. warmup_steps=10,
  76. max_steps=50,
  77. learning_rate=3e-4,
  78. fp16=True,
  79. logging_steps=1,
  80. output_dir="outputs/checkpoint-1"+time_str,
  81. optim="paged_adamw_8bit",
  82. save_strategy = 'steps',
  83. save_steps = 10,
  84. ),
  85. data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
  86. )
  87. model.config.use_cache = False # silence the warnings. Please re-enable for inference!
  88. trainer.train()
  89. trainer.save_model(trainer.args.output_dir)
  90. import torch
  91. from peft import PeftModel, PeftConfig
  92. from transformers import AutoModelForCausalLM, AutoTokenizer
  93. peft_model_dir = trainer.args.output_dir
  94. config = PeftConfig.from_pretrained(peft_model_dir)
  95. print(config)
  96. model = AutoModelForCausalLM.from_pretrained(
  97. config.base_model_name_or_path, return_dict=True, device_map=device,
  98. torch_dtype=torch.float16, quantization_config=quantization_config
  99. )
  100. tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
  101. # Load the Lora model
  102. model = PeftModel.from_pretrained(model, peft_model_dir)
  103. print(model)
  104. # 模拟对话
  105. prompt = "详细介绍一下大语言模型,评价下与深度学习的差异"
  106. messages = [
  107. {"role": "system", "content": "你是一个智能助理."},
  108. {"role": "user", "content": prompt}
  109. ]
  110. text = tokenizer.apply_chat_template(
  111. messages,
  112. tokenize=False,
  113. add_generation_prompt=True
  114. )
  115. model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
  116. gen_kwargs = {"max_length": 512, "do_sample": True, "top_k": 1}
  117. with torch.no_grad():
  118. outputs = model.generate(**model_inputs, **gen_kwargs)
  119. outputs = outputs[:, model_inputs['input_ids'].shape[1]:] #切除system、user等对话前缀
  120. print(tokenizer.decode(outputs[0], skip_special_tokens=True))

四、总结

本文首先对量化和微调的原理进行剖析,接着以Qwen2-7B为例,基于QLoRA、PEFT一步一步带着大家微调自己的大模型,本文参考全网peft+qlora微调教程,一步一排坑,让大家在网络环境不允许的情况下,也能丝滑的开启大模型微调之旅。希望能帮助到大家,喜欢的话关注+三连噢。

如果您还有时间,可以看看我的其他文章:

《AI—工程篇》

AI智能体研发之路-工程篇(一):Docker助力AI智能体开发提效

AI智能体研发之路-工程篇(二):Dify智能体开发平台一键部署

AI智能体研发之路-工程篇(三):大模型推理服务框架Ollama一键部署

AI智能体研发之路-工程篇(四):大模型推理服务框架Xinference一键部署

AI智能体研发之路-工程篇(五):大模型推理服务框架LocalAI一键部署

《AI—模型篇》

AI智能体研发之路-模型篇(一):大模型训练框架LLaMA-Factory在国内网络环境下的安装、部署及使用

AI智能体研发之路-模型篇(二):DeepSeek-V2-Chat 训练与推理实战

AI智能体研发之路-模型篇(三):中文大模型开、闭源之争

AI智能体研发之路-模型篇(四):一文入门pytorch开发

AI智能体研发之路-模型篇(五):pytorch vs tensorflow框架DNN网络结构源码级对比

AI智能体研发之路-模型篇(六):【机器学习】基于tensorflow实现你的第一个DNN网络

AI智能体研发之路-模型篇(七):【机器学习】基于YOLOv10实现你的第一个视觉AI大模型

AI智能体研发之路-模型篇(八):【机器学习】Qwen1.5-14B-Chat大模型训练与推理实战

AI智能体研发之路-模型篇(九):【机器学习】GLM4-9B-Chat大模型/GLM-4V-9B多模态大模型概述、原理及推理实战

AI智能体研发之路-模型篇(十):【机器学习】Qwen2大模型原理、训练及推理部署实战

《AI—Transformers应用》

【AI大模型】Transformers大模型库(一):Tokenizer

【AI大模型】Transformers大模型库(二):AutoModelForCausalLM

【AI大模型】Transformers大模型库(三):特殊标记(special tokens)

【AI大模型】Transformers大模型库(四):AutoTokenizer

【AI大模型】Transformers大模型库(五):AutoModel、Model Head及查看模型结构

【AI大模型】Transformers大模型库(六):torch.cuda.OutOfMemoryError: CUDA out of memory解决

【AI大模型】Transformers大模型库(七):单机多卡推理之device_map

【AI大模型】Transformers大模型库(八):大模型微调之LoraConfig

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/807371
推荐阅读
相关标签
  

闽ICP备14008679号