精调llama模型

2023-12-01 00:30
文章标签 模型 llama 精调

本文主要是介绍精调llama模型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

github地址:https://github.com/facebookresearch/llama-recipes
github:https://github.com/facebookresearch/llama

import torch
from transformers import LlamaForCausalLM, LlamaTokenizer#model_id="./models_hf/7B"
# 可以从huggingface上面下载模型,hf就是huggingface模型,也可以通过transformer库的convert_llama_weights_to_hf方法来转换原始的llama模型
model_id="模型path/Llama-2-7b-chat-hf-local"tokenizer = LlamaTokenizer.from_pretrained(model_id)model =LlamaForCausalLM.from_pretrained(model_id, load_in_8bit=True, device_map='auto', torch_dtype=torch.float16)
from llama_recipes.utils.dataset_utils import get_preprocessed_dataset
from llama_recipes.configs.datasets import samsum_datasettrain_dataset = get_preprocessed_dataset(tokenizer, samsum_dataset, 'train')
eval_prompt = """
Summarize this dialog:
A: Hi Tom, are you busy tomorrow’s afternoon?
B: I’m pretty sure I am. What’s up?
A: Can you go with me to the animal shelter?.
B: What do you want to do?
A: I want to get a puppy for my son.
B: That will make him so happy.
A: Yeah, we’ve discussed it many times. I think he’s ready now.
B: That’s good. Raising a dog is a tough issue. Like having a baby ;-)
A: I'll get him one of those little dogs.
B: One that won't grow up too big;-)
A: And eat too much;-))
B: Do you know which one he would like?
A: Oh, yes, I took him there last Monday. He showed me one that he really liked.
B: I bet you had to drag him away.
A: He wanted to take it home right away ;-).
B: I wonder what he'll name it.
A: He said he’d name it after his dead hamster – Lemmy  - he's  a great Motorhead fan :-)))
---
Summary:
"""model_input = tokenizer(eval_prompt, return_tensors="pt").to("cuda")model.eval()
with torch.no_grad():print(tokenizer.decode(model.generate(**model_input, max_new_tokens=100)[0], skip_special_tokens=True))model.train()def create_peft_config(model):from peft import (get_peft_model,LoraConfig,TaskType,prepare_model_for_int8_training,)peft_config = LoraConfig(task_type=TaskType.CAUSAL_LM,inference_mode=False,r=8,lora_alpha=32,lora_dropout=0.05,target_modules = ["q_proj", "v_proj"])# prepare int-8 model for trainingmodel = prepare_model_for_int8_training(model)model = get_peft_model(model, peft_config)model.print_trainable_parameters()return model, peft_config# create peft config
model, lora_config = create_peft_config(model)from transformers import TrainerCallback
from contextlib import nullcontext
enable_profiler = False
output_dir = "tmp/llama-output"config = {'lora_config': lora_config,'learning_rate': 1e-4,'num_train_epochs': 1,'gradient_accumulation_steps': 2,'per_device_train_batch_size': 2,'gradient_checkpointing': False,
}# Set up profiler
if enable_profiler:wait, warmup, active, repeat = 1, 1, 2, 1total_steps = (wait + warmup + active) * (1 + repeat)schedule =  torch.profiler.schedule(wait=wait, warmup=warmup, active=active, repeat=repeat)profiler = torch.profiler.profile(schedule=schedule,on_trace_ready=torch.profiler.tensorboard_trace_handler(f"{output_dir}/logs/tensorboard"),record_shapes=True,profile_memory=True,with_stack=True)class ProfilerCallback(TrainerCallback):def __init__(self, profiler):self.profiler = profilerdef on_step_end(self, *args, **kwargs):self.profiler.step()profiler_callback = ProfilerCallback(profiler)
else:profiler = nullcontext()from transformers import default_data_collator, Trainer, TrainingArguments# Define training args
training_args = TrainingArguments(output_dir=output_dir,overwrite_output_dir=True,bf16=True,  # Use BF16 if available# logging strategieslogging_dir=f"{output_dir}/logs",logging_strategy="steps",logging_steps=10,save_strategy="no",optim="adamw_torch_fused",max_steps=total_steps if enable_profiler else -1,**{k:v for k,v in config.items() if k != 'lora_config'}
)with profiler:# Create Trainer instancetrainer = Trainer(model=model,args=training_args,train_dataset=train_dataset,data_collator=default_data_collator,callbacks=[profiler_callback] if enable_profiler else [],)# Start trainingtrainer.train()model.save_pretrained(output_dir)model.eval()
with torch.no_grad():print(tokenizer.decode(model.generate(**model_input, max_new_tokens=100)[0], skip_special_tokens=True))

这篇关于精调llama模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/439129

相关文章

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

Java的IO模型、Netty原理解析

《Java的IO模型、Netty原理解析》Java的I/O是以流的方式进行数据输入输出的,Java的类库涉及很多领域的IO内容:标准的输入输出,文件的操作、网络上的数据传输流、字符串流、对象流等,这篇... 目录1.什么是IO2.同步与异步、阻塞与非阻塞3.三种IO模型BIO(blocking I/O)NI

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)

《C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)》本文主要介绍了C#集成DeepSeek模型实现AI私有化的方法,包括搭建基础环境,如安装Ollama和下载DeepS... 目录前言搭建基础环境1、安装 Ollama2、下载 DeepSeek R1 模型客户端 ChatBo

SpringBoot快速接入OpenAI大模型的方法(JDK8)

《SpringBoot快速接入OpenAI大模型的方法(JDK8)》本文介绍了如何使用AI4J快速接入OpenAI大模型,并展示了如何实现流式与非流式的输出,以及对函数调用的使用,AI4J支持JDK8... 目录使用AI4J快速接入OpenAI大模型介绍AI4J-github快速使用创建SpringBoot

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

Spring AI Alibaba接入大模型时的依赖问题小结

《SpringAIAlibaba接入大模型时的依赖问题小结》文章介绍了如何在pom.xml文件中配置SpringAIAlibaba依赖,并提供了一个示例pom.xml文件,同时,建议将Maven仓... 目录(一)pom.XML文件:(二)application.yml配置文件(一)pom.xml文件:首

如何在本地部署 DeepSeek Janus Pro 文生图大模型

《如何在本地部署DeepSeekJanusPro文生图大模型》DeepSeekJanusPro模型在本地成功部署,支持图片理解和文生图功能,通过Gradio界面进行交互,展示了其强大的多模态处... 目录什么是 Janus Pro1. 安装 conda2. 创建 python 虚拟环境3. 克隆 janus

本地私有化部署DeepSeek模型的详细教程

《本地私有化部署DeepSeek模型的详细教程》DeepSeek模型是一种强大的语言模型,本地私有化部署可以让用户在自己的环境中安全、高效地使用该模型,避免数据传输到外部带来的安全风险,同时也能根据自... 目录一、引言二、环境准备(一)硬件要求(二)软件要求(三)创建虚拟环境三、安装依赖库四、获取 Dee