2026/1/3 6:30:45
网站建设
项目流程
建设电商平台网站,google网站打不开了,文化体育局网站建设,软件下载网站如何履行安全原文#xff1a;towardsdatascience.com/i-fine-tuned-the-tiny-llama-3-2-1b-to-replace-gpt-4o-7ce1e5619f3d 一个年轻的儿科医生和一位著名的医生#xff0c;谁更能治疗婴儿的咳嗽#xff1f;
虽然两者都是医生#xff0c;都能治疗孩子的咳嗽#xff0c;但儿科医生是一…原文towardsdatascience.com/i-fine-tuned-the-tiny-llama-3-2-1b-to-replace-gpt-4o-7ce1e5619f3d一个年轻的儿科医生和一位著名的医生谁更能治疗婴儿的咳嗽虽然两者都是医生都能治疗孩子的咳嗽但儿科医生是一个能够更好地诊断婴儿的专家对吧这就是微调对较小模型所做的事情。它们使小型、较弱的模型在解决特定问题上比那些声称能做任何事情的巨人做得更好。我最近遇到了一个不得不在两者之间做出选择的情况。我正在构建一个查询路由机器人。它将用户查询路由到正确的部门在那里人工代理将继续对话。在底层这是一个简单的文本分类任务。GPT-4o以及迷你版在这方面做得非常好但它很僵化且昂贵。它是一个封闭模型因此你无法在自己的基础设施上对其进行微调。OpenAI 在其平台上提供微调服务但这对我来说成本太高。训练 GPT-4o 的费用为$25/1M token。我的训练数据很快就达到了几百万 token。此外微调模型的运行成本大约比普通模型高出 50%。在这个成本下我的小型应用程序无法上线。我正处于预算紧张之中备选方案是训练一个开源模型。开源模型在分类任务中表现出色。然而训练需要大量的 GPU 时间。我决定赌在小型模型上。较小的 LLM 是唯一能够以较低成本进行微调并获得良好结果的方法——如果它有效这正是我所希望的。较小的模型可以在廉价硬件上运行并且可以用相对便宜的 GPU 进行微调。此外它们的训练和推理时间比大型 LLM 要快得多。有几个候选模型——Phi3.5、DistillBERT 和 GPT-Neo——但我决定尝试 Meta Llama 3.2 的 1B 模型。这是一个随机选择。也许我最近受到了这个模型炒作的影响。如果你自托管 LLM你的服务器能承受多少压力在这篇文章中我将比较微调后的 Llama 3.2–1b 指令模型与 GPT-4o 在少量提示下的结果。这就是我如何训练以及我发现了什么。微调 Llama 3.2 1B免费是的我在训练上没有花费任何费用。除非你选择正确的策略否则微调可能会很昂贵。你可以重新训练所有参数进行迁移学习或者进行参数高效的微调。第一个全参数训练可能是成本最高且风险最大的。正如你所猜想的它将重新训练模型中的所有 1B 个参数。这将花费大量的时间和预算。此外全参数微调还受到所谓的“灾难性遗忘”的影响。这意味着当你微调一个模型时它可能会丢失预训练阶段学习的一些先前知识。第二个迁移学习是一个不错的选择但稍微复杂一些。迁移学习你可以学习的最高杠杆深度学习技能最后参数优化微调PEFT成本低且有效。其想法是只训练一些参数。更具体地说**低秩适应LORA**是所有微调策略中的最佳选择。在 Lora 中我们只对少数几个选定的层中的参数子集进行微调使微调既快速又有效。另一个可以显著减少训练基础设施需求的重大决策是量化。为了理解我们可以将模型的参数存储为 float16 值或更小的值。较小的值在内存中占用的空间更少计算速度更快。但这也以牺牲精度为代价。我们现在已经决定采用 LORA 作为微调策略。但我们在哪里可以获得免费的训练基础设施Colab 或 Kaggle 笔记本。这些平台提供免费的 GPU通常足以微调这个小型模型。微调后的 Llama-3.2 与 OpenAI GPT-4o 的少样本提示比较LORA 微调非常流行。我不想再给你另一个教程。查看由 Unsloth 提供的 Colab 笔记本它有一个出色的分步指南。实际上我也一直在使用这个笔记本进行我的微调任务。让我告诉你需要更改的内容。首先笔记本正在微调 3B 参数的 Llama-3.2。如果你希望保持原样可以这么做或者你也可以从众多可用的模型中选择一个。我已经将其更改为 Llama-3.2–1B-Instruct因为我想要测试最小的模型是否足够满足我的任务需求。然后有一个单元格将数据集转换为所需的格式。我已经将其更改为使用我的微调数据集。# Beforefromunsloth.chat_templatesimportstandardize_sharegpt datasetstandardize_sharegpt(dataset)datasetdataset.map(formatting_prompts_func,batchedTrue,)# AfterfromdatasetsimportDataset datasetDataset.from_json(/content/insurance_training_data.json)datasetdataset.map(formatting_prompts_func,batchedTrue,)最简单的方法是使用符合笔记本初始用途的数据集如下所示。{conversations:[{role:user,content:user_query}{role:assistant,content:department}]}就这些。这两个更改就足以根据你自己的数据微调一个模型。评估微调模型现在是激动人心的部分。LLM 评估是一个广泛且有趣的话题。我认为这也是最有价值的 LLM 开发技能。我之前的文章讨论了评估 LLM 应用。最有价值的 LLM 开发技能易于学习但实践成本高昂然而我将使用经典的混淆矩阵风格评估来保持事情整洁。在笔记本的末尾添加以下代码即可。fromlangchain.promptsimportFewShotPromptTemplatefromlangchain_openaiimportChatOpenAIfromlangchain_core.promptsimportPromptTemplatefrompydanticimportBaseModel# 1\. A function to generate response with the fine-tuned modeldefgenerate_response(user_query):# Enable faster inference for the language modelFastLanguageModel.for_inference(model)# Define the message templatemessages[{role:system,content:You are a helpful assistant who can route the following query to the relevant department.},{role:user,content:user_query},]# Apply the chat template to tokenize the input and prepare for generationtokenized_inputtokenizer.apply_chat_template(messages,tokenizeTrue,add_generation_promptTrue,# Required for text generationreturn_tensorspt).to(cuda)# Send input to the GPU# Generate a response using the modelgenerated_outputmodel.generate(input_idstokenized_input,max_new_tokens64,use_cacheTrue,# Enable cache for faster generationtemperature1.5,min_p0.1)# Decode the generated tokens into human-readable textdecoded_responsetokenizer.batch_decode(generated_output,skip_special_tokensTrue)[0]# Extract the assistants response (after system/user text)assistant_responsedecoded_response.split(nn)[-1]returnassistant_response# 2\. Generate Responeses with OpenAI GPT-4o# Define the prompt template for the exampleexample_prompt_templatePromptTemplate.from_template(User Query: {user_query}n{department})# Initialize OpenAI LLM (ensure the OPENAI_API_KEY environment variable is set)llmChatOpenAI(temperature0,modelgpt-4o)# Define few-shot examplesexamples[{user_query:I recently had an accident and need to file a claim for my vehicle. Can you guide me through the process?,department:Claims},...]# Create a few-shot prompt templatefew_shot_prompt_templateFewShotPromptTemplate(examplesexamples,example_promptexample_prompt_template,prefixYou are an intelligent assistant for an insurance company. Your task is to route customer queries to the appropriate department.,suffixUser Query: {user_query},input_variables[user_query])# Define the department model to structure the outputclassDepartment(BaseModel):department:str# Function to predict the appropriate department based on user querydefpredict_department(user_query):# Wrap LLM with structured outputstructured_llmllm.with_structured_output(Department)# Create the chain for generating predictionsprediction_chainfew_shot_prompt_template|structured_llm# Invoke the chain with the user query to get the departmentresultprediction_chain.invoke(user_query)returnresult.department# 3\. Read your evaluation dataset and predict departmentsimportjsonwithopen(/content/insurance_bot_evaluation_data (1).json,r)asf:eval_datajson.load(f)forix,iteminenumerate(eval_data):print(f{ix1}of{len(eval_data)})item[open_ai_response]generate_response(item[user_query])item[llama_response]item[open_ai_response]# 4\. Compute the precision, recall, accuracy, and F1 scores for the predictions.# 4.1 Using Open AIfromsklearn.metricsimportprecision_score,recall_score,accuracy_score,f1_score true_labels[item[department]foritemineval_data]predicted_labels_openai[item[open_ai_response]foritemineval_data]# Calculate the scores for open_ai_responseprecision_openaiprecision_score(true_labels,predicted_labels_openai,averageweighted)recall_openairecall_score(true_labels,predicted_labels_openai,averageweighted)accuracy_openaiaccuracy_score(true_labels,predicted_labels_openai)f1_openaif1_score(true_labels,predicted_labels_openai,averageweighted)print(OpenAI Response Scores:)print(Precision:,precision_openai)print(Recall:,recall_openai)print(Accuracy:,accuracy_openai)print(F1 Score:,f1_openai)# 4.2 Using Fine-tuned Llama 3.2 1B Instructtrue_labels[item[department]foritemineval_data]predicted_labels_llama[item[llama_response]foritemineval_data]# Calculate the scores for llama_responseprecision_llamaprecision_score(true_labels,predicted_labels_llama,averageweighted,zero_division0)recall_llamarecall_score(true_labels,predicted_labels_llama,averageweighted,zero_division0)accuracy_llamaaccuracy_score(true_labels,predicted_labels_llama)f1_llamaf1_score(true_labels,predicted_labels_llama,averageweighted,zero_division0)print(Llama Response Scores:)print(Precision:,precision_llama)print(Recall:,recall_llama)print(Accuracy:,accuracy_llama)print(F1 Score:,f1_llama)上述代码相当直观。我们创建了一个函数使用我们的微调模型来预测部门。我们还为 OpenAI GPT-4o 创建了一个。然后我们使用这些功能来生成对我们评估数据集的响应。评估数据集有预期的类别我们现在有生成的类别这对于计算指标是有好处的。我们将在后续章节中这样做。这里是结果OpenAI Response Scores:Precision:0.9Recall:0.75Accuracy:0.75F1 Score:0.818Llama Response Scores:Precision:0.88Recall:0.73Accuracy:0.79F1 Score:0.798结果显示微调后的结果几乎接近 GPT-4o 的。对于一个只有 1B 参数的小型模型来说这相当令人印象深刻。当然GPT-4o 做得更好但只是略微领先。此外我们本可以在**[few-shot prompt**]中提供更多示例。这将使 GPT-4o 产生更好的结果。但我的示例有时会很长。这将使成本飙升因为 OpenAI 按输入令牌收费。最后的想法我已经成为了小型 LLM 的粉丝。它们速度快成本低对于大多数用例来说足够了——如果不对它们进行微调的话。在这篇文章中我讨论了如何微调 Llama 3.2 1B这是一个可以在相对便宜硬件上运行的模型并且可以免费微调。我手头上的任务是文本分类。然而这并不意味着小型模型会持续优于像 GPT-4o 这样的巨无霸——甚至包括 Meta Llama 的 8B、11B 和 90B 参数模型。更广泛模型拥有如多语言理解、视觉指令和优秀的世界知识等超能力。我的观点是如果那些超能力不是你的关注点为什么不考虑一个微型 LLM 呢感谢阅读朋友除了*Medium*我还在LinkedIn和X,*上