9 분 소요

1. 원문 링크

2. RAG의 요점

  • 정의 : 검색기를 활용하여 관련된 컨텍스트를 찾아, LLM에게 제공함으로써, 환각증상(Halluciation)을 해결하고 사용자가 요구하는 대답을 더욱 정확히 할 수 있도록 하는 프롬프트 엔지니어의 일종이라고 보는 것이 좋을 듯하다.

  • 도구

    1. 로더 : 텍스트 추출 / 일반적으로 PyPDF 등과 같은 PDF리더기 등이 사용되어 텍스트를 추출함
    2. 텍스트 스플리터 : 긴 문서를 작은 단위인 청크(chunk)로 나누는 텍스트 분리 도구 → 전반적인 콘텍스트 맥락 파악을 강화하기 위해 일부 문장 중첩 가능
    3. 임베딩기 : 위치 배정 / 단어를 다차원 공간에 분포시켜서 거리 측정을 통해 유사도를 도출하는 도구(그림출처 : AWS) 임베딩기
    4. VectorDB : 검색할 텍스트를 보관한 DB / sqlite3 등
    5. retriver : 검색기 / 텍스트를 검색하는 것
    6. LLM : 거대 언어 모델 / gemini 등

3. 코드 예시

  • 참조 : https://www.youtube.com/watch?v=Xp7yFtpmXPk

      ## 관련 라이브러리 다운로드
      ! pip install -U --quiet langchain-google-genai
      ! pip install -U --quiet langchain tiktoken pypdf sentence_transformers chromadb
    
      from langchain.document_loaders import PyPDFLoader
      from langchain.text_splitter import RecursiveCharacterTextSplitter
      from langchain.embeddings import HuggingFaceEmbeddings
      from langchain.vectorstores import Chroma
      from langchain_google_genai import ChatGoogleGenerativeAI
      from langchain.prompts import ChatPromptTemplate
      from langchain.schema.runnable import RunnableMap
      import os
    
      ## 1. 로더(PDF시 PDF리더, TEXT시 단순 텍스트)
      ### 로더는 종류별로 각종 메타데이터(텍스트 이외의 정보 ex)페이지 번호 등)
      loader = PyPDFLoader("읽을 텍스트.pdf")
      pages = loader.load_and_split() ## 페이지별로 찢기
    
      ## 2. 토크나이저
      text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50) 
      texts = text_splitter.split_documents(pages)
    
      # 3. 임베딩기 선정(Open ai 또는 Hugging face)
      model_name = "jhgan/ko-sbert-nli" # 3. 임베딩기
      model_kwargs = {'device': 'cpu'}
      encode_kwargs = {'normalize_embeddings': True}
      hf = HuggingFaceEmbeddings(
          model_name=model_name,
          model_kwargs=model_kwargs,
          encode_kwargs=encode_kwargs
      )
    
      ## 4. VectorDB(Chroma)
      docsearch = Chroma.from_documents(texts, hf) 
    
      ## 5. 검색기
      retriever = docsearch.as_retriever(
                                      search_type="mmr",
                                      search_kwargs={'k':5, 'fetch_k': 50}) ## k는 검색 유사도 문장 수
      retriever.get_relevant_documents("검색 키워드") ## 이 후 chain.invoke question이 들어올 곳
    
    
      ## 프롬프트
      template = """Answer the question as based only on the following context:
      {context}
    
      Question: {question}
      """
    
      prompt = ChatPromptTemplate.from_template(template)
    
      ## 6. LLM 선정
      os.environ['GOOGLE_API_KEY'] = "gemini-api-key"
      gemini = ChatGoogleGenerativeAI(model="gemini-pro", temperature = 0)
    
      ## RAG
      chain = RunnableMap({
          "context": lambda x: retriever.get_relevant_documents(x['question']),
          "question": lambda x: x['question']
      }) | prompt | gemini
    
    
      Markdown(chain.invoke({'question': "묻고 싶은 문장"}).content)
    
    


  • 텍스트로 읽을 시

      with open('읽힐 텍스트.txt', 'r') as file:
          lines = file.readlines()
    
      docsearch = Chroma.from_texts(lines, hf)
    

4. 논문 리뷰

Abstract

  • RAG기법의 등장배경
    • 요약 : LLM의 지식 기반 작업에 대한 능력, 자신의 결정에 대한 근거를 제시하거나 지식을 업데이트하는 것은 여전히 제한적
    • 원문 : their ability to access and precisely manipulate knowledge is still limited, and hence on knowledge-intensive tasks, their performance lags behind task-specific architectures Additionally, providing provenance for their decisions and updating their world knowledge remain open research problems
  • RAG 소개
    • 요약 : 사전 학습된 시퀀스 모델과 위키피디아 벡터와 검색기가 결합된 RAG모델을 소개
    • 원문 : We introduce RAG models where the parametric memory is a pre-trained seq2seq model and the non-parametric memory is a dense vector index of Wikipedia, accessed with a pre-trained neural retriever
  • 실험 내용
    • 요약 : 두가지 RAG 기법을 비교(생성된 시퀀스 전반에 같은 구절 vs 토큰당 다른 구절)
    • 원문 : We compare two RAG formulations, one which conditions on the same retrieved passages across the whole generated sequence, and another which can use different passages per token

Introduction

  • RAG 소개
    • 요약 : RAG는 위키피디아 벡터를 사전 학습된 뉴럴 검색기 통해 접근하는 사전 학습된 시퀀스 트랜스포머 모델
    • 원문 : We endow pre-trained, parametric-memory generation models with a non-parametric memory through a general-purpose fine-tuning approach which we refer to as retrieval-augmented generation (RAG). We build RAG models where the parametric memory is a pre-trained seq2seq transformer, and the non-parametric memory is a dense vector index of Wikipedia, accessed with a pre-trained neural retriever
  • RAG의 강점
    • 요약(의역) : 학습된(parametric) 지식, 학습되지 않은(non-parametric) 지식의 결합으로 인간조차 외부 지식 원천이 필요한 분야인 지식 기반 작업을 가능케함
    • 원문 : Our results highlight the benefits of combining parametric and non-parametric memory with generation for nowledge-intensive tasks—tasks that humans could not reasonably be expected to perform without access to an external knowledge source.
  • 주요 용어
    • DPR(Dense Passage Retriever) : 검색기
    • BART(seq2seq model) : 시퀀스 모델

Methods

  • 주요 용어
    • $x$ : the input sequence
    • $y$ : target sequence
    • $z$ : a retrieved passage
    • $p_{\eta}(z|x)$ : a retriever with parameters $\eta$
    • $p_{\theta}(y_{i}|x,z,y_{1:i-1})$ : a generator
      • $i$ : time
      • $\theta$ : a current token based on a context of the previous $i-1$ tokens $y_{1:i-1}$
  • RAG-Sequence Model
    • 요약 : 시퀀스 확률(p(y$|$x))를 얻기 위해 검색된 문서를 하나의 숨겨진 변수로 활용(똑같은 검색된 문서 사용)
    • 원문 : The RAG-Sequence model uses the same retrieved document to generate the complete sequence. Technically, it treats the retrieved document as a single latent variable that is marginalized to get the seq2seq probability p(y$|$x) via a top-K approximation
    • 수식
      • $P_{RAG-Sequence}(y|x) \approx \sum_{z \in top-k(p(\cdot|x))}{p_{\eta}(z|x)} \prod_{i}^{N}{p_{\theta}(y_{i}|x,z,y_{1:i-1})}$
  • RAG-Token Model
    • 요약 : 각 토큰에 따라 다른 문서 활용
    • 원문 : In the RAG-Token model we can draw a different latent document for each target token and marginalize accordingly. This allows the generator to choose content from several documents when producing an answer.
    • 수식
      • $P_{RAG-Token}(y|x) \approx \prod_{i}^{N} \sum_{z \in top-k(p(\cdot|x))}{p_{\eta}(z|x)p_{\theta}(y_{i}|x,z,y_{1:i-1})}$
  • Retriever: DPR
    • 주요 용어
      • $d(z) = BERT_{d}(z)$ : dense representation of a document produced by a BERT document encoder
      • $q(x) = BERT_{q}(x)$ : a query representation produced by a query encoder, also based on BERT
    • 요약 : 사전 학습된 bi-encoder를 기반으로 문서 인덱스 생성(검색기 생성)
    • 원문 : We use a pre-trained bi-encoder from DPR to initialize our retriever and to build the document index
    • 수식(bi-encoder architecture) : 벡터 표현의 내적이 클수록 높은 확률
      • $p_{\eta}(z|x) \propto exp(d(z)^{T}q(x))$
  • Generator: BART
    • 요약 : BART-large 사용(400M params)
    • 원문 : The generator component pθ(yi|x, z, y1:i−1) could be modelled using any encoder-decoder. We use BART-large, a pre-trained seq2seq transformer with 400M parameters.
  • Training
    • 원문 : we minimize the negative marginal log-likelihood of each target using stochastic gradient descent with Adam
    • 손실함수 : $\sum_{j} -logp(y_{j}|x_{j})$
    • 옵티마이저 : adam
  • Decoding
    • 요약 : RAG 디코딩에는 RAG-Token과 RAG-Sequence이라는 두 가지 주요 방법이 있음.
    • RAG-Token : ${p_{\theta}}'(y_i|x,y_{1:i-1}) = \sum_{z \in top-k(p(\cdot|x))}{p_{\eta}(z|x)p_{\theta}(y_{i}|x,z_i,y_{1:i-1})}$이라는 전이 확률을 가진 표준 자동 회귀 seq2seq생성기
    • RAG-Sequence :
      • Thorough Decoding(정확도 높고 계산량 많음)
        • 원문 : To estimate the probability of an hypothesis y we run an additional forward pass for each document z for which y does not appear in the beam, multiply generator probability with $p_{\eta}(z|x)$ and then sum the probabilities across beams for the marginals
        • 각 문서 z에 대해 빔 검색 실행, 후보 시퀀시 생성, 생성자 확률과 문서 확률을 곱하여 전체 확률 계산, 생성되지 않은 후보 시퀀스에 대해 각 문서마다 추가적인 forward pass 수행
      • Fast Decoding(상대적으로 정확도 낮고 계산량 적음)
        • 원문 : we can make a further approximation that $p_{\theta}(y|x, z_i) ≈ 0$ where y was not generated during beam search from x, zi
        • 근사치를 추가해 후보 시퀀스 생성 후 추가적인 forward pass 없이 확률 계산

Experiments

  • 위키피디아 데이터, FAISS(검색기)를 활용해 다양한 테스크 실험함.
    • 원문 : We experiment with RAG in a wide range of knowledge-intensive tasks. For all experiments, we use a single Wikipedia dump for our non-parametric knowledge source.
  • Open-domain Question Answering(답변능력)
    • 추출적 질문 답변(Extractive QA), 폐쇄형 질문 답변(Closed_Book QA)와 비교하여 외부 지식을 활용하여 질문에 대해 좀 더 정확한 답변을 생성가능한지 점검하기 위함
      • 실험 데이터 : Natural Questions(NQ), TriviaQA(TQA), WebQuestions(WQ), CuratedTrec(CT) 등 4개 QA세트
    • 원문 : We compare RAG to the popular extractive QA paradigm (5, 7, 31, 26), where answers are extracted spans from retrieved documents, relying primarily on non-parametric knowledge. We also compare to “Closed-Book QA” approaches, which, like RAG, generate answers, but which do not exploit retrieval, instead relying purely on parametric knowledge
  • Abstractive Question Answering(추론능력)
    • “캘리포니아 볼케이노의 날씨는 어떻습니까?”와 같이 위키피디아 만으로 답변이 어려운 질문에 얼만큼 잘 대답하는 지 점검하기 위함
      • 실험 데이터 : MAMARCO 데이터셋
    • 원문 : MSMARCO has some questions that cannot be answered in a way that matches the reference answer without access to the gold passages, such as “What is the weather in Volcano, CA?” so performance will be lower without using gold passages.
  • Jeopardy Question Generation(생성능력)
    • Jeopardy란? 퀴즈쇼, 즉 고차원 질문 생성 능력을 점검하기 위함.
    • “1986년 멕시코는 이 국제 스포츠 대회를 두 번째 개최한 첫 번째 국가가 되었습니다 / 답 : 월드컵” 등 사실 기반으로한 질문을 생성하는 능력
      • 실험 데이터 : SearchQA
      • 평가방법 : SQuAD-tuned Q-BLEU-1 metric, 사람 평가
    • 원문 : we propose the more demanding task of generating Jeopardy questions. Jeopardy is an unusual format that consists of trying to guess an entity from a fact about that entity. For example, “The World Cup” is the answer to the question “In 1986 Mexico scored as the first country to host this international sports competition twice.” As Jeopardy questions are precise, factual statements, generating Jeopardy questions conditioned on their answer entities constitutes a challenging knowledge-intensive generation task.
  • Fact Verification(팩트체크)
    • 주장이 위키피디아에 의해 지원/반박 되는지 혹은 정보가 없는지 판단하는 태스크
      • 실험 데이터 : FEVER 데이터셋
    • 원문 : FEVER requires classifying whether a natural language claim is supported or refuted by Wikipedia, or whether there is not enough information to decide

Results

  • Open-domain Question Answering(답변능력)
    • 결론적으로 검색된 문건에 없는 내용 일때조차 추출적 모델이 0%, RAG는 11.8% 정확도를 보여 더 나은 성능을 보임.
      • 원문 : Furthermore, RAG can generate correct answers even when the correct answer is not in any retrieved document, achieving 11.8% accuracy in such cases for NQ, where an extractive model would score 0%.
  • Abstractive Question Answering(추론능력)
    • RAG모델이 hallucination이 줄고, 좀더 정확하고 더 다양하게 답변하는 것을 알 수 있었다.
      • 원문 : we find that RAG models hallucinate less and generate factually correct text more often than BART. Later, we also show that RAG generations are more diverse than BART generations (see §4.5).
  • Jeopardy Question Generation(생성능력)
    • RAG-Token > RAG-Sequence > others의 성능을 보여줌.(평가자들이 452개의 케이스 중 42.7%만큼을 RAG, 7.1%만큼을 BART가, 17%만큼을 둘다 모두 사실 기반이라 평가)
      • 원문 : RAG-Token performs better than RAG-Sequence on Jeopardy question generation, with both models outperforming BART on Q-BLEU-1. 4 shows human evaluation results, over 452 pairs of generations from BART and RAG-Token. Evaluators indicated that BART was more factual than RAG in only 7.1% of cases, while RAG was more factual in 42.7% of cases, and both RAG and BART were factual in a further 17% of cases, clearly demonstrating the effectiveness of RAG on the task over a state-of-the-art generation model
    • ✨정보가 파라미터에 저장되어 있는 증거 발견(외부 지식 없이도 BART모델이 (부족했던) 제목을 완성시킴)
      • 원문 : We find evidence for this hypothesis by feeding the BART-only baseline with the partial decoding “The Sun. BART completes the generation “The Sun Also Rises” is a novel by this author of “The Sun Also Rises” indicating the title “The Sun Also Rises” is stored in BART’s parameters
  • Fact Verification(팩트체크)
    • 3-way분류(지지/반박/불확실) 태스크에서 최고의 모델(복잡한 파이프라인 + 도메인 특화)와 4.3% 이내의 차이를 보임(막대한 엔지니어링 작업 미필요)
      • 원문 : Table 2 shows our results on FEVER. For 3-way classification, RAG scores are within 4.3% of state-of-the-art models, which are complex pipeline systems with domain-specific architectures and substantial engineering, trained using intermediate retrieval supervision, which RAG does not require.
    • 검색기 성능면에서 상위 1개 문건은 71% 케이스에서 실제 일치하는 근거 보유, 상위 10개까지 확대하면 90%까지 확대됨(올바르게 외부 정보 제공함을 시사)
      • 원문 : We calculate the overlap in article titles between the top k documents retrieved by RAG and gold evidence annotations. We find that the top retrieved document is from a gold article in 71% of cases, and a gold article is present in the top 10 retrieved articles in 90% of cases.

Additional Results

  • Generation Diversity(생성 다양성)
    • Jeopardy 질문 생성에서 BART모델보다 더 사실적이고 구체적이며 다양한 질문 생성한다는 점 찾음
  • Retrieval Ablations(검색능력)
    • 검색 능력 향상이 성능 향상에 중요한 역할을 할 수 있다는 점 시사
  • Index hot-swapping(인덱스 변경)
    • 논파라미터 모델이게 쉽게 지식을 업데이트할 수 있음, 즉 인덱싱을 함에 따라 다양한 시간대, 케이스에 대응 가능함을 시사
  • Effect of Retrieving more documents(제공하는 문서 개수)
    • 5건, 10건 정도의 문서를 제공하는데 큰 유위미한 차이 못 찾음. 단 RAG-Sequence모델은 검색 문서를 가져올수록 성능이 향상되는 반면 RAG-Token 모델은 10개의 문서에서 최고 성능을 보였음. 즉, 제공하는 문서의 개수에 따라 모델에 성능에 영향을 끼칠 수 있음을 시사

댓글남기기