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

张小明 2026/1/16 4:06:47
长沙专业外贸建站公司,百度信息流推广教程,苏州十大软件公司招聘,设计本官方网站电脑版实战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进行投诉反馈,一经查实,立即删除!

网站建设的流程与思路企业网站 阿里云

各位技术同仁,下午好!今天,我们将深入探讨一个在现代前端开发中既引人入胜又充满挑战的话题:React 并发模式下的内存压力。特别是,我们将聚焦一个颇具挑衅性的场景:如果同时启动 100 个 Transition 任务&am…

张小明 2026/1/16 9:28:47 网站建设

大型php网站系统在阿里云域名可以做网站吗

Docker镜像源失效怎么办?立即切换至清华镜像恢复TensorFlow构建 在人工智能项目开发中,你是否曾经历过这样的场景:满怀信心地运行 docker pull tensorflow/tensorflow:latest,结果命令行卡住十几分钟,最终报出一串网络…

张小明 2026/1/16 9:40:19 网站建设

做网站赚钱有哪些途径a5wordpress模板

伴随着互联网的发展,它已经成为我们生活中不可或缺的存在,无论是个人还是企业,都离不开互联网。正因为互联网得到了重视,网络安全问题也随之加剧,给我们的信息安全造成严重威胁,而想要有效规避这些风险&…

张小明 2026/1/16 13:38:59 网站建设

aspcms网站打不开个人社团网站怎么做

情感语音合成的未来趋势:从EmotiVoice看行业发展方向 在虚拟主播直播中突然“哽咽”,游戏NPC因剧情转折而语气颤抖,儿童教育APP里的故事讲述者随着情节发展时而紧张、时而欢笑——这些曾经只属于人类表演者的细腻表达,如今正悄然出…

张小明 2026/1/16 13:39:49 网站建设

工业皮带怎么做免费的网站室内设计学校排名榜

GEO的兴起,远不止是一种营销技术的迭代。它像一股暗流,正在深刻重构从信息生产、传播到消费的全链条,催生一个全新的信息生态系统。理解这一系统性变革,才能把握GEO真正的战略高度。一、链条重塑:从“发布-索引-排名”…

张小明 2026/1/9 5:19:13 网站建设

网站开发设计公玉雕网站建设

你是否曾面临这样的困境:业务流程设计工具要么界面陈旧体验差,要么功能单一扩展难,要么性能低下响应慢?传统的流程编辑器往往让开发者陷入"能用但不好用"的尴尬境地。 【免费下载链接】vite-vue-bpmn-process 基于 Vite…

张小明 2026/1/6 1:48:48 网站建设