【LLM教程-llama】如何Fine Tuning大语言模型?

今天给大家带来了一篇超级详细的教程,手把手教你如何对大语言模型进行微调(Fine Tuning)!(代码和详细解释放在后文)

目录

[大语言模型进行微调(Fine Tuning)需要哪些步骤?](#大语言模型进行微调(Fine Tuning)需要哪些步骤?)

[大语言模型进行微调(Fine Tuning)训练过程及代码](#大语言模型进行微调(Fine Tuning)训练过程及代码)


大语言模型进行微调(Fine Tuning)需要哪些步骤?

大语言模型进行微调(Fine Tuning)的主要步骤🤩

  1. 📚 准备训练数据集

    首先你需要准备一个高质量的训练数据集,最好是与你的应用场景相关的数据。可以是文本数据、对话数据等,格式一般为JSON/TXT等。

  2. 📦 选择合适的基础模型

    接下来需要选择一个合适的基础预训练模型,作为微调的起点。常见的有GPT、BERT、T5等大模型,可根据任务场景进行选择。

  3. ⚙️ 设置训练超参数

    然后是设置训练的各种超参数,比如学习率、批量大小、训练步数等等。选择合理的超参数对模型效果影响很大哦。

  4. 🧑‍💻 加载模型和数据集

    使用HuggingFace等库,把选定的基础模型和训练数据集加载进来。记得对数据集进行必要的前处理和划分。

  5. ⚡ 开始模型微调训练

    有了模型、数据集和超参数后,就可以开始模型微调训练了!可以使用PyTorch/TensorFlow等框架进行训练。

  6. 💾 保存微调后的模型

    训练结束后,别忘了把微调好的模型保存下来,方便后续加载使用哦。

  7. 🧪 在测试集上评估模型

    最后在准备好的测试集上评估一下微调后模型的效果。看看与之前的基础模型相比,是否有明显提升?

大语言模型进行微调(Fine Tuning)训练过程及代码

那如何使用 Lamini 库加载数据、设置模型和训练超参数、定义推理函数、微调基础模型、评估模型效果呢?

  • 首先,导入必要的库

    import os
    import lamini
    import datasets
    import tempfile
    import logging
    import random
    import config
    import os
    import yaml
    import time
    import torch
    import transformers
    import pandas as pd
    import jsonlines

    from utilities import *
    from transformers import AutoTokenizer
    from transformers import AutoModelForCausalLM
    from transformers import TrainingArguments
    from transformers import AutoModelForCausalLM
    from llama import BasicModelRunner

这部分导入了一些必需的Python库,包括Lamini、Hugging Face的Datasets、Transformers等。

  • 加载Lamini文档数据集

    dataset_name = "lamini_docs.jsonl"
    dataset_path = f"/content/{dataset_name}"
    use_hf = False
    dataset_path = "lamini/lamini_docs"
    use_hf = True

这里指定了数据集的路径,同时设置了use_hf标志,表示是否使用Hugging Face的Datasets库加载数据。

  • 设置模型、训练配置和分词器

    model_name = "EleutherAI/pythia-70m"
    training_config = { ... }
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    tokenizer.pad_token = tokenizer.eos_token
    train_dataset, test_dataset = tokenize_and_split_data(training_config, tokenizer)

这部分指定了基础预训练模型的名称,并设置了训练配置(如最大长度等)。然后,它使用AutoTokenizer从预训练模型中加载分词器,并对分词器进行了一些调整。最后,它调用tokenize_and_split_data函数对数据进行分词和划分训练/测试集。

  • 加载基础模型

    base_model = AutoModelForCausalLM.from_pretrained(model_name)
    device_count = torch.cuda.device_count()
    if device_count > 0:
    device = torch.device("cuda")
    else:
    device = torch.device("cpu")
    base_model.to(device)

这里使用AutoModelForCausalLM从预训练模型中加载基础模型,并根据设备(GPU或CPU)将模型移动到相应的设备上。

  • 定义推理函数

    def inference(text, model, tokenizer, max_input_tokens=1000, max_output_tokens=100):
    ...

这个函数用于在给定输入文本的情况下,使用模型和分词器进行推理并生成输出。它包括对输入文本进行分词、使用模型生成输出以及解码输出等步骤。

  • 尝试使用基础模型进行推理

    test_text = test_dataset[0]['question']
    print("Question input (test):", test_text)
    print(f"Correct answer from Lamini docs: {test_dataset[0]['answer']}")
    print("Model's answer: ")
    print(inference(test_text, base_model, tokenizer))

这部分使用上一步定义的inference函数,在测试数据集的第一个示例上尝试使用基础模型进行推理。它打印了输入问题、正确答案和模型的输出。

  • 设置训练参数

    max_steps = 3
    trained_model_name = f"lamini_docs_{max_steps}_steps"
    output_dir = trained_model_name
    training_args = TrainingArguments(

    # Learning rate
    learning_rate=1.0e-5,
    
    # Number of training epochs
    num_train_epochs=1,
    
    # Max steps to train for (each step is a batch of data)
    # Overrides num_train_epochs, if not -1
    max_steps=max_steps,
    
    # Batch size for training
    per_device_train_batch_size=1,
    
    # Directory to save model checkpoints
    output_dir=output_dir,
    
    # Other arguments
    overwrite_output_dir=False, # Overwrite the content of the output directory
    disable_tqdm=False, # Disable progress bars
    eval_steps=120, # Number of update steps between two evaluations
    save_steps=120, # After # steps model is saved
    warmup_steps=1, # Number of warmup steps for learning rate scheduler
    per_device_eval_batch_size=1, # Batch size for evaluation
    evaluation_strategy="steps",
    logging_strategy="steps",
    logging_steps=1,
    optim="adafactor",
    gradient_accumulation_steps = 4,
    gradient_checkpointing=False,
    
    # Parameters for early stopping
    load_best_model_at_end=True,
    save_total_limit=1,
    metric_for_best_model="eval_loss",
    greater_is_better=False
    

    )

这一部分设置了训练的一些参数,包括最大训练步数、输出模型目录、学习率等超参数。

为什么要这样设置这些训练超参数:

  1. learning_rate=1.0e-5

    学习率控制了模型在每个训练步骤中从训练数据中学习的速度。1e-5是一个相对较小的学习率,可以有助于稳定训练过程,防止出现divergence(发散)的情况。

  2. num_train_epochs=1

    训练的轮数,即让数据在模型上循环多少次。这里设置为1,是因为我们只想进行轻微的微调,避免过度训练(overfitting)。

  3. max_steps=max_steps

    最大训练步数,会覆盖num_train_epochs。这样可以更好地控制训练的总步数。

  4. per_device_train_batch_size=1

    每个设备(GPU/CPU)上的训练批量大小。批量大小越大,内存占用越高,但训练过程可能更加稳定。

  5. output_dir=output_dir

    用于保存训练过程中的检查点(checkpoints)和最终模型的目录。

  6. overwrite_output_dir=False

    如果目录已存在,是否覆盖它。设为False可以避免意外覆盖之前的结果。

  7. eval_steps=120, save_steps=120

    每120步评估一次模型性能,并保存模型。频繁保存可以在训练中断时恢复。

  8. warmup_steps=1

    学习率warmup步数,一开始使用较小的学习率有助于稳定训练早期阶段。

  9. per_device_eval_batch_size=1

    评估时每个设备上的批量大小。通常与训练时相同。

  10. evaluation_strategy="steps", logging_strategy="steps"

    以步数为间隔进行评估和记录日志,而不是以epoch为间隔。

  11. optim="adafactor"

    使用Adafactor优化器,适用于大规模语言模型训练。

  12. gradient_accumulation_steps=4

    梯度积累步数,可以模拟使用更大批量大小的效果,节省内存。

  13. load_best_model_at_end=True

    保存验证集上性能最好的那个检查点,作为最终模型。

  14. metric_for_best_model="eval_loss", greater_is_better=False

    根据验证损失评估模型,损失越小越好。

model_flops = (
  base_model.floating_point_ops(
    {
       "input_ids": torch.zeros(
           (1, training_config["model"]["max_length"])
      )
    }
  )
  * training_args.gradient_accumulation_steps
)

print(base_model)
print("Memory footprint", base_model.get_memory_footprint() / 1e9, "GB")
print("Flops", model_flops / 1e9, "GFLOPs")


print(base_model)
print("Memory footprint", base_model.get_memory_footprint() / 1e9, "GB")
print("Flops", model_flops / 1e9, "GFLOPs")

这里还计算并打印了模型的内存占用和计算复杂度(FLOPs)。

最后,使用这些参数创建了一个Trainer对象,用于实际进行模型训练。

trainer = Trainer(
    model=base_model,
    model_flops=model_flops,
    total_steps=max_steps,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=test_dataset,
)
  • 训练模型几个步骤

    training_output = trainer.train()

这一行代码启动了模型的微调训练过程,并将训练输出存储在training_output中。

  • 保存微调后的模型

    save_dir = f'{output_dir}/final'
    trainer.save_model(save_dir)
    print("Saved model to:", save_dir)
    finetuned_slightly_model = AutoModelForCausalLM.from_pretrained(save_dir, local_files_only=True)
    finetuned_slightly_model.to(device)

这部分将微调后的模型保存到指定的目录中。

然后,它使用AutoModelForCausalLM.from_pretrained从保存的模型中重新加载该模型,并将其移动到相应的设备上。

  • 使用微调后的模型进行推理

    test_question = test_dataset[0]['question']
    print("Question input (test):", test_question)
    print("Finetuned slightly model's answer: ")
    print(inference(test_question, finetuned_slightly_model, tokenizer))
    test_answer = test_dataset[0]['answer']
    print("Target answer output (test):", test_answer)

这里使用之前定义的inference函数,在测试数据集的第一个示例上尝试使用微调后的模型进行推理。

打印了输入问题、模型输出以及正确答案。

  • 加载并运行其他预训练模型

    finetuned_longer_model = AutoModelForCausalLM.from_pretrained("lamini/lamini_docs_finetuned")
    tokenizer = AutoTokenizer.from_pretrained("lamini/lamini_docs_finetuned")
    finetuned_longer_model.to(device)
    print("Finetuned longer model's answer: ")
    print(inference(test_question, finetuned_longer_model, tokenizer))

    bigger_finetuned_model = BasicModelRunner(model_name_to_id["bigger_model_name"])
    bigger_finetuned_output = bigger_finetuned_model(test_question)
    print("Bigger (2.8B) finetuned model (test): ", bigger_finetuned_output)

这部分加载了另一个经过更长时间微调的模型,以及一个更大的2.8B参数的微调模型。它使用这些模型在测试数据集的第一个示例上进行推理,并打印出结果。

相关推荐
过于真实呢3 分钟前
3-5 提高模型效果:归一化
人工智能·python·自然语言处理
Alice_JC17 分钟前
《昇思25天学习打卡营第11天|计算机视觉-ResNet50迁移学习》
深度学习·学习·计算机视觉·迁移学习
The Open Group1 小时前
The Open Group 2024架构·AI标准峰会——合作伙伴+演讲嘉宾预热征集中!
人工智能·架构
阿_旭1 小时前
【YOLOv9教程】如何使用YOLOv9进行图像与视频检测
人工智能·深度学习·目标检测·ai·yolov9
林叔聊渠道分销1 小时前
从0到1构建渠道运营体系:实战案例与策略指南
大数据·运维·人工智能·产品运营·流量运营·渠道运营
X.AI6661 小时前
【大模型LLM面试合集】大语言模型基础_LLM为什么Decoder only架构
人工智能·语言模型·架构
讳疾忌医丶1 小时前
卷积神经网络基础篇
深度学习·神经网络·cnn
galaxylove1 小时前
被⽹络罪犯利⽤的5⼤ChatGPT越狱提⽰
人工智能·chatgpt
dtge1 小时前
【ChatGPT】全面解析 ChatGPT:从起源到未来
人工智能·chatgpt
robinfang20192 小时前
Meerkat:第一个统一视听空间和时间定位的MLLM
大数据·人工智能·机器学习·语言模型