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

在哪做网站便宜又好公司网页设计

在哪做网站便宜又好,公司网页设计,成都 网站建设 公司,网站优化seo怎么做今天给大家带来了一篇超级详细的教程,手把手教你如何对大语言模型进行微调(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.ds6.com.cn/news/73809.html

相关文章:

  • 百度 安徽省工程建设信息网站东莞做网站的公司吗
  • 建筑营销型网站开鲁网站seo转接
  • 网站功能设计的内容百度网址大全网站
  • asp动态网站开发教程可以看封禁网站的浏览器
  • 怎么修复网站死链网站seo推广排名
  • 站长之家新网址天津seo外包团队
  • 德国 网站建设怎么自己找外贸订单
  • 做设计什么设计比较好的网站健康码防疫核验一体机
  • 旅者志 wordpress主题网站建设seo优化培训
  • 专业展馆展厅设计武汉seo网站优化技巧
  • 在虚拟机中如何做二级域名网站站内推广
  • 织梦网站主页网站seo优化方案项目策划书
  • 网站建设费用计入什么二级科目提交网站收录入口
  • 如何在手机上搭建网站seo软件工具箱
  • 标书制作软件免费版百度seo词条优化
  • 济南建设质量协会网站中国新闻社
  • 贵州贵州省住房和城乡建设厅网站正规接单赚佣金的平台
  • 青岛做网站的费用百度企业推广
  • 网络推广优化网站抖音广告代运营
  • 建设网站筛选网站供应商安卓手机游戏优化器
  • 嵊州做网站厦门网页搜索排名提升
  • 电子产品网站建设策划书什么是百度搜索推广
  • 优秀网站设计案例分析ppt和生活app下载安装最新版
  • 做环保网站案例分析百度信息流是什么
  • 下载网站如何做批量外链工具
  • 高新企业如何在税务网站做备案三亚百度推广开户
  • 自己做网站怎么选架构孝感seo
  • 绵阳手机网站制作巨量引擎广告投放平台官网
  • 网站模板 酒类百度广告怎么收费
  • 封面型网站首页怎么做网站提交收录入口