使用谷歌开源大模型Gemma 7B构建RAG应用程序

2024年02月29日 由 alex 发表 548 0

简介

随着大型语言模型的发展,构建 RAG(检索增强生成)应用程序的热潮日益高涨。谷歌刚刚推出了一个开源模型: Gemma。我们知道,RAG 是两种基本方法的融合:基于检索的技术和生成模型。基于检索的技术涉及从庞大的知识库或语料库中获取相关信息,以响应特定的查询。生成模型利用从训练数据中获得的洞察力,从零开始创建新的内容,在制作原创文本或回复方面表现出色。在此发布之际,何不尝试一下构建 RAG 管道的新开源模型,看看它的性能如何?


让我们开始吧!


在 Gemma 7B 上构建 RAG 应用程序

在开始工作之前,让我们先安装并导入所需的依赖项。


%pip install -q -U langchain torch transformers sentence-transformers datasets faiss-cpu


import torch
from datasets import load_dataset
from langchain_community.document_loaders.csv_loader import CSVLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers import AutoTokenizer, pipeline
from langchain import HuggingFacePipeline
from langchain.chains import RetrievalQA


加载数据集: Cosmopedia

为了制作 RAG 应用程序,我们选择了拥抱脸数据集 Cosmopedia。该数据集由 Mixtral-8x7B-Instruct-v0.1 生成的合成教科书、博客文章、故事、帖子和 WikiHow 文章组成。该数据集包含 3000 多万个文件和 250 亿个代币,是迄今为止最大的开放合成数据集。


该数据集包含 8 个子集。我们将从 "故事 "子集开始。我们将使用数据集库加载数据集。


data = load_dataset("HuggingFaceTB/cosmopedia", "stories", split="train")


然后,我们将其转换为 Pandas 数据帧,并保存为 CSV 文件。


data = data.to_pandas()
data.to_csv("dataset.csv")
data.head()


2


现在数据集已保存在系统中,我们将使用 LangChain 来加载数据集。


loader = CSVLoader(file_path='./dataset.csv')
data = loader.load()


数据加载完毕后,我们需要分割数据中的文档。在这里,我们将文档分割成 1000 块的大小。这将有助于模型快速高效地工作。


text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
docs = text_splitter.split_documents(data)


使用Hugging Face生成嵌入

之后,我们将使用 Hugging Face Embeddings 并在 Sentence Transformers 模型的帮助下生成嵌入。


modelPath = "sentence-transformers/all-MiniLM-l6-v2"
model_kwargs = {'device':'cpu'}
encode_kwargs = {'normalize_embeddings': False}
embeddings = HuggingFaceEmbeddings(
 model_name=modelPath, 
 model_kwargs=model_kwargs, 
 encode_kwargs=encode_kwargs 
)


存储在 FAISS 数据库中

嵌入已经生成,但我们需要将其存储到向量数据库中。我们将在 FAISS 向量存储库中保存这些嵌入,这是一个用于高效相似性搜索和聚类密集向量的库。


db = FAISS.from_documents(docs, embeddings)


Gemma:SOTA 模型介绍

Gemma 提供两种规模的模型,分别有 20 亿和 70 亿个参数,可满足不同的计算限制和应用场景。提供预训练和微调检查点,以及用于推理和服务的开源代码库。它可在多达 6 万亿个词组的文本数据上进行训练,并利用与 Gemini 模型类似的架构、数据集和训练方法。这两种模型都具有跨文本领域的强大通用能力,在大规模理解和推理任务中表现出色。


该版本包括原始的预训练检查点以及针对特定任务(如对话、指令遵循、帮助和安全)进行优化的微调检查点。为了评估模型的性能并解决任何不足之处,我们进行了全面的评估,从而能够对模型调整机制进行深入研究和调查,并开发出更安全、更负责任的模型开发方法。通过自动基准和人工评估,Gemma 在各个领域(包括问题解答、常识推理、数学和科学以及编码)的性能都超过了同等规模的开放模型。


要开始使用 Gemma 模型,你应该在 "Hugging Face "上确认他们的条款。然后在登录时传递 Hugging Face 标记。


from huggingface_hub import notebook_login
notebook_login()


使用模型初始化标记符。


model = AutoModelForCausalLM.from_pretrained("google/gemma-7b")
tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b", padding=True, truncation=True, max_length=512)


创建文本生成管道。


pipe = pipeline(
 "text-generation", 
 model=model, 
 tokenizer=tokenizer,
 return_tensors='pt',
 max_length=512,
 max_new_tokens=512,
 model_kwargs={"torch_dtype": torch.bfloat16},
 device="cuda"
)


使用管道和模型参数初始化 LLM。


llm = HuggingFacePipeline(
 pipeline=pipe,
 model_kwargs={"temperature": 0.7, "max_length": 512},
)


现在是使用向量存储和 LLM 进行问题解答检索的时候了。


qa = RetrievalQA.from_chain_type(
 llm=llm,
 chain_type="stuff",
 retriever=db.as_retriever()
)


查询 RAG 管道

RAG 管道已准备就绪,让我们通过查询看看它的性能如何。


qa.invoke("Write an educational story for young children.")


结果是:


Once upon a time, in a cozy little village nestled between rolling hills and green meadows, there lived a curious kitten named Whiskers. Whiskers loved to explore every nook and cranny of the village, from the bustling marketplace to the quiet corners where flowers bloomed. One sunny morning, as Whiskers trotted down the cobblestone path, he spotted something shimmering in the distance. With his whiskers twitching in excitement, he scampered towards it, his little paws pitter-pattering on the ground. To his delight, he found a shiny object peeking out from beneath a bush - a beautiful, colorful kite! With a twinkle in his eye, Whiskers decided to take the kite on an adventure. He tugged at the string, and the kite soared into the sky, dancing gracefully with the gentle breeze. Whiskers giggled with joy as he watched the kite soar higher and higher, painting the sky with its vibrant colors.


总结

Gemma 7B 型号的表现非常出色。新的 SOTA 模型使用起来既有趣又令人兴奋。在 FAISS 向量商店的帮助下,我们建立了一个 RAG 管道。

文章来源:https://blog.superteams.ai/steps-to-build-rag-application-with-gemma-7b-llm-43f7251a36a1
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消