深圳网站建设深圳网络,定制商品的网站建设,视觉设计作品集,要建设网站原文#xff1a;towardsdatascience.com/how-to-improve-llms-with-rag-abdc132f76ac 本文是关于在实践中使用大型语言模型的一个更大系列的一部分。在上一篇文章中#xff0c;我们使用 QLoRA 将 Mistral-7b-Instruct 微调以响应 YouTube 评论。尽管微调后的模型在回应观众反…原文towardsdatascience.com/how-to-improve-llms-with-rag-abdc132f76ac本文是关于在实践中使用大型语言模型的一个更大系列的一部分。在上一篇文章中我们使用 QLoRA 将 Mistral-7b-Instruct 微调以响应 YouTube 评论。尽管微调后的模型在回应观众反馈时成功捕捉到了我的风格但其对技术问题的回答并没有匹配我的解释。在这里我将讨论如何通过检索增强生成即 RAG来提高 LLM 的性能。https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/883f1a0b046090f06081491eba20e773.png原始的 RAG 系统。图片来自 Canva。大型语言模型LLMs在存储和部署大量知识以响应用户查询方面展现出了令人印象深刻的能力。虽然这已经使得像 ChatGPT 这样的强大 AI 系统的创建成为可能但这种方式压缩世界知识有两个关键限制。首先LLM 的知识是静态的即当新信息可用时不会更新。其次LLM 可能对在训练数据中不突出的细分和专业知识“理解”不足。这些限制可能导致模型对用户查询的响应不理想甚至可能是虚构的。我们可以减轻这些限制的一种方法是通过一个专业且可变的知识库来增强模型例如客户常见问题解答、软件文档或产品目录。这有助于创建更稳健和适应性强的 AI 系统。检索增强生成或称RAG是此类方法之一。在此我提供一个对 RAG 的高级介绍并分享使用 LlamaIndex 实现 RAG 系统的 Python 代码示例。cdn.embedly.com/widgets/media.html?srchttps%3A%2F%2Fwww.youtube.com%2Fembed%2FYlz779Op9Pw%3Ffeature%3Doembeddisplay_nameYouTubeurlhttps%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYlz779Op9Pwimagehttps%3A%2F%2Fi.ytimg.com%2Fvi%2FYlz779Op9Pw%2Fhqdefault.jpgkeya19fcc184b9711e1b4764040d3dc5c07typetext%2Fhtmlschemayoutube什么是 RAGLLM 的基本用法包括提供提示并获取响应。https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/e52a1c0422cd4805c032b17d31e17eca.png大型语言模型LLM的基本用法即输入提示输出响应。图片由作者提供。RAG 通过向基本流程添加一个步骤来工作。具体来说执行一个检索步骤根据用户的提示从外部知识库中提取相关信息并将其注入到提示中然后再传递给 LLM。https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/2c8690feec70f37963061e4d905eccd8.pngRAG 系统概述。图片由作者提供。我们为什么关心注意到 RAG 并没有从根本上改变我们使用 LLM 的方式它仍然是提示输入和响应输出。RAG 只是增强了这个过程因此得名。这使得RAG 成为改进基于 LLM 的系统的一种灵活且相对简单的方法。此外由于知识存储在外部数据库中更新系统知识就像在表中添加或删除记录一样简单。为什么不微调本系列之前的文章讨论了微调这是将现有模型适应特定用例的过程。虽然这是赋予 LLM大型语言模型专业知识的一种替代方法但根据经验微调在实现这一点上似乎不如 RAG检索增强生成有效[1]。如何工作RAG 系统有两个关键元素一个检索器和一个知识库。检索器检索器接收用户提示并从知识库中返回相关项。这通常使用所谓的文本嵌入来实现这是文本在概念空间中的数值表示。换句话说这些是代表给定文本意义的数字。文本嵌入可以用来计算用户查询与知识库中每个项之间的相似度得分。这个过程的结果是每个项与输入查询的相关性排名。检索器可以提取最相关的 k 个例如 k3项并将它们注入到用户提示中。这个增强的提示随后被传递到 LLM 进行生成。https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/eb8ab3b723fb141d1122480c0b971751.png检索步骤概述。图片由作者提供。知识库RAG 系统的下一个关键元素是知识库。这个知识库存储了您希望提供给 LLM 的所有信息。虽然为 RAG 构建知识库有无数种方法但在这里我将专注于从一组文档中构建一个。该过程可以分解为4 个关键步骤[2,3]。加载文档– 这包括收集一组文档并确保它们处于可解析的格式更多内容将在后面介绍。**文档块化—**由于 LLM 的上下文窗口有限文档必须分成更小的块例如256 或 512 个字符长。嵌入块– 使用文本嵌入模型将每个块转换为数字。加载到向量数据库— 将文本嵌入加载到数据库中也称为向量数据库。https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/de4d3df3d814e42d661915bcd26ee9c0.png知识库创建概述。图片由作者提供。一些细节虽然构建 RAG 系统的步骤在概念上很简单但一些细节可能会使在现实世界中构建一个更加复杂。文档准备——RAG 系统的质量取决于从源文档中提取有用信息的能力有多强。例如如果一个文档未格式化且充满图像和表格那么解析起来会比格式良好的文本文件更困难。选择合适的块大小——我们之前已经提到了由于 LLM 上下文窗口的需要而进行分块的原因。然而还有两个额外的分块动机。首先它降低了计算成本。你注入到提示中的文本越多生成完成所需的计算就越多。其次是性能。对于特定查询的相关信息往往集中在源文档中通常一句话就能回答一个问题。分块有助于最小化传递给模型的不相关信息[4]。改进搜索– 虽然文本嵌入提供了一种强大且快速的方式进行搜索但它并不总是像人们希望的那样有效。换句话说它可能返回与用户查询“相似”但无法帮助回答查询的结果例如“洛杉矶的天气怎么样”可能会返回“纽约的天气怎么样”。最简单的方法是通过良好的文档准备和分块来减轻这一点。然而对于某些用例可能需要额外的搜索改进策略例如为每个块使用元标签采用混合搜索它结合了基于关键词和基于嵌入的搜索或者使用重排器这是一个专门计算两段输入文本相似度的模型。示例代码使用 RAG 改进 YouTube 评论响应器在对 RAG 的工作原理有基本了解之后让我们看看如何在实践中使用它。我将基于上一篇文章中的例子我在其中使用 QLoRA 微调了 Mistral-7B-Instruct 以响应 YouTube 评论。我们将使用 LlamaIndex 将 RAG 系统添加到之前微调的模型中。示例代码在Colab 笔记本中免费提供可以在提供的免费T4 GPU 上运行。本例的源文件可在GitHub 仓库中找到。 Google Colab | GitHub 仓库导入我们首先安装并导入必要的 Python 库。!pip install llama-index !pip install llama-index-embeddings-huggingface !pip install peft !pip install auto-gptq !pip install optimum !pip install bitsandbytes# if not running on Colab ensure transformers is installed toofromllama_index.embeddings.huggingfaceimportHuggingFaceEmbeddingfromllama_index.coreimportSettings,SimpleDirectoryReader,VectorStoreIndexfromllama_index.core.retrieversimportVectorIndexRetrieverfromllama_index.core.query_engineimportRetrieverQueryEnginefromllama_index.core.postprocessorimportSimilarityPostprocessor设置知识库我们可以通过定义我们的嵌入模型、块大小和块重叠来配置我们的知识库。在这里我们使用 BAAI 提供的~33M 参数bge-small-en-v1.5嵌入模型该模型可在 Hugging Face hub 上找到。此文本嵌入排行榜上还有其他嵌入模型选项。# import any embedding model on HF hubSettings.embed_modelHuggingFaceEmbedding(model_nameBAAI/bge-small-en-v1.5)Settings.llmNone# we wont use LlamaIndex to set up LLMSettings.chunk_size256Settings.chunk_overlap25接下来我们加载我们的源文档。在这里我有一个名为articles的文件夹其中包含我写的 3 篇关于fat tails的 Medium 文章的 PDF 版本。如果在 Colab 中运行此代码您必须从GitHub 仓库下载文章文件夹并将其手动上传到您的 Colab 环境中。对于此文件夹中的每个文件下面的函数将读取 PDF 中的文本根据之前定义的设置将其拆分为块并将每个块存储在名为documents的列表中。documentsSimpleDirectoryReader(articles).load_data()由于博客是直接从 Medium 下载为 PDF 格式它们更像是一个网页而不是格式良好的文章。因此某些部分可能包含与文章无关的文本例如网页标题和 Medium 文章推荐。在下面的代码块中我精炼了文档中的块移除了文章正文前后的大部分块。print(len(documents))# prints: 71fordocindocuments:ifMember-only storyindoc.text:documents.remove(doc)continueifThe Data Entrepreneursindoc.text:documents.remove(doc)if min readindoc.text:documents.remove(doc)print(len(documents))# prints: 61最后我们可以将精炼后的块存储在向量数据库中。indexVectorStoreIndex.from_documents(documents)设置 Retriever在我们的知识库就绪后我们可以使用 LlamaIndex 的*VectorIndexRetreiver()*创建一个检索器该检索器返回与用户查询最相似的 3 个块。# set number of docs to retreivetop_k3# configure retrieverretrieverVectorIndexRetriever(indexindex,similarity_top_ktop_k,)接下来我们定义一个查询引擎该引擎使用检索器和查询返回一组相关块。# assemble query enginequery_engineRetrieverQueryEngine(retrieverretriever,node_postprocessors[SimilarityPostprocessor(similarity_cutoff0.5)],)使用查询引擎现在在我们的知识库和检索系统设置完成后让我们使用它来返回与查询相关的块。在这里我们将传递与上一篇文章中询问 ShawGPTYouTube 评论响应者相同的技术问题。queryWhat is fat-tailedness?responsequery_engine.query(query)查询引擎返回一个包含文本、元数据和相关块索引的响应对象。下面的代码块返回了此信息的更易读版本。# reformat responsecontextContext:nforiinrange(top_k):contextcontextresponse.source_nodes[i].textnnprint(context)Context:Some of the controversy might be explained by the observation that log-normal distributions behave like Gaussianforlow sigmaandlike Power Law at high sigma[2].However,to avoid controversy,we can depart(fornow)fromwhether some given data fits a Power Lawornotandfocus instead on fat tails.Fat-tailedness-measuring the space between MediocristanandExtremistan Fat Tails are a more general idea than ParetoandPower Law distributions.One way we can think about itisthatfat-tailednessisthe degree to which rare events drive the aggregate statistics of a distribution.From this point of view,fat-tailedness lives on a spectrumfromnotfat-tailed(i.e.a Gaussian)to very fat-tailed(i.e.Pareto80–20).This maps directly to the idea of Mediocristan vs Extremistan discussed earlier.The image below visualizes different distributions across this conceptual landscape[2].print(mean kappa_1n str(np.mean(kappa_dict[filename])))print()Mean κ(1,100)valuesfrom1000runsforeach dataset.Image by author.These more stable results indicate Medium followers are the most fat-tailed,followed by LinkedIn ImpressionsandYouTube earnings.Note:One can compare these values to Table IIIinref[3]to better understand each κ value.Namely,these values are comparable to a Pareto distributionwithα between2and3.Although each heuristic told a slightly different story,allsigns point toward Medium followers gained being the most fat-tailed of the3datasets.Conclusion While binary labeling dataasfat-tailed(ornot)may be tempting,fat-tailedness lives on a spectrum.Here,we broke down4heuristicsforquantifying how fat-tailed data are.Pareto,Power Laws,andFat Tails What they dont teach youinstatistics towardsdatascience.com Although Pareto(andmore generally power law)distributions give us a salient example of fat tails,thisisa more general notion that lives on a spectrum rangingfromthin-tailed(i.e.a Gaussian)to very fat-tailed(i.e.Pareto80–20).The spectrum of Fat-tailedness.Image by author.This view of fat-tailedness provides uswitha more flexibleandprecise way of categorizing data than simply labeling itasa Power Law(ornot).However,this begs the question:how do we define fat-tailedness?4Ways to Quantify Fat Tails将 RAG 添加到 LLM我们首先从 Hugging Face hub 下载微调模型。# load fine-tuned model from hubfrompeftimportPeftModel,PeftConfigfromtransformersimportAutoModelForCausalLM,AutoTokenizer model_nameTheBloke/Mistral-7B-Instruct-v0.2-GPTQmodelAutoModelForCausalLM.from_pretrained(model_name,device_mapauto,trust_remote_codeFalse,revisionmain)configPeftConfig.from_pretrained(shawhin/shawgpt-ft)modelPeftModel.from_pretrained(model,shawhin/shawgpt-ft)# load tokenizertokenizerAutoTokenizer.from_pretrained(model_name,use_fastTrue)作为基线我们可以看到模型在没有文章上下文的情况下对技术问题的响应。为此我们使用 lambda 函数创建一个提示模板该模板接受一个观众评论并返回一个用于 LLM 的提示。有关此提示来源的更多详细信息请参阅本系列的上一篇文章。# prompt (no context)intstructions_stringfShawGPT, functioning as a virtual data science consultant on YouTube, communicates in clear, accessible language, escalating to technical depth upon request. It reacts to feedback aptly and ends responses with its signature –ShawGPT. ShawGPT will tailor the length of its responses to match the viewers comment, providing concise acknowledgments to brief expressions of gratitude or feedback, thus keeping the interaction natural and engaging. Please respond to the following comment. prompt_templatelambdacomment:f[INST]{intstructions_string}n{comment}n[/INST]commentWhat is fat-tailedness?promptprompt_template(comment)print(prompt)[INST]ShawGPT,functioningasa virtual data science consultant on YouTube,communicatesinclear,accessible language,escalating to technical depth upon request.It reacts to feedback aptlyandends responseswithits signature–ShawGPT.ShawGPT will tailor the length of its responses tomatchthe viewers comment,providing concise acknowledgments to brief expressions of gratitudeorfeedback,thus keeping the interaction naturalandengaging.Please respond to the following comment.Whatisfat-tailedness?[/INST]接下来我们可以使用下面的代码将这个提示传递给模型。model.eval()inputstokenizer(prompt,return_tensorspt)outputsmodel.generate(input_idsinputs[input_ids].to(cuda),max_new_tokens280)print(tokenizer.batch_decode(outputs)[0])这是模型的响应无上下文。Great question! Fat-tailednessisa statisticalpropertyof a distribution.In simple terms,it refers to the presence of extreme outliersorheavy tailsinthe distribution.For instance,consider the distribution of heightsina population.A normal distribution would have most people clustered around an average heightwitha few people deviating slightlyfromthe mean.However,ina fat-tailed distribution,you would observe a larger number of people being significantly tallerorshorter than the average.In finance,fat-tailednessisoften used to describe the presence of extreme market movesoroutliersinfinancial returns.Its an important conceptinrisk managementandfinancial modeling.I hope this explanation helps! Let me knowifyou haveanyquestions.–ShawGPT尽管响应的风格和格式都很棒但模型对厚尾性的解释与我视频视频和博客系列中的定义有所不同。让我们看看当我们包含适当的上下文时模型响应会发生什么。为此我们创建了一个另一个提示模板它也可以接受来自 RAG 系统的上下文。# prompt (with context)prompt_template_w_contextlambdacontext,comment:f[INST]ShawGPT, functioning as a virtual data science consultant on YouTube, communicates in clear, accessible language, escalating to technical depth upon request. It reacts to feedback aptly and ends responses with its signature –ShawGPT. ShawGPT will tailor the length of its responses to match the viewers comment, providing concise acknowledgments to brief expressions of gratitude or feedback, thus keeping the interaction natural and engaging.{context}Please respond to the following comment. Use the context above if it is helpful.{comment}[/INST] 接下来我们将查询引擎和视图评论中的上下文提示传递给模型。promptprompt_template_w_context(context,comment)inputstokenizer(prompt,return_tensorspt)outputsmodel.generate(input_idsinputs[input_ids].to(cuda),max_new_tokens280)print(tokenizer.batch_decode(outputs)[0])这是新的响应带有上下文。Great question! Fat-tailednessisapropertyof a distribution that describes how much the presence of extreme values(rare events)affects the overall statistics of the distribution.In the context of the video,the author discusses how MediocristanandExtremistan distributions differinterms of fat-tailedness.Mediocristan distributions have a relatively small impactfromextreme values,whileExtremistan distributions are heavily influenced by extreme values.The author also mentions that fat-tailednessisa more general concept than specific distributions like ParetoorPower Laws.Instead,it lives on a spectrum rangingfromthin-tailed(Gaussian)to very fat-tailed(Pareto80-20).I hope that helps clarify things a bit! Let me knowifyou haveanyquestions.–ShawGPT这比没有上下文的响应更好地捕捉了我对厚尾性的解释甚至指出了 Mediocristan 和 Extremistan 的利基概念。Google Colaboratory接下来是什么在这里我提供了一个面向初学者的 RAG 介绍并分享了如何使用 LlamaIndex 实现它的具体示例。RAG 使我们能够通过可更新和特定领域的知识来改进 LLM 系统。尽管最近的人工智能炒作主要集中在构建 AI 助手上但一种强大但不太受欢迎的创新来自文本嵌入即我们过去用来检索的东西。在系列文章的下一篇文章中我将更详细地探讨文本嵌入包括它们如何用于语义搜索和分类任务。更多关于 LLMs 大型语言模型 (LLMs)资源连接: 我的网站 | 预约通话社交: YouTube | LinkedIn | Instagram支持: 买我一杯咖啡 ☕️免费获取我写的每一篇新故事[1] RAG FT (经验)[2] LlamaIndex 网络研讨会构建生产级 LLM 应用第一部分与 Anyscale 共同主持[3] LlamaIndex 文档[4] LlamaIndex 网络研讨会使 RAG 生产就绪