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

news2024/9/24 7:23:22

本文包括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.coloradmin.cn/o/1388112.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

pl/sql程序块的使用

-- Created on 2024-01-15 by ADMINISTRATOR declare -- Local variables hererecord_tablename varchar2(100);---test_record表名record_StartNo integer(19);---test_record开始编号temp_No integer(19);maxnbbh integer(19);nCnt integer : 20;fi…

通用外设-W25Q64

前言 一、SPI通信 二、W25Q64基初时序 1.各种命令代码 2.代码 1.写使能指令 2.读取芯片是否忙碌状态并等待 3.写入数据 4.擦除函数操作 5.读取代码 三.验证 四.擦除说明 总结 前言 在单片机中一般32K FLASH就够用了&#xff0c;但是当我们使用图片或其他大量数据时…

K8s(二)Pod资源——node调度策略、node亲和性、污点与容忍度

目录 node调度策略nodeName和nodeSelector 指定nodeName 指定nodeSelector node亲和性 node节点亲和性 硬亲和性 软亲和性 污点与容忍度 本文主要介绍了在pod中&#xff0c;与node相关的调度策略&#xff0c;亲和性&#xff0c;污点与容忍度等的内容 node调度策略node…

深度学习中指定特定的GPU使用

目录 前言1. 问题所示2. 解决方法 前言 老生常谈&#xff0c;同样的问题&#xff0c;主要来源于&#xff1a;RuntimeError: CUDA error: out of memory 当使用完之后&#xff0c;想从其他方式调试&#xff0c;具体可看我这篇文章的&#xff1a;出现 CUDA out of memory 的解决…

Ps:认识路径

在 Photoshop 中&#xff0c;路径 Path广泛地应用于创建精确的图像边界&#xff08;包括精准抠图&#xff09;以及复杂的图形设计之中。 路径又称为“矢量路径”&#xff0c;或者“贝塞尔曲线” Bezier Curves路径。 路径本身只是一种基于数学方程的“轮廓指示”&#xff0c;并…

Python数据分析案例31——中国A股的月份效应研究(方差分析,虚拟变量回归)

案例背景 本次案例是博主本科在行为金融学课程上做的一个小项目&#xff0c;最近看很多经管类的学生作业都很需要&#xff0c;我就用python来重新做了一遍。不弄那些复杂的机器学习模型了&#xff0c;经管类同学就用简单的统计学方法来做模型就好。 研究目的 有效市场假说是现…

论文复现|tightly focused circularly polarized ring Airy beam

请尊重原创的劳动成果 如需要转载&#xff0c;请后台联系 前言 采用MATLAB复现一篇论文里面的插图&#xff0c;涡旋光束的聚焦的仿真方式有很多种&#xff0c;这里采用MATLAB进行仿真&#xff0c;当然也有其他的很多方式&#xff0c;不同的方式各有千秋。 论文摘要 本文证明…

Sqoop安全性:确保安全的数据传输

确保数据传输的安全性在大数据处理中至关重要。Sqoop作为一个用于数据传输的工具&#xff0c;也提供了多种安全性措施&#xff0c;以确保数据在传输过程中的机密性和完整性。本文将深入探讨Sqoop的安全性特性&#xff0c;提供详细的示例代码和全面的内容&#xff0c;以帮助大家…

压缩编码之不同缩放参数对重建图像质量的影响的python实现——JPEG变换编码不同压缩率的模拟

原理 JPEG&#xff08;Joint Photographic Experts Group&#xff09;是一种常用的图像压缩标准&#xff0c;它通过采用离散余弦变换&#xff08;DCT&#xff09;和量化来实现图像的压缩。 离散余弦变换&#xff08;DCT&#xff09;&#xff1a; JPEG首先将图像分割成8x8的块…

彝族民居一大特色——土掌房

彝族民居一大特色——土掌房在彝区&#xff0c;各地、各支系传承的居室建筑形式是多种多样的&#xff0c;并与当地的居住习俗有密切关联&#xff0c;从村寨的聚落到住宅的地址&#xff1b;从房间的分置到什物的堆放&#xff1b;从建筑结构到民居信仰和禁忌&#xff0c;都表现出…

U-Boot学习(3):.config、defconfig文件对比及图形化配置Kconfig

在上一节中&#xff0c;我们介绍了U-Boot编译和.config配置文件生成分析&#xff0c;我们可以通过make xxx__defconfig来进行一些配置&#xff0c;其中xxx__defconfig对应config目录下的基于不同开发板的一些配置&#xff0c;指令执行完后会根据对应的配置在根目录下生成一个.c…

基于java web的机票管理系统设计与实现设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

Redis主从架构、哨兵集群原理实战

1.主从架构简介 背景 单机部署简单&#xff0c;但是可靠性低&#xff0c;且不能很好利用CPU多核处理能力生产环境必须要保证高可用&#xff0c;一般不可能单机部署读写分离是可用性要求不高、性能要求较高、数据规模小的情况 目标 读写分离&#xff0c;扩展主节点的读能力&…

多选下拉框数据溢出父页面高度被截断

问题 解决 给父页面div一个最小高度minHeight。 <div style{{minHeight: 300,marginTop: 20}}><Row><Select...</Row> </div>&#xff08;在我的具体实例中&#xff0c;下拉框与表格页面都为Tabs ——> TabPane 所包含。故下拉框高度超出页面高…

【Spring实战】29 @Value 注解

文章目录 1. 定义2. 好处3. 示例1&#xff09;注入基本类型2&#xff09;注入集合类型3&#xff09;使用默认值4&#xff09;注入整数和其他类型 总结 在实际的应用中&#xff0c;我们经常需要从外部配置文件或其他配置源中获取参数值。Spring 框架提供了 Value 注解&#xff0…

基于SSM的网上购物商城设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

任务13:使用MapReduce对天气数据进行ETL(获取各基站ID)

任务描述 知识点&#xff1a; 天气数据进行ETL 重 点&#xff1a; 掌握MapReduce程序的运行流程熟练编写MapReduce程序使用MapReduce进行ETL 内 容&#xff1a; 编写MapReduce程序编写Shell脚本&#xff0c;获取MapReduce程序的inputPath将生成的inputPath文件传入到Wi…

【Debian】非图形界面Debian10.0.0安装xfce和lxde桌面

一、安装 1. Debian10.0.0安装xfce桌面 sudo apt update sudo apt install xfce4 startxfce4 2. Debian10.0.0安装lxde桌面 sudo apt-get install lxde安装后重启电脑。 二、说明 XFCE、LXDE 和 GNOME 是三个流行的桌面环境&#xff0c;它们都是为类 Unix 操作系统设计…

【数位dp】【C++算法】600. 不含连续1的非负整数

作者推荐 【矩阵快速幂】封装类及测试用例及样例 涉及知识点 数位dp LeetCode600. 不含连续1的非负整数 给定一个正整数 n &#xff0c;请你统计在 [0, n] 范围的非负整数中&#xff0c;有多少个整数的二进制表示中不存在 连续的 1 。 示例 1: 输入: n 5 输出: 5 解释: 下…

浏览器打印无法显示单选框选中效果

上面是原代码&#xff0c;我点击打印&#xff0c;出现打印页面&#xff0c;但单选框并未勾选中&#xff0c;我在外部放了一模一样的代码是能勾选上的&#xff0c;于是我对打印页的input单选框进行分析&#xff0c;发现他丢失了checked属性。然后通过gpt分析原因。得知了default…