写过一篇 发表于 2024-9-11 13:46:54

重新开始微调Llama 3.1模型

https://img-blog.csdnimg.cn/img_convert/cb5537d3d77accfde675039521e98b61.png

在本日的科技专栏中,我们将深入探讨怎样微调Llama 3.1模型,以使其更好地适应您的特定领域数据。微调大型语言模型(如Llama)的重要目的是为了在特定领域的数据上体现更好,从而生成更符合您需求的输出。以下是我们将要先容的五个重要步调:

[*]安装须要的软件包
[*]准备数据集
[*]练习模型
[*]举行推理
[*]生存模型
第一步:安装须要的软件包

起首,我们需要安装一些须要的软件包unsloth和torch,我们将使用它来练习模型,以及accelerate和bitsandbytes等其他工具。值得一提的是,我们使用的是Google Colab提供的免费T4 GPU,这意味着您可以在无需花费任何费用的情况下练习您的模型,这无疑是一个很棒的功能。
!pip install "unsloth @ git+https://github.com/unslothai/unsloth.git"
!pip install --no-deps "trl<0.9.0" peft accelerate bitsandbytes
第二步:准备数据集

在这一部分,我们将加载并准备我们的Llama 3.1模型。起首,我们需要导入须要的软件包,如UNS sloth和torch,并设置最大序列长度、数据类型等参数。
import unsloth import FastLanguageModel
import torch

max_sequence_length = 2048
dtype = None
load_in_4bit = True
接下来,我们将从UNS sloth加载模型,并使用Laura技能来只更新1%到10%的参数。这样做的好处是可以或许更高效地举行练习。
model,tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Meta-Llama-3.1-8B",
    max_seq_length = max_sequence_length ,
    dtype = dtype,
    load_in_4bit = load_in_4bit
)
第三步:练习模型

如今我们已经准备好了数据集,可以开始练习模型了。在这一步中,我们将配置练习参数,并使用Alpaca数据集来举行练习。
from datasets import load_dataset

data = load_dataset('alpaca', split='train')
data = data.rename_column('output', 'response')
接下来,我们将配置练习参数,并开始练习模型。
from transformers import Trainer, TrainingArguments

training_args = TrainingArguments(
    output_dir='./results',
    num_train_epochs=3,
    per_device_train_batch_size=8,
    save_steps=10_000,
    save_total_limit=2,
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=data,
)

trainer.train()
练习完成后,我们可以查看练习的内存和时间统计信息。
print(trainer.state.log_history)
第四步:举行推理

练习完成后,我们可以举行推理。起首,我们需要加载模型并对输入举行标记化处理。然后,我们将生成模型的输出。
from transformers import pipeline

inference_pipeline = pipeline('text-generation', model=model)
input_text = "请介绍一下Llama 3.1模型的应用场景。"
outputs = inference_pipeline(input_text)

for i, output in enumerate(outputs):
    print(f"Output {i+1}: {output['generated_text']}")
此外,我们还可以使用Hugging Face的新功能——TextStreamer举行实时流式输出,这样我们就无需等候最闭幕果。
from transformers import TextStreamer

streamer = TextStreamer(model=model)
input_text = "请介绍一下Llama 3.1模型的应用场景。"
streamer(input_text)
第五步:生存模型

末了,我们需要生存已经练习好的模型。最好的方法是将其推送到Hugging Face Hub,这样就可以随时访问和使用模型。
model.save_pretrained('path_to_your_model')
tokenizer.save_pretrained('path_to_your_tokenizer')

from huggingface_hub import HfApi

api = HfApi()
api.upload_folder(
    folder_path='path_to_your_model',
    path_in_repo='your_repo_name',
    repo_id='your_username/your_repo_name',
    token='your_huggingface_token'
如果您盼望以不同的格式(如16位、4位或更低的适配器)生存模型,也可以举行相应的配置。
总结

通过以上五个步调,我们已经完成了Llama 3.1模型的微调。从安装须要的软件包到准备数据集,再到练习模型、举行推理,末了是生存模型,每一步都至关紧张。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 重新开始微调Llama 3.1模型