长沙专业外贸建站公司百度信息流推广教程

张小明 2026/1/10 19:08:04
长沙专业外贸建站公司,百度信息流推广教程,苏州十大软件公司招聘,设计本官方网站电脑版实战LLaMA2-7B指令微调 前言#xff1a;数据质量远胜于数据数量——高质量的指令数据集能极大提升模型效果 1、Alpaca格式介绍 用一套固定的、清晰的格式#xff08;指令输入响应#xff09;来“教”AI如何正确地理解和完成人类的各种请求。 格式如下 ### Instruction: (指令…实战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 数据集datasetload_dataset(databricks/databricks-dolly-15k,splittrain)# 以 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_dataifresponsenotinsample_dataorinstructionnotinsample_data:# Handle the error or return a default messagereturnError: 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 Attentionpython -cimport 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_JOBS4pipinstallflash-attn --no-build-isolationimporttorchfromtransformersimportAutoTokenizer,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_attentionTrueelse:use_flash_attentionFalseprint(Hardware not supported for Flash Attention)# 获取 LLAMA 2-7B 模型权重# 无需 Meta AI 审核的模型权重别人开源的model_idNousResearch/llama-2-7b-hf# 通过 Meta AI 审核后可使用此 Model ID 下载# model_id meta-llama/llama-2-7b-hf# 使用 BnB 加载优化后的模型bnb_configBitsAndBytesConfig(load_in_4bitTrue,bnb_4bit_use_double_quantTrue,bnb_4bit_quant_typenf4,bnb_4bit_compute_dtypetorch.bfloat16)# 加载模型与分词器modelAutoModelForCausalLM.from_pretrained(model_id,quantization_configbnb_config,use_cacheFalse,device_mapauto)# 验证模型是否在使用 flash attentionifuse_flash_attention:fromutils.llama_patchimportforwardassertmodel.model.layers[0].self_attn.forward.__doc__forward.__doc__,Model is not using flash attentiontokenizerAutoTokenizer.from_pretrained(model_id)tokenizer.pad_tokentokenizer.eos_token tokenizer.padding_siderightimportdatetimefromtransformersimportTrainingArgumentsfrompeftimportLoraConfig,prepare_model_for_kbit_training,get_peft_model# 生成时间戳用于输出目录timestampdatetime.datetime.now().strftime(%Y%m%d_%H%M%S)# 演示训练参数实际训练时可设置为 Falsedemo_trainTrueoutput_dirfmodels/llama-7-int4-dolly-{timestamp}# 训练超参数配置argsTrainingArguments(output_diroutput_dir,num_train_epochs1ifdemo_trainelse3,max_steps100,per_device_train_batch_size3,# Nvidia T4 16GB 显存支持的最大 Batch Sizegradient_accumulation_steps1ifdemo_trainelse4,gradient_checkpointingTrue,optimpaged_adamw_32bit,logging_steps10,save_strategystepsifdemo_trainelseepoch,save_steps10,learning_rate2e-4,bf16True,# 修正取消注释并启用 bfloat16max_grad_norm0.3,warmup_ratio0.03,lr_scheduler_typeconstant)# QLoRA 配置peft_configLoraConfig(lora_alpha16,lora_dropout0.1,r16,biasnone,task_typeCAUSAL_LM,# 修正将 CAUSALL_LM 改为 CAUSAL_LM)# 使用 QLoRA 配置加载 PEFT 模型modelprepare_model_for_kbit_training(model)qlora_modelget_peft_model(model,peft_config)qlora_model.print_trainable_parameters()SFTTrainer监督式微调训练器来训练模型。fromtrlimportSFTTrainer# 数据库的最大长度序列筛选后的训练数据样例数为1158max_seq_length2048trainerSFTTrainer(modelqlora_model,# 修正为 qlora_modeltrain_datasetdataset,peft_configpeft_config,max_seq_lengthmax_seq_length,tokenizertokenizer,packingTrue,formatting_funcformat_instruction,argsargs,)3、开始训练模型trainer.train()4、加载和运行经过微调的LLaMA2-7B模型进行推理# 代码片段1使用微调后的LLaMA2-7B推理importtorchfrompeftimportAutoPeftModelForCausalLMfromtransformersimportAutoTokenizer# model_dir models/llama-7-int4-dollymodel_dirmodels/llama-7-int4-dolly-20240404_033139# 加载基础LLM模型与分词器modelAutoPeftModelForCausalLM.from_pretrained(model_dir,low_cpu_mem_usageTrue,torch_dtypetorch.float16,load_in_4bitTrue,)tokenizerAutoTokenizer.from_pretrained(model_dir)# 代码片段2生成测试样本fromdatasetsimportload_datasetfromrandomimportrandrange# 从hub加载数据集并得到一个样本datasetload_dataset(databricks/databricks-dolly-15k,splittrain)sampledataset[randrange(len(dataset))]promptf### 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_idstokenizer(prompt,return_tensorspt,truncationTrue).input_ids.cuda()outputsmodel.generate(input_idsinput_ids,max_new_tokens100,do_sampleTrue,top_p0.9,temperature0.9)print(fPrompt:\n{sample[response]}\n)print(fGenerated instruction:\n{tokenizer.batch_decode(outputs.detach().cpu().numpy(),skip_special_tokensTrue)[0][len(prompt):]})print(fGround 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.Prompt:部分是从数据集中随机抽取的一个“回答”。它是一段关于光合作用的陈述性事实。Generated instruction:部分是你的微调模型根据上面的回答所生成的“指令”。它学会了将一段陈述性文字转换成一个可以引导LLM生成类似文本的提问式指令。Ground truth:部分是数据集中人工编写的、与该回答配对的真实指令。它作为“标准答案”用于评估模型生成指令的质量。
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

哪些网站可以直接做英文字谜建立免费网站的步骤

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容: 创建一个Oracle数据库连接配置生成器,功能包括:1. 支持TNS连接和SID/SERVICE_NAME两种模式;2. 自动生成包含SSL配置的连接字符串;3. …

张小明 2025/12/25 20:25:14 网站建设

企业品牌营销推广seo查询价格

Linly-Talker在消防应急演练中的语音指挥应用 在一场高层建筑的消防应急演练中,刺耳的警报声响起,人群开始有序疏散。与此同时,监控大屏上一位神情严肃的“指挥官”正通过清晰、镇定的声音发布指令:“请三楼东侧人员沿安全通道向南…

张小明 2025/12/25 20:24:41 网站建设

wordpress设置2个网站吗网站导航结构设计

csp信奥赛C标准模板库STL(10):priority_queue的使用详解 一、什么是优先队列? priority_queue是一种容器适配器,它提供了一种可以快速访问“最大”或“最小”元素的队列。它的底层通常由堆(Heap&#xff0…

张小明 2026/1/10 18:35:05 网站建设

做网站公司简介模版微信app

一、现在的真实情况:查重过了,论文却被卡 AI 率 这两年,很多同学都会遇到一个很反直觉的情况: 重复率 5%–10%,老师点头 AI 率 40%–70%,直接打回 问题不在你“是不是抄袭”,而在于—— 现在…

张小明 2026/1/2 0:12:33 网站建设

内部网络网站怎么做百度搜索指数排行

在毕业季的钟声敲响之际,无数毕业生都站在了论文写作的“战场”前,既兴奋又忐忑。毕业论文,作为大学生涯的“终极BOSS”,不仅考验着我们的知识储备,更考验着我们的写作能力和创新思维。不过,别担心&#xf…

张小明 2025/12/25 20:22:30 网站建设

可视化网站后台管理系统东莞有哪些好企业

5分钟掌握WireViz:零基础绘制专业线束图 【免费下载链接】WireViz Easily document cables and wiring harnesses. 项目地址: https://gitcode.com/gh_mirrors/wi/WireViz 在现代电子工程和自动化系统中,线束设计是不可或缺的重要环节。传统的线束…

张小明 2025/12/25 20:21:58 网站建设