news 2026/6/24 13:58:25

实战LLaMA2-7B指令微调

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
实战LLaMA2-7B指令微调

实战LLaMA2-7B指令微调

前言:数据质量远胜于数据数量——高质量的指令数据集能极大提升模型效果

1、Alpaca格式介绍

用一套固定的、清晰的格式(指令+输入+响应)来“教”AI如何正确地理解和完成人类的各种请求。

格式如下

### Instruction: (指令内容-作用:告诉AI这次要“扮演”什么角色(翻译官、总结者、提问者等)) ### Input: (输入内容-完成这项任务所需要的具体资料,如一段需要翻译的文字,有时可以为空。比如你的指令是“讲个笑话”,那就不需要额外材料。) ### Response: (期望的回复-这是最关键的部分,是“教学样本”。AI通过成千上万张这样的“工作单”(指令+输入)和“标准答案”(响应)来学习,以后遇到类似的“指令+输入”时,它就能模仿着生成正确的“响应”。)

示例如下

### Instruction: 把这段中文翻译成英文 ### Input: 今天天气真好。 ### Response:t The weather is so nice today.

2、Databricks Dolly-15K数据集介绍

Databricks Dolly-15K 是一个由专家精心制作的、包含1.5万道高质量练习题的开源数据集,专门用于系统性地训练AI,让它变得更聪明、更听话、更有用。其遵循CC开源协议。这意味着任何个人、学校或公司(包括他们的竞争对手)都可以免费下载、使用甚至修改它,用来训练自己的AI模型。这极大地推动了整个AI行业的发展,让更多人能做出好用的AI。

3、实战

1、下载 数据集以 Alpaca-Style 格式化指令数据

fromdatasetsimportload_datasetfromrandomimportrandrange# 下载 databricks-dolly-15k 数据集dataset=load_dataset("databricks/databricks-dolly-15k",split="train")# 以 Alpaca-Style 格式化指令数据defformat_instruction(sample_data):""" Formats the given data into a structured instruction format. Parameters: sample_data (dict): A dictionary containing 'response' and 'instruction' keys. Returns: str: A formatted string containing the instruction, input, and response. """# Check if required keys exist in the sample_dataif'response'notinsample_dataor'instruction'notinsample_data:# Handle the error or return a default messagereturn"Error: 'response' or 'instruction' key missing in the input data."returnf"""### Instruction: Use the Input below to create an instruction, which could have been used to generate the input using an LLM. ### Input:{sample_data['response']}### Response:{sample_data['instruction']}"""# 以 Alpaca-Style 格式化指令数据,然后随机抽选一个样例,打印 Alpaca 格式化后的样例print(format_instruction(dataset[randrange(len(dataset))]))

2、加载和配置模型

使用快速注意力(Flash Attentio) 加速训练,检查硬件是否支持 Flash Attention

python -c"import torch; assert torch.cuda.get_device_capability()[0] >= 8, 'Hardware not supported for Flash Attention'"# 如果硬件不支持,会显示:AssertionError: Hardware not supported for Flash Attention# 如果硬件支持(CUDA compute capability >= 8.0),可以安装 flash-attn 加速包:MAX_JOBS=4pipinstallflash-attn --no-build-isolation
importtorchfromtransformersimportAutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig# 检查硬件是否支持 Flash Attentioniftorch.cuda.get_device_capability()[0]>=8:fromutils.llama_patchimportreplace_attn_with_flash_attnprint("Using flash attention")replace_attn_with_flash_attn()use_flash_attention=Trueelse:use_flash_attention=Falseprint("Hardware not supported for Flash Attention")# 获取 LLAMA 2-7B 模型权重# 无需 Meta AI 审核的模型权重,别人开源的model_id="NousResearch/llama-2-7b-hf"# 通过 Meta AI 审核后可使用此 Model ID 下载# model_id = "meta-llama/llama-2-7b-hf"# 使用 BnB 加载优化后的模型bnb_config=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_use_double_quant=True,bnb_4bit_quant_type="nf4",bnb_4bit_compute_dtype=torch.bfloat16)# 加载模型与分词器model=AutoModelForCausalLM.from_pretrained(model_id,quantization_config=bnb_config,use_cache=False,device_map="auto")# 验证模型是否在使用 flash attentionifuse_flash_attention:fromutils.llama_patchimportforwardassertmodel.model.layers[0].self_attn.forward.__doc__==forward.__doc__,"Model is not using flash attention"tokenizer=AutoTokenizer.from_pretrained(model_id)tokenizer.pad_token=tokenizer.eos_token tokenizer.padding_side="right"
importdatetimefromtransformersimportTrainingArgumentsfrompeftimportLoraConfig,prepare_model_for_kbit_training,get_peft_model# 生成时间戳用于输出目录timestamp=datetime.datetime.now().strftime("%Y%m%d_%H%M%S")# 演示训练参数(实际训练时可设置为 False)demo_train=Trueoutput_dir=f"models/llama-7-int4-dolly-{timestamp}"# 训练超参数配置args=TrainingArguments(output_dir=output_dir,num_train_epochs=1ifdemo_trainelse3,max_steps=100,per_device_train_batch_size=3,# Nvidia T4 16GB 显存支持的最大 Batch Sizegradient_accumulation_steps=1ifdemo_trainelse4,gradient_checkpointing=True,optim="paged_adamw_32bit",logging_steps=10,save_strategy="steps"ifdemo_trainelse"epoch",save_steps=10,learning_rate=2e-4,bf16=True,# 修正:取消注释并启用 bfloat16max_grad_norm=0.3,warmup_ratio=0.03,lr_scheduler_type="constant")# QLoRA 配置peft_config=LoraConfig(lora_alpha=16,lora_dropout=0.1,r=16,bias="none",task_type="CAUSAL_LM",# 修正:将 "CAUSALL_LM" 改为 "CAUSAL_LM")# 使用 QLoRA 配置加载 PEFT 模型model=prepare_model_for_kbit_training(model)qlora_model=get_peft_model(model,peft_config)qlora_model.print_trainable_parameters()

SFTTrainer(监督式微调训练器)来训练模型。

fromtrlimportSFTTrainer# 数据库的最大长度序列(筛选后的训练数据样例数为1158)max_seq_length=2048trainer=SFTTrainer(model=qlora_model,# 修正为 qlora_modeltrain_dataset=dataset,peft_config=peft_config,max_seq_length=max_seq_length,tokenizer=tokenizer,packing=True,formatting_func=format_instruction,args=args,)

3、开始训练模型

trainer.train()

4、加载和运行经过微调的LLaMA2-7B模型进行推理

# 代码片段1:使用微调后的LLaMA2-7B推理importtorchfrompeftimportAutoPeftModelForCausalLMfromtransformersimportAutoTokenizer# model_dir = "models/llama-7-int4-dolly"model_dir="models/llama-7-int4-dolly-20240404_033139"# 加载基础LLM模型与分词器model=AutoPeftModelForCausalLM.from_pretrained(model_dir,low_cpu_mem_usage=True,torch_dtype=torch.float16,load_in_4bit=True,)tokenizer=AutoTokenizer.from_pretrained(model_dir)# 代码片段2:生成测试样本fromdatasetsimportload_datasetfromrandomimportrandrange# 从hub加载数据集并得到一个样本dataset=load_dataset("databricks/databricks-dolly-15k",split="train")sample=dataset[randrange(len(dataset))]prompt=f"""### Instruction: Use the Input below to create an instruction, which could have been used to generate the input using an LLM. ### Input:{sample['response']}### Response: """input_ids=tokenizer(prompt,return_tensors="pt",truncation=True).input_ids.cuda()outputs=model.generate(input_ids=input_ids,max_new_tokens=100,do_sample=True,top_p=0.9,temperature=0.9)print(f"Prompt:\n{sample['response']}\n")print(f"Generated instruction:\n{tokenizer.batch_decode(outputs.detach().cpu().numpy(),skip_special_tokens=True)[0][len(prompt):]}")print(f"Ground truth:\n{sample['instruction']}")

预期输出格式,示例

Prompt: The process of photosynthesis in plants converts light energy, usually from the sun, into chemical energy stored in glucose. This vital reaction takes place in the chloroplasts of plant cells and requires water and carbon dioxide, releasing oxygen as a byproduct. Generated instruction: Explain the process of photosynthesis in plants. Ground truth: Describe how photosynthesis works in plants.
  1. Prompt:部分是从数据集中随机抽取的一个“回答”。它是一段关于光合作用的陈述性事实。
  2. Generated instruction:部分是你的微调模型根据上面的回答所生成的“指令”。它学会了将一段陈述性文字,转换成一个可以引导LLM生成类似文本的提问式指令。
  3. Ground truth:部分是数据集中人工编写的、与该回答配对的真实指令。它作为“标准答案”,用于评估模型生成指令的质量。
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/22 20:52:22

SpringAI MCP入门:零基础搭建首个AI增强应用

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容: 创建一个面向新手的SpringAI MCP学习项目,要求:1. 从零开始配置开发环境的分步指南;2. 实现一个带AI功能的TODO应用(基础CRUD智能任务…

作者头像 李华
网站建设 2026/6/23 18:01:04

传统VS Phyfusion:物理开发效率提升300%的秘诀

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容: 创建一个对比Demo:左侧展示传统方式手写代码实现的简单物理场景(如Jenga积木塔),右侧展示Phyfusion生成的相同场景。要求&#xff1a…

作者头像 李华
网站建设 2026/6/24 4:23:55

【开题答辩全过程】以 基于微信小程序的失物认领系统为例,包含答辩的问题和答案

个人简介一名14年经验的资深毕设内行人,语言擅长Java、php、微信小程序、Python、Golang、安卓Android等开发项目包括大数据、深度学习、网站、小程序、安卓、算法。平常会做一些项目定制化开发、代码讲解、答辩教学、文档编写、也懂一些降重方面的技巧。感谢大家的…

作者头像 李华
网站建设 2026/6/24 2:57:42

数字色彩的骨架:计算机如何理解颜色

视觉的生理基础与数学化 人类视觉系统对色彩的感知依赖于视网膜上的三种视锥细胞,它们分别对长波、中波和短波敏感。这种生物学特性直接决定了计算机图形学的底层逻辑。技术人员并不需要模拟自然界中连续且无限的光谱,只需要通过特定比例混合三种基础光…

作者头像 李华
网站建设 2026/6/24 14:29:53

服务器文件管理太麻烦?宝塔 FTP+cpolar 让远程操作像本地一样简单

文章目录前言1. Linux安装Cpolar2. 创建FTP公网地址3. 宝塔FTP服务设置4. FTP服务远程连接小结5. 固定FTP公网地址6. 固定FTP地址连接**宝塔 FTP 让服务器文件管理变得简单,而 cpolar 则打破了局域网的限制,两者结合为远程文件操作提供了安全、高效的解决…

作者头像 李华