当前位置: 首页 > news >正文

在哪做网站便宜又好网上开店如何推广自己的网店

在哪做网站便宜又好,网上开店如何推广自己的网店,网站建设售后服务安全维护,外贸专业网站制作今天给大家带来了一篇超级详细的教程,手把手教你如何对大语言模型进行微调(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 jsonlinesfrom 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 ratelearning_rate=1.0e-5,# Number of training epochsnum_train_epochs=1,# Max steps to train for (each step is a batch of data)# Overrides num_train_epochs, if not -1max_steps=max_steps,# Batch size for trainingper_device_train_batch_size=1,# Directory to save model checkpointsoutput_dir=output_dir,# Other argumentsoverwrite_output_dir=False, # Overwrite the content of the output directorydisable_tqdm=False, # Disable progress barseval_steps=120, # Number of update steps between two evaluationssave_steps=120, # After # steps model is savedwarmup_steps=1, # Number of warmup steps for learning rate schedulerper_device_eval_batch_size=1, # Batch size for evaluationevaluation_strategy="steps",logging_strategy="steps",logging_steps=1,optim="adafactor",gradient_accumulation_steps = 4,gradient_checkpointing=False,# Parameters for early stoppingload_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参数的微调模型。它使用这些模型在测试数据集的第一个示例上进行推理,并打印出结果。

http://www.yidumall.com/news/31604.html

相关文章:

  • 设计一份包含网站建设范深圳外贸网站推广
  • 个人博客网站模板源码搜索引擎google
  • 益阳北京网站建设市场调研方法有哪些
  • ssm实战项目网站开发武汉大学人民医院精神卫生中心
  • 传统纸媒公司网站建设需求百度最新收录方法
  • 宝安做棋牌网站建设哪家公司收费合理常用的网络推广手段有哪些
  • html购物网站企业seo排名外包
  • 公司多个门户是做二级域名还是做多个网站seo分析工具
  • 兰州做网站优化企业推广网络营销外包服务
  • 宁波seo网络推广代理价格seo排名第一的企业
  • 网站建设教程浩森宇特营销软文800字范文
  • 龙泉做网站哪家好网站收录查询
  • 金泉网普通会员可以建设网站吗网络营销优化
  • 北京搜索引擎推广系统搜索引擎优化要考虑哪些方面
  • 陕西省建设执业注册中心网站公司网站建设服务机构
  • 做修图网站电脑配置网络推广员工作好做吗
  • 招聘网站开发学徒2021年经典营销案例
  • 智能建造师证书有用吗比较好的网络优化公司
  • 网站怎么做视频百度手机卫士
  • 自学web前端能找到工作吗seo企业优化顾问
  • 庞各庄网站建设优秀的网页设计案例
  • 旅游网站html5代码模板夸克搜索引擎
  • 舟山网站制作网页制作代码
  • 做网站怎么接广告赚钱拓客软件排行榜
  • 柳州企业做网站西安seo外包优化
  • 企业网站方案设计小红书搜索指数
  • 毕业设计网站代做多少钱汉中网络推广
  • 公司注册流程步骤图青岛设计优化公司
  • 青岛网景互联网站建设公司郑州seo优化顾问阿亮
  • 章丘灵通环保设备在哪个网站上做的中国域名注册局官网