#RAG##AIGC#检索增强生成 (RAG) 基本介绍和入门实操示例

本文包括RAG基本介绍和入门实操示例

RAG 基本介绍

通用语言模型可以进行微调以实现一些常见任务,例如情感分析和命名实体识别。这些任务通常不需要额外的背景知识。
对于更复杂和知识密集型的任务,可以构建基于语言模型的系统来访问外部知识源来完成任务。这使得事实更加一致,提高了生成响应的可靠性,并有助于减轻“幻觉”问题。
Meta AI 研究人员推出了一种称为检索增强生成(RAG)的方法来解决此类知识密集型任务。 RAG 将信息检索组件与文本生成器模型相结合。 RAG 可以进行微调,并且可以有效地修改其内部知识,而无需重新训练整个模型。
RAG 接受输入并检索一组给定来源(例如维基百科)的相关/支持文档。这些文档作为上下文与原始输入提示连接起来,并输入到生成最终输出的文本生成器。这使得 RAG 能够适应事实可能随时间变化的情况。这非常有用,因为 LLMs 的参数知识是静态的。 RAG 允许语言模型绕过再训练,从而能够访问最新信息,从而通过基于检索的生成来生成可靠的输出。
Lewis 等人 (2021) 提出了一种 RAG 的通用微调方法。预训练的 seq2seq 模型用作参数存储器,维基百科的密集向量索引用作非参数存储器(使用神经预训练检索器访问)。下面概述了该方法的工作原理:
请添加图片描述
RAG 在自然问题等多项基准测试中表现强劲, WebQuestions , 网络问题,和 CuratedTrec。在针对 MS-MARCO 和 Jeopardy 问题进行测试时,RAG 生成的答案更加真实、具体和多样化。 RAG 还改进了 FEVER 事实验证的结果。
这表明 RAG 作为增强知识密集型任务中语言模型输出的可行选择的潜力。
最近,这些基于检索器的方法变得越来越流行,并与 ChatGPT 等流行的 LLMs 相结合,以提高功能和事实一致性。

RAG 用例:生成友好的 ML 论文标题

下面,我们准备了一个笔记本教程,展示如何使用开源 LLMs 构建 RAG 系统来生成简短的机器学习论文标题:

RAG入门

虽然大型语言模型(LLM)显示出强大的功能来支持高级用例,但它们也存在事实不一致和幻觉等问题。检索增强生成(RAG)是丰富LLM能力和提高其可靠性的一种强大方法。
RAG涉及通过用有助于完成任务的相关信息丰富提示上下文,将LLM与外部知识相结合。

本教程展示了如何利用矢量存储和开源LLM开始使用RAG。
为了展示RAG的强大功能,本用例将涵盖构建一个RAG系统,该系统从原始ML论文标题中建议简短且易于阅读的ML论文标题。

对于普通受众来说,纸质资料可能过于技术化,因此使用RAG在之前创建的短标题的基础上生成小标题可以使研究论文标题更容易访问,并用于科学传播,如以时事通讯或博客的形式。

在开始之前,让我们先安装我们将要使用的库:

%%capture
!pip install chromadb tqdm fireworks-ai python-dotenv pandas
!pip install sentence-transformers

在继续之前,您需要获得Fireworks API密钥才能使用Mistral 7B模型。

查看此快速指南以获取您的Fireworks API密钥:: https://readme.fireworks.ai/docs

import fireworks.client
import os
import dotenv
import chromadb
import json
from tqdm.auto import tqdm
import pandas as pd
import random

# 可以使用 Colab secrets 设置环境
dotenv.load_dotenv()

fireworks.client.api_key = os.getenv("FIREWORKS_API_KEY")

开始

让我们定义一个函数,从Fireworks推理平台获取完成。

def get_completion(prompt, model=None, max_tokens=50):

    fw_model_dir = "accounts/fireworks/models/"

    if model is None:
        model = fw_model_dir + "llama-v2-7b"
    else:
        model = fw_model_dir + model

    completion = fireworks.client.Completion.create(
        model=model,
        prompt=prompt,
        max_tokens=max_tokens,
        temperature=0
    )

    return completion.choices[0].text

让我们首先尝试一个简单提示的函数:

get_completion("Hello, my name is")
' Katie and I am a 20 year old student at the University of Leeds. I am currently studying a BA in English Literature and Creative Writing. I have been working as a tutor for over 3 years now and I'

现在让我们使用Mistral-7B-指令进行测试:

mistral_llm = "mistral-7b-instruct-4k"

get_completion("Hello, my name is", model=mistral_llm)
' [Your Name]. I am a [Your Profession/Occupation]. I am writing to [Purpose of Writing].\n\nI am writing to [Purpose of Writing] because [Reason for Writing]. I believe that ['

Mistral 7B指令模型需要使用特殊的指令标记 [INST] <instruction> [/INST] 进行指令,以获得正确的行为。您可以在此处找到有关如何提示Mistral 7B指令的更多说明:: https://docs.mistral.ai/llm/mistral-instruct-v0.1

mistral_llm = "mistral-7b-instruct-4k"

get_completion("Tell me 2 jokes", model=mistral_llm)
".\n1. Why don't scientists trust atoms? Because they make up everything!\n2. Did you hear about the mathematician who’s afraid of negative numbers? He will stop at nothing to avoid them."
mistral_llm = "mistral-7b-instruct-4k"

get_completion("[INST]Tell me 2 jokes[/INST]", model=mistral_llm)
" Sure, here are two jokes for you:\n\n1. Why don't scientists trust atoms? Because they make up everything!\n2. Why did the tomato turn red? Because it saw the salad dressing!"

现在,让我们尝试使用一个更复杂的提示,其中包含说明:

prompt = """[INST]
Given the following wedding guest data, write a very short 3-sentences thank you letter:

{
  "name": "John Doe",
  "relationship": "Bride's cousin",
  "hometown": "New York, NY",
  "fun_fact": "Climbed Mount Everest in 2020",
  "attending_with": "Sophia Smith",
  "bride_groom_name": "Tom and Mary"
}

Use only the data provided in the JSON object above.

The senders of the letter is the bride and groom, Tom and Mary.
[/INST]"""

get_completion(prompt, model=mistral_llm, max_tokens=150)
" Dear John Doe,\n\nWe, Tom and Mary, would like to extend our heartfelt gratitude for your attendance at our wedding. It was a pleasure to have you there, and we truly appreciate the effort you made to be a part of our special day.\n\nWe were thrilled to learn about your fun fact - climbing Mount Everest is an incredible accomplishment! We hope you had a safe and memorable journey.\n\nThank you again for joining us on this special occasion. We hope to stay in touch and catch up on all the amazing things you've been up to.\n\nWith love,\n\nTom and Mary"

RAG用例:生成短文标题

对于RAG用例,我们将使用a dataset 其中包含每周热门ML论文的列表。

用户将提供原始论文标题。然后,我们将接受该输入,然后使用数据集生成简短而吸引人的论文标题的上下文,这将有助于为原始输入标题生成吸引人的标题。

步骤1:加载数据集

让我们首先加载我们将使用的数据集:

# load dataset from data/ folder to pandas dataframe
# dataset contains column names

ml_papers = pd.read_csv("../data/ml-potw-10232023.csv", header=0)

# remove rows with empty titles or descriptions
ml_papers = ml_papers.dropna(subset=["Title", "Description"])
ml_papers.head()
TitleDescriptionPaperURLTweetURLAbstract
0Llemmaan LLM for mathematics which is based on conti...https://arxiv.org/abs/2310.10631https://x.com/zhangir_azerbay/status/171409802...We present Llemma, a large language model for ...
1LLMs for Software Engineeringa comprehensive survey of LLMs for software en...https://arxiv.org/abs/2310.03533https://x.com/omarsar0/status/1713940983199506...This paper provides a survey of the emerging a...
2Self-RAGpresents a new retrieval-augmented framework t...https://arxiv.org/abs/2310.11511https://x.com/AkariAsai/status/171511027707796...Despite their remarkable capabilities, large l...
3Retrieval-Augmentation for Long-form Question ...explores retrieval-augmented language models o...https://arxiv.org/abs/2310.12150https://x.com/omarsar0/status/1714986431859282...We present a study of retrieval-augmented lang...
4GenBenchpresents a framework for characterizing and un...https://www.nature.com/articles/s42256-023-007...https://x.com/AIatMeta/status/1715041427283902...NaN
# convert dataframe to list of dicts with Title and Description columns only

ml_papers_dict = ml_papers.to_dict(orient="records")
ml_papers_dict[0]
{'Title': 'Llemma',
 'Description': 'an LLM for mathematics which is based on continued pretraining from Code Llama on the Proof-Pile-2 dataset; the dataset involves scientific paper, web data containing mathematics, and mathematical code; Llemma outperforms open base models and the unreleased Minerva on the MATH benchmark; the model is released, including dataset and code to replicate experiments.',
 'PaperURL': 'https://arxiv.org/abs/2310.10631',
 'TweetURL': 'https://x.com/zhangir_azerbay/status/1714098025956864031?s=20',
 'Abstract': 'We present Llemma, a large language model for mathematics. We continue pretraining Code Llama on the Proof-Pile-2, a mixture of scientific papers, web data containing mathematics, and mathematical code, yielding Llemma. On the MATH benchmark Llemma outperforms all known open base models, as well as the unreleased Minerva model suite on an equi-parameter basis. Moreover, Llemma is capable of tool use and formal theorem proving without any further finetuning. We openly release all artifacts, including 7 billion and 34 billion parameter models, the Proof-Pile-2, and code to replicate our experiments.'}

我们将使用PenceTransformer生成嵌入,并将其存储到Chroma文档存储中。

from chromadb import Documents, EmbeddingFunction, Embeddings
from sentence_transformers import SentenceTransformer
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')

class MyEmbeddingFunction(EmbeddingFunction):
    def __call__(self, input: Documents) -> Embeddings:
        batch_embeddings = embedding_model.encode(input)
        return batch_embeddings.tolist()

embed_fn = MyEmbeddingFunction()

# Initialize the chromadb directory, and client.
client = chromadb.PersistentClient(path="./chromadb")

# create collection
collection = client.get_or_create_collection(
    name=f"ml-papers-nov-2023"
)
.gitattributes: 100%|██████████| 1.18k/1.18k [00:00<00:00, 194kB/s]
1_Pooling/config.json: 100%|██████████| 190/190 [00:00<00:00, 204kB/s]
README.md: 100%|██████████| 10.6k/10.6k [00:00<00:00, 7.64MB/s]
config.json: 100%|██████████| 612/612 [00:00<00:00, 679kB/s]
config_sentence_transformers.json: 100%|██████████| 116/116 [00:00<00:00, 94.0kB/s]
data_config.json: 100%|██████████| 39.3k/39.3k [00:00<00:00, 7.80MB/s]
pytorch_model.bin: 100%|██████████| 90.9M/90.9M [00:03<00:00, 24.3MB/s]
sentence_bert_config.json: 100%|██████████| 53.0/53.0 [00:00<00:00, 55.4kB/s]
special_tokens_map.json: 100%|██████████| 112/112 [00:00<00:00, 161kB/s]
tokenizer.json: 100%|██████████| 466k/466k [00:00<00:00, 6.15MB/s]
tokenizer_config.json: 100%|██████████| 350/350 [00:00<00:00, 286kB/s]
train_script.py: 100%|██████████| 13.2k/13.2k [00:00<00:00, 12.2MB/s]
vocab.txt: 100%|██████████| 232k/232k [00:00<00:00, 9.15MB/s]
modules.json: 100%|██████████| 349/349 [00:00<00:00, 500kB/s]

我们现在将为批生成嵌入:

# Generate embeddings, and index titles in batches
batch_size = 50

# loop through batches and generated + store embeddings
for i in tqdm(range(0, len(ml_papers_dict), batch_size)):

    i_end = min(i + batch_size, len(ml_papers_dict))
    batch = ml_papers_dict[i : i + batch_size]

    # Replace title with "No Title" if empty string
    batch_titles = [str(paper["Title"]) if str(paper["Title"]) != "" else "No Title" for paper in batch]
    batch_ids = [str(sum(ord(c) + random.randint(1, 10000) for c in paper["Title"])) for paper in batch]
    batch_metadata = [dict(url=paper["PaperURL"],
                           abstract=paper['Abstract'])
                           for paper in batch]

    # generate embeddings
    batch_embeddings = embedding_model.encode(batch_titles)

    # upsert to chromadb
    collection.upsert(
        ids=batch_ids,
        metadatas=batch_metadata,
        documents=batch_titles,
        embeddings=batch_embeddings.tolist(),
    )
100%|██████████| 9/9 [00:01<00:00,  7.62it/s]

现在我们可以测试寻回器:

collection = client.get_or_create_collection(
    name=f"ml-papers-nov-2023",
    embedding_function=embed_fn
)

retriever_results = collection.query(
    query_texts=["Software Engineering"],
    n_results=2,
)

print(retriever_results["documents"])
[['LLMs for Software Engineering', 'Communicative Agents for Software Development']]

现在,让我们总结一下最后的提示:

# user query
user_query = "S3Eval: A Synthetic, Scalable, Systematic Evaluation Suite for Large Language Models"

# query for user query
results = collection.query(
    query_texts=[user_query],
    n_results=10,
)

# concatenate titles into a single string
short_titles = '\n'.join(results['documents'][0])

prompt_template = f'''[INST]

Your main task is to generate 5 SUGGESTED_TITLES based for the PAPER_TITLE

You should mimic a similar style and length as SHORT_TITLES but PLEASE DO NOT include titles from SHORT_TITLES in the SUGGESTED_TITLES, only generate versions of the PAPER_TILE.

PAPER_TITLE: {user_query}

SHORT_TITLES: {short_titles}

SUGGESTED_TITLES:

[/INST]
'''

responses = get_completion(prompt_template, model=mistral_llm, max_tokens=2000)
suggested_titles = ''.join([str(r) for r in responses])

# Print the suggestions.
print("Model Suggestions:")
print(suggested_titles)
print("\n\n\nPrompt Template:")
print(prompt_template)
Model Suggestions:

1. S3Eval: A Comprehensive Evaluation Suite for Large Language Models
2. Synthetic and Scalable Evaluation for Large Language Models
3. Systematic Evaluation of Large Language Models with S3Eval
4. S3Eval: A Synthetic and Scalable Approach to Language Model Evaluation
5. S3Eval: A Synthetic and Scalable Evaluation Suite for Large Language Models



Prompt Template:
[INST]

Your main task is to generate 5 SUGGESTED_TITLES based for the PAPER_TITLE

You should mimic a similar style and length as SHORT_TITLES but PLEASE DO NOT include titles from SHORT_TITLES in the SUGGESTED_TITLES, only generate versions of the PAPER_TILE.

PAPER_TITLE: S3Eval: A Synthetic, Scalable, Systematic Evaluation Suite for Large Language Models

SHORT_TITLES: Pythia: A Suite for Analyzing Large Language Models Across Training and Scaling
ChemCrow: Augmenting large-language models with chemistry tools
A Survey of Large Language Models
LLaMA: Open and Efficient Foundation Language Models
SparseGPT: Massive Language Models Can Be Accurately Pruned In One-Shot
REPLUG: Retrieval-Augmented Black-Box Language Models
LLaMA-Adapter: Efficient Fine-tuning of Language Models with Zero-init Attention
Auditing large language models: a three-layered approach
Fine-Tuning Language Models with Just Forward Passes
DERA: Enhancing Large Language Model Completions with Dialog-Enabled Resolving Agents

SUGGESTED_TITLES:

[/INST]

正如您所看到的,LLM生成的简短标题在某种程度上是可以的。这个用例仍然需要做更多的工作,并且可能也会从微调中受益。为了本教程的目的,我们使用Firework的开源模型提供了一个简单的RAG应用程序

在这里尝试其他开源模型: https://app.fireworks.ai/models

R点击此处了解有关Fireworks API的更多信息: https://readme.fireworks.ai/reference/createchatcompletion

参考文献

· https://arxiv.org/abs/2312.10997 Retrieval-Augmented Generation for Large Language Models: A Survey
大型语言模型的检索增强生成:一项调查
· https://ai.meta.com/blog/retrieval-augmented-generation-streamlining-the-creation-of-intelligent-natural-language-processing-models/ Retrieval Augmented Generation: Streamlining the creation of intelligent natural language processing models
检索增强生成:简化智能自然语言处理模型的创建
· https://arxiv.org/abs/2302.07842 Augmented Language Models: a Survey
增强语言模型:调查

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/324618.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【C语言】指针知识点笔记(2)

目录 一、野指针 二、assert断言 三、指针的使用和传址调用 四、数组名的理解 五、使用指针访问数组 一、野指针 二、assert断言 三、指针的使用和传址调用 四、数组名的理解 五、使用指针访问数组

高通平台开发系列讲解(USB篇)DWC3控制USB速率

文章目录 一、设备树二、相关结构体三、最大速率设置四、当前速率设置沉淀、分享、成长,让自己和他人都能有所收获!😄 📢本文主要介绍高通平台USB DWC3控制USB速率。 一、设备树 目录:msm-4.14/arch/arm64/boot/dts/qcom/sdxprairie-usb.dtsi dwc3@a600000 {compatibl…

pandas之重复数据的查看、删除和提取(后附数据网盘链接)

数据预览&#xff1a; 一、 查看value_counts() 这一函数能够查看每一数据出现了几次&#xff0c;但是用data.value_counts()这一方法时&#xff0c;只有一行数据全都一样才算做重复行&#xff0c;如下图中的郭靖分数不一样的话它没有计入是重复行&#xff0c;要想以名字作为重…

unity面试题

一&#xff1a;什么是协同程序&#xff1f; 在主线程运行的同时开启另一段逻辑处理&#xff0c;来协助当前程序的执行&#xff0c;协程很像多线程&#xff0c;但是不是多线程&#xff0c;Unity的协程实在每帧结束之后去检测yield的条件是否满足。 二&#xff1a;Unity3d中的碰…

身体互联网 (IoB)

现在&#xff0c;我们的互联网网关就是我们手中的一个小设备。 普渡大学副教授施里亚斯森表示。 我们不断地看着这个盒子&#xff0c;我们低着头走路&#xff0c;我们把大部分时间都花在它上面。如果我们不想让这种未来继续下去&#xff0c;我们就需要开发新技术。相反&#x…

使用scipy处理图片——任意比例缩放

大纲 缩小放大代码地址 在《使用numpy处理图片——缩放图片》一文中&#xff0c;我们每2个取1个像素来达到图像缩小的效果。这就要求缩小的比例只能是整数倍&#xff0c;而不能支持缩小到0.3倍或者放大到1.5倍这样的效果。 为了支持任意倍数的缩放功能&#xff0c;我们需要使用…

集群服务器GPU深度模型训练笔记(PBS作用调度系统)

相关手册与软件准备 官方使用手册 用户手册&#xff1a;https://hpc.sustech.edu.cn/ref/cluster_User_Manual.pdf 培训视频&#xff1a;https://hpc.sustech.edu.cn/ref/meeting_20230810.mp4 启明2.0使用手册&#xff1a;https://hpc.sustech.edu.cn/ref/qiming_User_Manua…

基于vue+Spring Boot家政服务人员预约系统iph9d

通过对家政服务管理内容的学习研究&#xff0c;进而设计并实现一个家政服务系统。系统能实现的主要功能应包括即时通讯、通讯回复、预约订单、接单信息、服务费用管、服务评价的一些操作。还有可以正确的为用户服务&#xff0c;准确显示当前信息[5]。 开发软件有很多种可以用&…

【JVM】性能调优

一、前言 性能调优&#xff0c;顾名思义&#xff0c;就是对系统或软件的性能进行优化&#xff0c;以提高其运行效率和响应速度。在计算机科学中&#xff0c;性能调优通常涉及到硬件、操作系统、数据库、网络等多个方面。对于Java开发者来说&#xff0c;JVM&#xff08;Java虚拟…

Docker 容器之间的互相通信

Docker容器之间的互相通信 步骤一&#xff1a;创建自定义网络 首先&#xff0c;我们需要创建一个自定义网络&#xff0c;以便容器可以连接到这个网络上&#xff0c;从而实现互相通信。在命令行中执行以下命令&#xff1a; # 创建 docker network create ddz # 查看 docker n…

O2066PM无线WIFI6E网卡Windows环境吞吐测试

从2023年开始&#xff0c;除手机外的无线终端设备也逐步向WIFI6/6E进行升级更新&#xff0c;基于802.11ax技术的设备能够进一步满足用户体验新一代Wi-Fi标准时获得优质的性能和覆盖范围。 用户对于WIFI模块&#xff0c;通常会关注WIFI模块的吞吐量&#xff0c;拿到样品之后&am…

如何在iPhone或iPad中截取长页面,这里有详细步骤

iOS有太多隐藏的功能&#xff0c;记住它们可能是一个挑战&#xff0c;但知道如何在iPhone或iPad上截屏整个页面是我从未忘记的。 你若是一名作家&#xff0c;你经常会发现自己需要截屏网站和文章中的大块文本&#xff0c;以便发送给某人或稍后阅读。虽然现在的手机有着令人羡慕…

python统计分析——生成正态分布随机数

参考资料&#xff1a;用python动手学统计学&#xff0c;帮助文档 方法1&#xff1a;scipy.stats.norm.rvs() from scipy import stats stats.norm.rvs(loc4,scale0.8,size10) 参数介绍如下&#xff1a; loc&#xff1a;表示正态分布的均值&#xff0c;默认为0 scale&#…

Visual Studio Code常用设置

此处用于记录下本人所使用 VScode 的使用习惯。其中主要包括&#xff1a;界面&#xff0c;主题&#xff0c;光标&#xff0c;文件保存等选项。 VSCode 用户区设置 相关介绍命令行方式进行配置可视化组件方式进行配置 更新 相关介绍 基本原理&#xff1a; Visual Studio Code 会…

sizeof与strlen的使用及其区别

目录 1. sizeof 1.1sizeof简介 1.2 sizeof的使用 1.3 sizeof的使用注意事项 1.4 sizeof用于数组 2.strlen&#xff08;&#xff09;函数 3.区别 示例1 示例2 示例3 4.总结 1. sizeof 1.1sizeof简介 sizeof是一个编译时运算符&#xff0c;可用于任何变量名、类型名…

Realm Management Extension领域管理扩展之系统架构

RME不仅仅是一组处理器功能,为了充分利用RME引入的功能,系统的其余部分需要提供支持。 下图显示了一个示例系统以及引入RME后受到影响的组件: 主存储器保护 RME启用的系统包括内存加密和可能的完整性。基线加密要求支持对外部内存进行加密,使用每个PA空间的单独加密密钥或…

1131. 拯救大兵瑞恩(dp思想运用,set)

1131. 拯救大兵瑞恩 - AcWing题库 1944 年&#xff0c;特种兵麦克接到国防部的命令&#xff0c;要求立即赶赴太平洋上的一个孤岛&#xff0c;营救被敌军俘虏的大兵瑞恩。 瑞恩被关押在一个迷宫里&#xff0c;迷宫地形复杂&#xff0c;但幸好麦克得到了迷宫的地形图。 迷宫的…

文心一言 vs. ChatGPT:哪个更胜一筹?

文心一言 vs. ChatGPT&#xff1a;从简洁美到深度思考的文本生成之旅 近年来&#xff0c;文本生成工具的崛起使得人们在表达和沟通方面拥有了更多的选择。在这个领域中&#xff0c;文心一言和ChatGPT作为两个备受瞩目的工具&#xff0c;各自以独特的优势展现在用户面前。本文将…

Maven普通工程和web工程创建

文章目录 创建项目前设置maven工程前设置工作创建项目前--》设置utf-8配置maven参数Maven普通工程和web工程创建Maven简单工程第一步&#xff1a;File–New–Project 第二步&#xff1a;选择maven然后下一步&#xff1a;填写后询选择finish初始化maven工程目录简介maven简单工程…

单列的堆叠柱状图

目的 MSingleColumnStackBarChart类被设计用于创建只有单列的堆叠柱状图&#xff0c;用于血糖数据的统计。以下是封装这个类的目的的详细描述&#xff1a; 抽象复杂性&#xff1a; 通过创建MSingleColumnStackBarChart类&#xff0c;你将复杂的MPAndroidChart库的使用和配置封…
最新文章