随着人工智能技术的飞速发展,大型语言模型(LLMs)如GPT-4等已在众多领域展现出卓越的能力。然而,这些大型模型往往伴随着高昂的计算成本和资源消耗,限制了其在某些场景下的广泛应用。近年来,利用小型语言模型(small LLMs)来实现检索增强生成(Retrieval-Augmented Generation, RAG)(RAG(Retrieval Augmented Generation)及衍生框架:CRAG、Self-RAG与HyDe的深入探讨)成为了一个备受关注的研究方向。今天我们一起来看一下通过小模型来做RAG。
高维噪声
直接嵌入文档中的原始文本而不进行摘要,往往会导致嵌入结果包含大量无关信息。例如,原始文本可能包含格式化的痕迹、样板语言等,这些内容对于理解核心内容并没有帮助,反而增加了嵌入向量的维度,形成了噪声。
比如在一篇产品文档中,可能存在大量的版权声明、页码标注等信息,这些在对文档主要内容进行理解和检索时是干扰因素。
关键概念稀释
重要的概念可能被淹没在大量的无关文本中。这使得嵌入向量不能很好地代表关键信息,降低了检索系统对核心内容的捕捉能力。
例如在一篇关于医疗技术的文档中,关键的治疗方法可能被冗长的疾病背景介绍和历史发展描述所掩盖。
匹配用户查询效果不佳
当嵌入向量不能准确代表文本的关键概念时,检索系统可能无法有效地匹配用户查询。嵌入向量可能与查询嵌入向量不一致,导致相关文档检索效果差。
例如用户查询关于 “某种疾病的最新治疗方法”,但由于原始文本嵌入的问题,检索系统可能无法准确找到包含该治疗方法关键信息的文档。
提供正确上下文困难
即使检索到了文档,由于嵌入中的噪声,它可能无法提供用户所寻求的精确信息。
比如检索到的文档可能包含大量关于疾病的一般性介绍(Retrieval-Augmented Generation (RAG 检索增强生成) 创新切块策略),而用户需要的关于特定治疗方法在特定情况下的应用细节却无法准确获取。
资源高效:小型语言模型(Llama3.2 1B与3B:轻盈而强大的AI新势力)相较于大型模型,具有更低的计算复杂度和资源消耗。这使得它们能够在资源有限的场景下,如企业级应用或云端部署中,实现更为高效的运行。
易于部署:小型模型的体积小、重量轻,使得它们更容易在各类硬件平台上进行部署和集成。
适用性强:对于某些特定任务,如文本摘要、关键词提取等,小型语言模型同样能够展现出出色的性能。这些任务在RAG系统中至关重要,因为它们直接关系到信息的检索效率和准确性
文本摘要与索引:利用小型语言模型对大型文档进行摘要和索引,可以显著提高RAG系统的检索效率。通过对文档进行摘要处理,可以去除冗余信息,保留核心要点,从而生成更为紧凑和高效的索引结构。
生成嵌入向量:小型语言模型还可以用于生成文本的嵌入向量。这些向量能够捕捉到文本的主要内容和特征,从而支持更准确的文本检索和匹配。
错误自校正:在RAG系统的生成过程中,小型语言模型还可以用于自我校正输出中的错误。通过不断迭代和优化生成过程,可以提高输出的准确性和可靠性。
(一)离线数据处理
1、环境配置,导入必要的包
importpandasaspdimportfitz#PyMuPDFfromtransformersimportAutoModelForCausalLM,AutoTokenizerimporttorchimportlancedbfromsentence_transformersimportSentenceTransformerimportjsonimportpyarrowaspaimportnumpyasnpimportre
2、定义辅助函数
defcreate_prompt(question):"""CreateapromptasperLLAMA3.2format."""system_message="YouareahelpfulassistantforsummarizingtextandresultinJSONformat"prompt_template=f'''<|begin_of_text|><|start_header_id|>system<|end_header_id|>{system_message}<|eot_id|><|start_header_id|>user<|end_header_id|>{question}<|eot_id|><|start_header_id|>assistant1231231222<|end_header_id|>'''returnprompt_template2)处理提示函数
定义函数 process_prompt,它使用模型和分词器处理提示。通过设置温度为 0.1,使模型更具确定性,减少创造性(即减少幻觉)。该函数对输入的提示进行编码,生成响应,并提取出助手的回复。
defprocess_prompt(prompt,model,tokenizer,device,max_length=500):"""rocessesaprompt,generatesaresponse,andextractstheassistant'sreply."""prompt_encoded=tokenizer(prompt,truncation=True,padding=False,return_tensors="pt")model.eval()output=model.generate(input_ids=prompt_encoded.input_ids.to(device),max_new_tokens=max_length,attention_mask=prompt_encoded.attention_mask.to(device),temperature=0.1#Moredeterministic)answer=tokenizer.decode(output[0],skip_special_tokens=True)parts=answer.split("assistant1231231222",1)iflen(parts)>1:words_after_assistant=parts[1].strip()returnwords_after_assistantelse:print("Theassistant'sresponsewasnotfound.")return"NONE"
3、加载模型
model_name_long="meta-llama/Llama-3.2-1B-Instruct"tokenizer=AutoTokenizer.from_pretrained(model_name_long)device=torch.device("cuda"iftorch.cuda.is_available()else"cpu")log.info(f"Loadingthemodel{model_name_long}")bf16=Falsefp16=Trueiftorch.cuda.is_available():major,_=torch.cuda.get_device_capability()ifmajor>=8:log.info("YourGPUsupportsbfloat16:acceleratetrainingwithbf16=True")bf16=Truefp16=False#Loadthemodeldevice_map={"":0}#LoadonGPU0torch_dtype=torch.bfloat16ifbf16elsetorch.float16model=AutoModelForCausalLM.from_pretrained(model_name_long,torch_dtype=torch_dtype,device_map=device_map,)log.info(f"Modelloadedwithtorch_dtype={torch_dtype}")4、数据解析
file_path='./data/troubleshooting.pdf'dict_pages={}#OpenthePDFfilewithfitz.open(file_path)aspdf_document:forpage_numberinrange(pdf_document.page_count):page=pdf_document.load_page(page_number)page_text=page.get_text()dict_pages[page_number]=page_textprint(f"ProcessedPDFpage{page_number+1}")设置向量数据库和embedding模型
#InitializetheSentenceTransformermodelsentence_model=SentenceTransformer('all-MiniLM-L6-v2')#ConnecttoLanceDBdb=lancedb.connect('./data/my_lancedb')#DefinetheschemausingPyArrowschema=pa.schema([pa.field("page_number",pa.int64()),pa.field("original_content",pa.string()),pa.field("summary",pa.string()),pa.field("keywords",pa.string()),pa.field("vectorS",pa.list_(pa.float32(),384)),#Embeddingsizeof384pa.field("vectorK",pa.list_(pa.float32(),384)),])#Createorconnecttoatabletable=db.create_table('summaries',schema=schema,mode='overwrite')循环处理每一页
对于 PDF 文档中的每一页文本,首先创建一个包含要求生成摘要和关键词的问题的提示。然后使用模型和辅助函数处理提示,获取摘要和关键词的 JSON 格式输出。
错误处理和 JSON 解析
如果最初获取的输出无法正确解析为 JSON 格式,则重新提示模型纠正错误,并再次尝试解析。
生成嵌入向量并存储数据
对于正确解析的摘要和关键词,使用 SentenceTransformer 模型生成相应的嵌入向量,并将页面编号、原始内容、摘要、关键词以及嵌入向量等数据存储到 LanceDB 数据库表中。
#LoopthrougheachpageinthePDFforpage_number,textindict_pages.items():question=f"""Forthegivenpassage,providealongsummaryaboutit,incorporatingallthemainkeywordsinthepassage.FormatshouldbeinJSONformatlikebelow:{{"summary":<textsummary>,"keywords":<acomma-separatedlistofmainkeywordsandacronymsthatappearinthepassage>,}}MakesurethatJSONfieldshavedoublequotesandusethecorrectclosingdelimiters.Passage:{text}"""prompt=create_prompt(question)response=process_prompt(prompt,model,tokenizer,device)#ErrorhandlingforJSONdecodingtry:summary_json=json.loads(response)exceptjson.decoder.JSONDecodeErrorase:exception_msg=str(e)question=f"""CorrectthefollowingJSON{response}whichhas{exception_msg}toproperJSONformat.OutputonlyJSON."""log.warning(f"{exception_msg}for{response}")prompt=create_prompt(question)response=process_prompt(prompt,model,tokenizer,device)log.warning(f"Corrected'{response}'")try:summary_json=json.loads(response)exceptExceptionase:log.error(f"FailedtoparseJSON:'{e}'for'{response}'")continuekeywords=','.join(summary_json['keywords'])#GenerateembeddingsvectorS=sentence_model.encode(summary_json['summary'])vectorK=sentence_model.encode(keywords)#StorethedatainLanceDBtable.add([{"page_number":int(page_number),"original_content":text,"summary":summary_json['summary'],"keywords":keywords,"vectorS":vectorS,"vectorK":vectorK}])print(f"Dataforpage{page_number}storedsuccessfully.")处理格式错误
当 LLM 生成的摘要和关键词输出不符合预期格式(如 JSON 格式错误)时,可以利用 LLM 本身来纠正这些输出。通过重新提示模型修复错误,确保数据格式正确,以便进行下游处理。
通过 LLM Agents 扩展自纠正
LLM Agents 可以进一步自动化这个过程。它可以检测错误,自主决定如何纠正错误,无需明确的指令。LLM Agents 可以解析输出、验证格式,在遇到错误时重新提示 LLM,并记录错误和纠正信息,用于未来参考和模型微调。
#UsetheSmallLLAMA3.21Bmodeltocreatesummaryforpage_number,textindict_pages.items():question=f"""Forthegivenpassage,providealongsummaryaboutit,incorporatingallthemainkeywordsinthepassage.FormatshouldbeinJSONformatlikebelow:{{"summary":<textsummary>example"SomeSummarytext","keywords":<acommaseparatedlistofmainkeywordsandacronymsthatappearinthepassage>example["keyword1","keyword2"],}}MakesurethatJSONfieldshavedoublequotes,e.g.,insteadof'summary'use"summary",andusetheclosingandendingdelimiters.Passage:{text}"""prompt=create_prompt(question)response=process_prompt(prompt,model,tokenizer,device)try:summary_json=json.loads(response)exceptjson.decoder.JSONDecodeErrorase:exception_msg=str(e)#UsetheLLMtocorrectitsownoutputquestion=f"""CorrectthefollowingJSON{response}whichhas{exception_msg}toproperJSONformat.OutputonlythecorrectedJSON.FormatshouldbeinJSONformatlikebelow:{{"summary":<textsummary>example"SomeSummarytext","keywords":<acommaseparatedlistofkeywordsandacronymsthatappearinthepassage>example["keyword1","keyword2"],}}"""log.warning(f"{exception_msg}for{response}")prompt=create_prompt(question)response=process_prompt(prompt,model,tokenizer,device)log.warning(f"Corrected'{response}'")#TryparsingthecorrectedJSONtry:summary_json=json.loads(response)exceptjson.decoder.JSONDecodeErrorase:log.error(f"FailedtoparsecorrectedJSON:'{e}'for'{response}'")continue用户问题向量
将用户的问题使用与索引时相同的 SentenceTransformer 模型转换为嵌入向量。
相似性搜索
使用查询嵌入向量在 LanceDB 向量数据库中搜索最相似的摘要,并返回前 3 个结果(可以根据实际情况调整)。这些结果包括页面编号和摘要内容。
使用 LLM 排名
将检索到的摘要列表传递给语言模型,提示它根据与用户问题的相关性对摘要进行排名,并选择最相关的一个。这种使用 LLM 进行排名的方法比单纯使用 K - Nearest Neighbour 或 Cosine 距离等算法更能考虑到上下文嵌入(向量)匹配和语义相关性。
获取原始内容
通过解析出选定摘要的页面编号,从 LanceDB 中获取与之相关的原始内容。
生成答案
使用获取的原始内容作为上下文,提示语言模型生成对用户问题的详细答案。通过设置较低的温度(如 0.01),减少模型产生幻觉的可能性,使答案更加准确可靠。
通过使用小型 LLM 如 LLAMA 3.2 1B Instruct(Llama3.2 1B与3B:轻盈而强大的AI新势力),可以高效地对大型文档进行摘要和提取关键词。这些摘要和关键词可以被嵌入并存储在像 LanceDB 这样的数据库中,从而为 RAG 系统提供高效的检索能力(Astute RAG(Retrieval-Augmented Generation):LLM信息检索与利用的新思路)。在整个工作流程中,小型 LLM 不仅在生成阶段发挥作用,还在检索增强过程中起到了关键作用,包括对检索到的摘要进行排名等。这种方法在降低计算成本的同时,能够为用户提供较为准确和相关的答案,提高了 RAG 系统的实用性和经济性。
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |