0


微调llama2模型教程:创建自己的Python代码生成器

本文将演示如何使用PEFT、QLoRa和Huggingface对新的lama-2进行微调,生成自己的代码生成器。所以本文将重点展示如何定制自己的llama2,进行快速训练,以完成特定任务。

一些知识点

llama2相比于前一代,令牌数量增加了40%,达到2T,上下文长度增加了一倍,并应用分组查询注意(GQA)技术来加速在较重的70B模型上的推理。在标准的transformer 体系结构上,使用RMSNorm归一化、SwiGLU激活和旋转位置嵌入,上下文长度达到了4096个,并应用了具有余弦学习率调度、权重衰减0.1和梯度裁剪的Adam优化器。

有监督微调(SFT)阶段的特点是优先考虑质量样本而不是数量,因为许多报告表明,使用高质量数据可以提高最终模型的性能。

最后,通过带有人类反馈的强化学习(RLHF)步骤使模型与用户偏好保持一致。收集了大量示例,其中人类在比较中选择他们首选的模型输出。这些数据被用来训练奖励模型。

最主要的一点是,LLaMA 2-CHAT已经和OpenAI ChatGPT一样好了,所以我们可以使用它作为我们本地的一个替代了

数据集

对于的微调过程,我们将使用大约18,000个示例的数据集,其中要求模型构建解决给定任务的Python代码。这是原始数据集[2]的提取,其中只选择了Python语言示例。每行包含要解决的任务的描述,如果适用的话,任务的数据输入示例,并提供解决任务的生成代码片段[3]。

  1. # Load dataset from the hub
  2. dataset = load_dataset(dataset_name, split=dataset_split)
  3. # Show dataset size
  4. print(f"dataset size: {len(dataset)}")
  5. # Show an example
  6. print(dataset[randrange(len(dataset))])

创建提示

为了执行指令微调,我们必须将每个数据示例转换为指令,并将其主要部分概述如下:

  1. def format_instruction(sample):
  2. return f"""### Instruction:
  3. Use the Task below and the Input given to write the Response, which is a programming code that can solve the following Task:
  4. ### Task:
  5. {sample['instruction']}
  6. ### Input:
  7. {sample['input']}
  8. ### Response:
  9. {sample['output']}
  10. """

输出的结果是这样的:

  1. ### Instruction:
  2. Use the Task below and the Input given to write the Response, which is a programming code that can solve the following Task:
  3. ### Task:
  4. Develop a Python program that prints "Hello, World!" whenever it is run.
  5. ### Input:
  6. ### Response:
  7. #Python program to print "Hello World!"
  8. print("Hello, World!")

微调模型

为了方便演示,我们使用Google Colab环境,对于第一次测试运行,T4实例就足够了,但是当涉及到运行整个数据集训练,则需要使用A100。

除此以外,还可以登录Huggingface hub ,这样可以上传和共享模型,当然这个是可选项。

  1. from huggingface_hub import login
  2. from dotenv import load_dotenv
  3. import os
  4. # Load the enviroment variables
  5. load_dotenv()
  6. # Login to the Hugging Face Hub
  7. login(token=os.getenv("HF_HUB_TOKEN"))

PEFT、Lora和QLora

训练LLM的通常步骤包括:首先,对数十亿或数万亿个令牌进行预训练得到基础模型,然后对该模型进行微调,使其专门用于下游任务。

参数高效微调(PEFT)允许我们通过微调少量额外参数来大大减少RAM和存储需求,因为所有模型参数都保持冻结状态。并且PEFT还增强了模型的可重用性和可移植性,它很容易将小的检查点添加到基本模型中,通过添加PEFT参数让基础模型在多个场景中重用。最后由于没有调整基本模型,还可以保留在预训练阶段获得的所有知识,从而避免了灾难性遗忘。

PEFT保持预训练的基本模型不变,并在其上添加新的层或参数。这些层被称为“适配器”,我们将这些层添加到预训练的基本模型中,只训练这些新层的参数。但是这种方法的一个严重问题是,这些层会导致推理阶段的延迟增加,从而使流程在许多情况下效率低下。

而在LoRa技术(大型语言模型的低秩适应)中不是添加新的层,而是以一种避免在推理阶段出现这种可怕的延迟问题的方式向模型各层参数添加值。LoRa训练并存储附加权重的变化,同时冻结预训练模型的所有权重。也就是说我们利用预训练模型矩阵的变化训练一个新的权重矩阵,并将这个新矩阵分解为2个低秩矩阵,如下所示:

LoRA[1]的作者提出权值变化矩阵∆W的变化可以分解为两个低秩矩阵A和b。LoRA不直接训练∆W中的参数,而是直接训练A和b中的参数,因此可训练参数的数量要少得多。假设A的维数为100 * 1,B的维数为1 * 100,则∆W中的参数个数为100 * 100 = 10000。在A和B中训练的人数只有100 + 100 = 200,而在∆W中训练的个数是10000

这些低秩矩阵的大小由r参数定义。这个值越小,需要训练的参数就越少,速度更快。但是参数过少可能会损失信息和性能,所以r参数的选择也是需要考虑的问题。

最后,QLoRa[6]则是将量化应用于LoRa方法,通过优化内存使用的技巧,以实现“更轻量”和更便宜的训练。

微调流程

我们的示例中使用QLoRa,所以要指定BitsAndBytes配置,下载4位量化的预训练模型,定义LoraConfig。

  1. # Get the type
  2. compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
  3. # BitsAndBytesConfig int-4 config
  4. bnb_config = BitsAndBytesConfig(
  5. load_in_4bit=use_4bit,
  6. bnb_4bit_use_double_quant=use_double_nested_quant,
  7. bnb_4bit_quant_type=bnb_4bit_quant_type,
  8. bnb_4bit_compute_dtype=compute_dtype
  9. )
  10. # Load model and tokenizer
  11. model = AutoModelForCausalLM.from_pretrained(model_id,
  12. quantization_config=bnb_config, use_cache = False, device_map=device_map)
  13. model.config.pretraining_tp = 1
  14. # Load the tokenizer
  15. tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
  16. tokenizer.pad_token = tokenizer.eos_token
  17. tokenizer.padding_side = "right"

下面是参数定义,

  1. # Activate 4-bit precision base model loading
  2. use_4bit = True
  3. # Compute dtype for 4-bit base models
  4. bnb_4bit_compute_dtype = "float16"
  5. # Quantization type (fp4 or nf4)
  6. bnb_4bit_quant_type = "nf4"
  7. # Activate nested quantization for 4-bit base models (double quantization)
  8. use_double_nested_quant = False
  9. # LoRA attention dimension
  10. lora_r = 64
  11. # Alpha parameter for LoRA scaling
  12. lora_alpha = 16
  13. # Dropout probability for LoRA layers
  14. lora_dropout = 0.1

接下来的步骤对于所有的Hugging Face用户来说应该都很熟悉了,设置训练参数,创建Trainer。在执行指令微调时,我们调用封装PEFT模型定义和其他步骤的SFTTrainer方法。

  1. # Define the training arguments
  2. args = TrainingArguments(
  3. output_dir=output_dir,
  4. num_train_epochs=num_train_epochs,
  5. per_device_train_batch_size=per_device_train_batch_size, # 6 if use_flash_attention else 4,
  6. gradient_accumulation_steps=gradient_accumulation_steps,
  7. gradient_checkpointing=gradient_checkpointing,
  8. optim=optim,
  9. logging_steps=logging_steps,
  10. save_strategy="epoch",
  11. learning_rate=learning_rate,
  12. weight_decay=weight_decay,
  13. fp16=fp16,
  14. bf16=bf16,
  15. max_grad_norm=max_grad_norm,
  16. warmup_ratio=warmup_ratio,
  17. group_by_length=group_by_length,
  18. lr_scheduler_type=lr_scheduler_type,
  19. disable_tqdm=disable_tqdm,
  20. report_to="tensorboard",
  21. seed=42
  22. )
  23. # Create the trainer
  24. trainer = SFTTrainer(
  25. model=model,
  26. train_dataset=dataset,
  27. peft_config=peft_config,
  28. max_seq_length=max_seq_length,
  29. tokenizer=tokenizer,
  30. packing=packing,
  31. formatting_func=format_instruction,
  32. args=args,
  33. )
  34. # train the model
  35. trainer.train() # there will not be a progress bar since tqdm is disabled
  36. # save model in local
  37. trainer.save_model()

这些参数大多数通常用于llm上的其他微调脚本,我们就不做过多的说明了:

  1. # Number of training epochs
  2. num_train_epochs = 1
  3. # Enable fp16/bf16 training (set bf16 to True with an A100)
  4. fp16 = False
  5. bf16 = True
  6. # Batch size per GPU for training
  7. per_device_train_batch_size = 4
  8. # Number of update steps to accumulate the gradients for
  9. gradient_accumulation_steps = 1
  10. # Enable gradient checkpointing
  11. gradient_checkpointing = True
  12. # Maximum gradient normal (gradient clipping)
  13. max_grad_norm = 0.3
  14. # Initial learning rate (AdamW optimizer)
  15. learning_rate = 2e-4
  16. # Weight decay to apply to all layers except bias/LayerNorm weights
  17. weight_decay = 0.001
  18. # Optimizer to use
  19. optim = "paged_adamw_32bit"
  20. # Learning rate schedule
  21. lr_scheduler_type = "cosine" #"constant"
  22. # Ratio of steps for a linear warmup (from 0 to learning rate)
  23. warmup_ratio = 0.03
  24. # Group sequences into batches with same length
  25. # Saves memory and speeds up training considerably
  26. group_by_length = False
  27. # Save checkpoint every X updates steps
  28. save_steps = 0
  29. # Log every X updates steps
  30. logging_steps = 25
  31. # Disable tqdm
  32. disable_tqdm= True

合并权重

正如上面我们提到的方法,LoRa在基本模型上训练了“修改权重”,所以最终模型需要将预训练的模型和适配器权重合并到一个模型中。

  1. from peft import AutoPeftModelForCausalLM
  2. model = AutoPeftModelForCausalLM.from_pretrained(
  3. args.output_dir,
  4. low_cpu_mem_usage=True,
  5. return_dict=True,
  6. torch_dtype=torch.float16,
  7. device_map=device_map,
  8. )
  9. # Merge LoRA and base model
  10. merged_model = model.merge_and_unload()
  11. # Save the merged model
  12. merged_model.save_pretrained("merged_model",safe_serialization=True)
  13. tokenizer.save_pretrained("merged_model")
  14. # push merged model to the hub
  15. merged_model.push_to_hub(hf_model_repo)
  16. tokenizer.push_to_hub(hf_model_repo)

推理

最后就是推理的过程了

  1. import torch
  2. from transformers import AutoModelForCausalLM, AutoTokenizer
  3. # Get the tokenizer
  4. tokenizer = AutoTokenizer.from_pretrained(hf_model_repo)
  5. # Load the model
  6. model = AutoModelForCausalLM.from_pretrained(hf_model_repo, load_in_4bit=True,
  7. torch_dtype=torch.float16,
  8. device_map=device_map)
  9. # Create an instruction
  10. instruction="Optimize a code snippet written in Python. The code snippet should create a list of numbers from 0 to 10 that are divisible by 2."
  11. input=""
  12. prompt = f"""### Instruction:
  13. Use the Task below and the Input given to write the Response, which is a programming code that can solve the Task.
  14. ### Task:
  15. {instruction}
  16. ### Input:
  17. {input}
  18. ### Response:
  19. """
  20. # Tokenize the input
  21. input_ids = tokenizer(prompt, return_tensors="pt", truncation=True).input_ids.cuda()
  22. # Run the model to infere an output
  23. outputs = model.generate(input_ids=input_ids, max_new_tokens=100, do_sample=True, top_p=0.9,temperature=0.5)
  24. # Print the result
  25. print(f"Prompt:\n{prompt}\n")
  26. print(f"Generated instruction:\n{tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True)[0][len(prompt):]}")

结果如下:

  1. Prompt:
  2. ### Instruction:
  3. Use the Task below and the Input given to write the Response, which is a programming code that can solve the Task.
  4. ### Task:
  5. Optimize a code snippet written in Python. The code snippet should create a list of numbers from 0 to 10 that are divisible by 2.
  6. ### Input:
  7. arr = []
  8. for i in range(10):
  9. if i % 2 == 0:
  10. arr.append(i)
  11. ### Response:
  12. Generated instruction:
  13. arr = [i for i in range(10) if i % 2 == 0]
  14. Ground truth:
  15. arr = [i for i in range(11) if i % 2 == 0]

看样子还是很不错的

总结

以上就是我们微调llama2的完整过程,这里面的一个最重要的步骤其实是提示的生成,一个好的提示对于模型的性能也是非常有帮助的。

[1] Llama-2 paper https://arxiv.org/pdf/2307.09288.pdf

[2] python code dataset http://sahil2801/code_instructions_120k

[3] 本文使用的数据集 https://huggingface.co/datasets/iamtarun/python_code_instructions_18k_alpaca

[4] LoRA: Low-Rank Adaptation of Large Language Models. arXiv:2106.09685

[5]. QLoRa: Efficient Finetuning of QuantizedLLMs arXiv:2305.14314

作者:Eduardo Muñoz

“微调llama2模型教程:创建自己的Python代码生成器”的评论:

还没有评论