Skip to content
On this page

Llama3 fine-tuning

为什么选择 Llama3 进行微调

  1. 高精度:Llama3 在各种基准测试中表现出更加先进的准确性,包括 SuperGLUE、GLUE、SQuAD
  2. 高效率:Llama3 经过优化,可以高效运行,即使是在资源有限的设备上也是如此。这意味着它可以用于各种实时应用程序
  3. 泛化能力强:Llama3 能够泛化到与训练数据不同的数据,这意味着它可以用于各种新任务和域
  4. 更灵活:Llama3 可以使用多种方法进行微调,这使其可用于各种任务

unsloth

Unsloth 是一个新兴的人工智能公司,专注于加快和优化大型语言模型(LLMs)的训练过程。传统上,LLMs的训练需要大量的计算资源和内存,耗时较长。为了解决这一问题,Unsloth 开发了一款名为 Unsloth 的软件,能够将训练速度提升高达30倍,并将内存使用减少60%。

unsloth 主要特点和优势:

通过 QLoRA 和 LoRA 技术来加速 LLM 的微调,能够提升 2-5 倍的性能并减少 70% 的内存使用量

  1. 技术优化

    • 手动自动微分(Manual Autograd):通过手动计算梯度来优化模型更新过程,加快训练速度。
    • 链式矩阵乘法(Chained Matrix Multiplication):高效地优化矩阵乘法,是LLMs训练中的关键步骤。
    • Triton语言内核(Triton Language Kernels):使用由OpenAI开发的高性能计算语言 Triton 重写关键训练代码。
    • Flash Attention:通过 xformers 和 Tri Dao 的实现,帮助模型集中注意力于输入数据的重要部分。
  2. 工作原理

    • 通过将 LLM 的权重分解为低秩矩阵来减少内存使用量
    • 能够在更小的 GPU 上训练 LLM,或者在更大的 GPU 上训练更大的 LLM
    • 可以有效地加速各种 LLM 的微调,包括 GPT-3 Jurassic-1 Jumbo 和 Megatron-Turing NLG
  3. 兼容性和可访问性

    • 支持 NVIDIA、Intel 和 AMD 等主流GPU,无需购买昂贵的新硬件即可使用。
    • 提供免费的开源版本,任何人都可以在GitHub上获取并体验快速训练和更少内存使用的好处。
  4. 适用场景

    • NLP
    • 机器翻译
    • 文本生成
    • 问答系统
    • 聊天机器人
  5. 支持的语言模型

    • 支持多种流行的语言模型,使用户可以轻松应用优化技术到其喜爱的模型上。
  6. 性能测试结果

    • 在多个数据集和硬件设置下,Unsloth 显著减少了训练时间和内存使用量,例如在 Alpaca 数据集上,将训练时间从85小时缩短到仅3小时,内存使用从16.7GB降至6.9GB。
  7. 社区和未来计划

    • 积极与AI社区互动,鼓励用户尝试其开源软件并提供反馈。
    • 提供Pro和Max版本,支持多GPU和完整的LLM训练功能。
    • 未来计划包括进一步增加推理速度、实施 sqrt 梯度检查点技术以进一步减少内存使用、优化训练方法等。
  8. 结论

    • Unsloth 在加快和优化AI语言模型训练方面取得了显著进展。他们的技术不仅提高了训练效率,还通过兼容性、可访问性和社区参与,致力于在AI和自然语言处理领域产生深远影响。

这些特点使得 Unsloth 成为当前AI领域中备受关注的技术创新之一。

具体实现

colab

  1. 安装 unsloth
python
# Installs Unsloth, Xformers (Flash Attention) and all other packages!
!pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
!pip install --no-deps xformers "trl<0.9.0" peft accelerate bitsandbytes
  1. 加载模型
python
from unsloth import FastLanguageModel
import torch
max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.

# 4bit pre quantized models we support for 4x faster downloading + no OOMs.
fourbit_models = [
    "unsloth/mistral-7b-v0.3-bnb-4bit",      # New Mistral v3 2x faster!
    "unsloth/mistral-7b-instruct-v0.3-bnb-4bit",
    "unsloth/llama-3-8b-bnb-4bit",           # Llama-3 15 trillion tokens model 2x faster!
    "unsloth/llama-3-8b-Instruct-bnb-4bit",
    "unsloth/llama-3-70b-bnb-4bit",
    "unsloth/Phi-3-mini-4k-instruct",        # Phi-3 2x faster!
    "unsloth/Phi-3-medium-4k-instruct",
    "unsloth/mistral-7b-bnb-4bit",
    "unsloth/gemma-7b-bnb-4bit",             # Gemma 2.2x faster!
] # More models at https://huggingface.co/unsloth

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/llama-3-8b-bnb-4bit",
    max_seq_length = max_seq_length,
    dtype = dtype,
    load_in_4bit = load_in_4bit,
    # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
)
  1. 修改模型 结合 QLoRA/LoRA 配置优化微调参数
python
model = FastLanguageModel.get_peft_model(
    model,
    r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",],
    lora_alpha = 16,
    lora_dropout = 0, # Supports any, but = 0 is optimized
    bias = "none",    # Supports any, but = "none" is optimized
    # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
    use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
    random_state = 3407,
    use_rslora = False,  # We support rank stabilized LoRA
    loftq_config = None, # And LoftQ
)
  1. 加载并构造 train-data
python
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
{}

### Input:
{}

### Response:
{}"""

EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
def formatting_prompts_func(examples):
    instructions = examples["instruction"]
    inputs       = examples["input"]
    outputs      = examples["output"]
    texts = []
    for instruction, input, output in zip(instructions, inputs, outputs):
        # Must add EOS_TOKEN, otherwise your generation will go on forever!
        text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
        texts.append(text)
    return { "text" : texts, }
pass

from datasets import load_dataset
dataset = load_dataset("yahma/alpaca-cleaned", split = "train")
dataset = dataset.map(formatting_prompts_func, batched = True,)
  1. 训练模型配置
python
from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported

trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = dataset,
    dataset_text_field = "text",
    max_seq_length = max_seq_length,
    dataset_num_proc = 2,
    packing = False, # Can make training 5x faster for short sequences.
    args = TrainingArguments(
        per_device_train_batch_size = 2,
        gradient_accumulation_steps = 4,
        warmup_steps = 5,
        max_steps = 60,
        learning_rate = 2e-4,
        fp16 = not is_bfloat16_supported(),
        bf16 = is_bfloat16_supported(),
        logging_steps = 1,
        optim = "adamw_8bit",
        weight_decay = 0.01,
        lr_scheduler_type = "linear",
        seed = 3407,
        output_dir = "outputs",
    ),
)
  1. [Optional]显示当前memory状态[对比内存占用]
python
#@title Show current memory stats
gpu_stats = torch.cuda.get_device_properties(0)
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
print(f"{start_gpu_memory} GB of memory reserved.")
  1. 实际执行训练
python
trainer_stats = trainer.train()
  1. [Optional]显示当前memory状态[对比内存占用]
python
#@title Show final memory and time stats
used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
used_percentage = round(used_memory         /max_memory*100, 3)
lora_percentage = round(used_memory_for_lora/max_memory*100, 3)
print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
print(f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.")
print(f"Peak reserved memory = {used_memory} GB.")
print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
print(f"Peak reserved memory % of max memory = {used_percentage} %.")
print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
  1. 完成后执行推理
python
# alpaca_prompt = Copied from above
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
    alpaca_prompt.format(
        "Continue the fibonnaci sequence.", # instruction
        "1, 1, 2, 3, 5, 8", # input
        "", # output - leave this blank for generation!
    )
], return_tensors = "pt").to("cuda")

outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)

stream形式

python
# alpaca_prompt = Copied from above
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
inputs = tokenizer(
[
    alpaca_prompt.format(
        "Continue the fibonnaci sequence.", # instruction
        "1, 1, 2, 3, 5, 8", # input
        "", # output - leave this blank for generation!
    )
], return_tensors = "pt").to("cuda")

from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer)
_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 128)
  1. 保存模型
python
model.save_pretrained("lora_model") # Local saving
tokenizer.save_pretrained("lora_model")
# model.push_to_hub("your_name/lora_model", token = "...") # Online saving
# tokenizer.push_to_hub("your_name/lora_model", token = "...") # Online saving
  1. unsloth加载模型
python
if False:
    from unsloth import FastLanguageModel
    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name = "lora_model", # YOUR MODEL YOU USED FOR TRAINING
        max_seq_length = max_seq_length,
        dtype = dtype,
        load_in_4bit = load_in_4bit,
    )
    FastLanguageModel.for_inference(model) # Enable native 2x faster inference

# alpaca_prompt = You MUST copy from above!

inputs = tokenizer(
[
    alpaca_prompt.format(
        "What is a famous tall tower in Paris?", # instruction
        "", # input
        "", # output - leave this blank for generation!
    )
], return_tensors = "pt").to("cuda")

outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
tokenizer.batch_decode(outputs)
  1. hf加载模型
python
if False:
    # I highly do NOT suggest - use Unsloth if possible
    from peft import AutoPeftModelForCausalLM
    from transformers import AutoTokenizer
    model = AutoPeftModelForCausalLM.from_pretrained(
        "lora_model", # YOUR MODEL YOU USED FOR TRAINING
        load_in_4bit = load_in_4bit,
    )
    tokenizer = AutoTokenizer.from_pretrained("lora_model")
  1. 保存为VLLM float16
python
# Merge to 16bit
if True: model.save_pretrained_merged("llama-3-8b-bnb-4bit-ft-1", tokenizer, save_method = "merged_16bit",)
if True: model.push_to_hub_merged("lumiseven/llama-3-8b-bnb-4bit-ft-1", tokenizer, save_method = "merged_16bit", token = "")

# Merge to 4bit
if False: model.save_pretrained_merged("llama-3-8b-bnb-4bit-ft-1", tokenizer, save_method = "merged_4bit",)
if False: model.push_to_hub_merged("lumiseven/llama-3-8b-bnb-4bit-ft-1", tokenizer, save_method = "merged_4bit", token = "")

# Just LoRA adapters
if False: model.save_pretrained_merged("model", tokenizer, save_method = "lora",)
if False: model.push_to_hub_merged("hf/model", tokenizer, save_method = "lora", token = "")
  1. GGUF/llama.cpp 转换
python
# Save to 8bit Q8_0
if False: model.save_pretrained_gguf("model", tokenizer,)
if False: model.push_to_hub_gguf("hf/model", tokenizer, token = "")

# Save to 16bit GGUF
if False: model.save_pretrained_gguf("model", tokenizer, quantization_method = "f16")
if False: model.push_to_hub_gguf("hf/model", tokenizer, quantization_method = "f16", token = "")

# Save to q4_k_m GGUF
if False: model.save_pretrained_gguf("model", tokenizer, quantization_method = "q4_k_m")
if False: model.push_to_hub_gguf("hf/model", tokenizer, quantization_method = "q4_k_m", token = "")

Released under the MIT License.