LLM

똑똑해진 AI: RAG vs CAG, 인공지능의 지식 확장 전략 대결

AgentAIHub 2025. 3. 18. 09:52

LLM(대규모 언어 모델)의 놀라운 능력에도 불구하고, 이들에게는 치명적인 약점이 있습니다. 바로 훈련 데이터에 포함되지 않은 정보는 알 수 없다는 점입니다. 이 문제를 해결하기 위해 등장한 두 가지 혁신적인 접근법인 RAG(Retrieval Augmented Generation)와 CAG(Cache Augmented Generation)에 대해 알아보겠습니다. 두 기술 모두 AI 모델의 지식을 확장하는 방법이지만, 그 접근 방식과 적합한 사용 사례는 매우 다릅니다.

 

 

RAG vs. CAG: Solving Knowledge Gaps in AI Models

이 영상은 AI 모델의 **지식 격차**를 해결하기 위한 두 가지 주요 기술인 **RAG(Retrieval Augmented Generation)**와 **CAG(Cache Augmented Generation)**를 비교 분석합니다. RAG는 외부 지식 베이스에서 관련 정보를

lilys.ai

 

RAG: 필요할 때 지식을 찾아내는 사서형 AI

RAG는 마치 도서관 사서처럼 필요한 정보를 그때그때 찾아 제공하는 방식입니다. 외부 지식 소스에서 정보를 검색하여 언어 모델의 응답 생성을 향상시키는 접근법으로, 다음과 같은 구조로 작동합니다.

RAG의 작동 원리

RAG 시스템은 크게 오프라인 단계온라인 단계로 나뉩니다1.

  1. 오프라인 단계 (인덱싱 준비)
    • 문서를 의미 있는 청크(chunks)로 분할
    • 각 청크를 벡터 임베딩으로 변환
    • 벡터 데이터베이스에 저장하여 검색 가능한 인덱스 구축
  2. 온라인 단계 (검색 및 생성)
    • 사용자 질문을 받아 벡터로 변환
    • 벡터 데이터베이스에서 유사성 검색을 통해 관련 문서 검색
    • 검색된 문서와 사용자 질문을 함께 LLM의 컨텍스트 창에 입력
    • LLM이 검색된 정보를 기반으로 답변 생성

RAG의 가장 큰 장점은 모듈성이 뛰어나다는 점입니다. 시스템을 전체적으로 재구축하지 않고도 벡터 데이터베이스, 임베딩 모델, LLM 등 각 구성 요소를 필요에 따라 교체할 수 있습니다1.

CAG: 모든 지식을 미리 담아두는 암기형 AI

CAG는 마치 시험 전에 모든 내용을 암기하고 들어가는 학생과 같습니다. 필요한 모든 정보를 미리 모델의 컨텍스트에 로드하고, 이를 캐시하여 활용하는 방식입니다11.

CAG의 작동 원리

  1. 지식 프리로딩
    • 모든 수집된 지식을 하나의 거대한 프롬프트로 포맷
    • 이 정보를 모델의 확장된 컨텍스트 창에 한 번에 로드
    • 모델이 이 정보를 처리하여 KV 캐시(key-value cache) 생성4
  2. 쿼리 처리
    • 사용자가 쿼리를 제출하면 이를 KV 캐시에 추가
    • 모델이 캐시된 정보를 활용하여 추가 검색 없이 바로 답변 생성

CAG는 APE(Adaptive Parallel Encoding)와 같은 기술을 사용하여 각 컨텍스트를 독립적으로 인코딩하고 캐시함으로써 성능을 더욱 향상시킬 수 있습니다414.

RAG vs CAG: 무엇이 더 뛰어날까?

두 기술의 본질적인 차이는 지식 처리의 시점과 방법에 있습니다. RAG는 필요할 때만 정보를 검색하는 반면, CAG는 모든 문서를 미리 로드하여 나중에 활용합니다.

정확성 비교

  • RAG: 정확성은 주로 retriever의 성능에 의존합니다. 만약 retriever가 관련 정보를 찾지 못하면, LLM은 정확한 응답을 제공하기 어렵습니다1.
  • CAG: 모든 관련 정보가 이미 컨텍스트에 로드되어 있기 때문에 정보 자체는 존재하지만, LLM이 방대한 컨텍스트에서 적절한 정보를 식별하는 과정에서 혼동이 발생할 수 있습니다11.

지연 시간 비교

  • RAG: 검색 과정이 추가되어 응답 생성까지 더 많은 시간이 소요됩니다1.
  • CAG: 지식이 이미 캐시된 후에는 단일 전달 과정만으로 응답을 생성할 수 있어 지연 시간이 크게 감소합니다. 연구에 따르면 128K 길이의 컨텍스트에 대해 프리필링 시간을 28배까지 줄이고, 전체 추론 속도를 4.5배까지 향상시킬 수 있습니다414.

확장성 비교

  • RAG: 벡터 데이터베이스의 크기에 따라 확장 가능하며, 수백만 개의 문서도 처리할 수 있습니다1.
  • CAG: 모델의 컨텍스트 창 크기에 제한을 받아, 일반적으로 32,000에서 100,000 토큰의 제한이 있어 수백 개의 문서만 처리할 수 있습니다11.

데이터 최신성

  • RAG: 인덱스를 쉽게 업데이트할 수 있어 최신 정보에 대한 접근이 용이합니다1.
  • CAG: 데이터가 변경될 때마다 전체 KV 캐시를 재계산해야 하므로, 빈번한 데이터 변경이 있는 경우 캐싱의 이점이 감소합니다11.

어떤 상황에서 어떤 기술을 선택해야 할까?

CAG가 적합한 경우

  1. 제한된 도메인 지식
    • 지식 소스가 제한적이고 관리 가능한 크기일 때
    • 데이터가 자주 변경되지 않는 정적인 경우
    • 예: 기업 내부 정책 문서, 제품 매뉴얼, 교육용 콘텐츠
  2. 낮은 지연 시간 요구
    • 빠른 응답 시간이 중요한 실시간 애플리케이션
    • 예: 고객 지원 채팅봇, 실시간 질의응답 시스템
  3. 단순화된 배포
    • 복잡한 검색 인프라를 설정하고 유지하기 어려운 경우
    • 예: 리소스가 제한된 환경, 엣지 배포

RAG가 적합한 경우

  1. 방대한 지식 베이스
    • 모델의 컨텍스트 창에 맞지 않는 대규모 문서 컬렉션
    • 예: 법률 문서 라이브러리, 의학 연구 논문, 대규모 기술 문서
  2. 자주 업데이트되는 정보
    • 데이터가 지속적으로 변경되고 최신 정보가 중요한 경우
    • 예: 뉴스 기반 애플리케이션, 실시간 시장 분석
  3. 정확한 인용이 필요한 경우
    • 응답의 출처를 명확히 추적해야 하는 경우
    • 예: 법률 조언, 의학 정보, 학술 연구 지원

실제 적용 사례

IT 헬프데스크 봇

소규모 기업의 IT 헬프데스크 봇은 자주 묻는 질문과 기술 문서가 제한적이고 자주 변경되지 않기 때문에 CAG 접근 방식이 효과적입니다. 모든 지식을 미리 로드하여 사용자의 IT 관련 질문에 지연 없이 빠르게 응답할 수 있습니다.

법률 연구 보조 시스템

법률 회사의 연구 보조 시스템은 수많은 판례, 법률 문서, 지속적으로 업데이트되는 법규를 다루기 때문에 RAG 접근 방식이 더 적합합니다. 필요한 법률 정보를 정확히 검색하고 출처를 명확히 제시할 수 있습니다.

임상 의사 결정 지원 시스템

병원의 임상 의사 결정 지원 시스템은 하이브리드 접근법이 효과적입니다. 자주 참조하는 의학 지침과 프로토콜은 CAG로 미리 로드하고, 특정 환자 사례나 최신 의학 연구는 RAG를 통해 검색함으로써 정확성과 응답 속도의 균형을 맞출 수 있습니다.

결론: 상황에 맞는 최적의 선택

RAG와 CAG는 모두 LLM을 외부 지식으로 강화하기 위한 유효한 전략입니다. 어떤 접근법을 선택할지는 다음 요소들을 고려하여 결정해야 합니다:

  • 지식 소스의 크기: 소규모는 CAG, 대규모는 RAG
  • 업데이트 빈도: 정적 데이터는 CAG, 동적 데이터는 RAG
  • 인용 필요성: 정확한 출처 추적이 필요하면 RAG
  • 응답 시간: 낮은 지연 시간이 중요하면 CAG
  • 리소스 제한: 인프라 복잡성을 줄이려면 CAG

두 기술은 상호 배타적이지 않으며, 하이브리드 접근법도 많은 상황에서 효과적일 수 있습니다. 결국 AI 시스템의 요구 사항과 제약 조건에 따라 최적의 선택이 달라질 것입니다.

 

#인공지능 #LLM #RAG #CAG #지식증강 #검색증강생성 #캐시증강생성 #AI기술 #자연어처리 #컨텍스트창 #벡터데이터베이스 #APE

  

#인공지능 #LLM #RAG #CAG #지식증강 #검색증강생성 #캐시증강생성 #AI기술 #자연어처리 #컨텍스트창 #벡터데이터베이스 #APE

Smart AI: RAG vs CAG, Battle of Knowledge Expansion Strategies for Artificial Intelligence

Despite the amazing capabilities of Large Language Models (LLMs), they have a fatal weakness: they cannot know information that wasn't included in their training data. Let's explore two innovative approaches that have emerged to solve this problem: RAG (Retrieval Augmented Generation) and CAG (Cache Augmented Generation). Both technologies aim to expand the knowledge of AI models, but their approaches and suitable use cases differ significantly.

RAG: The Librarian AI That Finds Knowledge When Needed

RAG works like a librarian who finds and provides the necessary information as needed. It's an approach that enhances language model responses by retrieving information from external knowledge sources, operating with the following structure.

How RAG Works

RAG systems are broadly divided into an offline phase and an online phase1.

  1. Offline Phase (Indexing Preparation)
    • Split documents into meaningful chunks
    • Convert each chunk into vector embeddings
    • Store in a vector database to build a searchable index
  2. Online Phase (Retrieval and Generation)
    • Receive a user question and convert it to a vector
    • Search for relevant documents in the vector database through similarity search
    • Input the retrieved documents and user question together into the LLM's context window
    • LLM generates answers based on the retrieved information

The biggest advantage of RAG is its excellent modularity. You can replace vector databases, embedding models, or LLMs as needed without rebuilding the entire system1.

CAG: The Memorizing AI That Preloads All Knowledge

CAG is like a student who memorizes all content before an exam. It preloads all necessary information into the model's context and utilizes it by caching11.

How CAG Works

  1. Knowledge Preloading
    • Format all collected knowledge into one giant prompt
    • Load this information at once into the model's extended context window
    • The model processes this information to create a KV cache (key-value cache)4
  2. Query Processing
    • When a user submits a query, it's added to the KV cache
    • The model utilizes cached information to generate answers without additional retrieval

CAG can further improve performance by using technologies like APE (Adaptive Parallel Encoding) to independently encode and cache each context414.

RAG vs CAG: Which Is Superior?

The essential difference between the two technologies lies in when and how knowledge is processed. RAG retrieves information only when needed, while CAG preloads all documents and utilizes them later.

Accuracy Comparison

  • RAG: Accuracy mainly depends on the retriever's performance. If the retriever fails to find relevant information, the LLM will struggle to provide accurate responses1.
  • CAG: Since all relevant information is already loaded in the context, the information itself exists, but confusion may occur in the process of the LLM identifying appropriate information from the vast context11.

Latency Comparison

  • RAG: The addition of the retrieval process requires more time until response generation1.
  • CAG: After knowledge is already cached, responses can be generated with just a single forward pass, greatly reducing latency. Research shows it can reduce prefilling time by up to 28x for a 128K length context, improving overall inference speed by up to 4.5x414.

Scalability Comparison

  • RAG: Can scale according to vector database size and handle millions of documents1.
  • CAG: Limited by the model's context window size, typically 32,000 to 100,000 tokens, allowing processing of only hundreds of documents11.

Data Freshness

  • RAG: Easily update indexes for access to the latest information1.
  • CAG: Requires recalculation of the entire KV cache whenever data changes, reducing the benefits of caching when frequent data changes occur11.

Which Technology Should You Choose in What Situation?

When CAG Is Suitable

  1. Limited Domain Knowledge
    • When knowledge sources are limited and manageable in size
    • When data is static and doesn't change frequently
    • Examples: Corporate internal policy documents, product manuals, educational content
  2. Low Latency Requirements
    • Real-time applications where fast response time is important
    • Examples: Customer support chatbots, real-time Q&A systems
  3. Simplified Deployment
    • When it's difficult to set up and maintain complex search infrastructure
    • Examples: Resource-constrained environments, edge deployments

When RAG Is Suitable

  1. Vast Knowledge Base
    • Large document collections that don't fit into the model's context window
    • Examples: Legal document libraries, medical research papers, large technical documentation
  2. Frequently Updated Information
    • When data changes continuously and latest information is important
    • Examples: News-based applications, real-time market analysis
  3. When Accurate Citations Are Needed
    • When sources of responses need to be clearly tracked
    • Examples: Legal advice, medical information, academic research support

Real Application Cases

IT Helpdesk Bot

An IT helpdesk bot for small businesses is effective with a CAG approach because frequently asked questions and technical documents are limited and don't change often. Preloading all knowledge allows quick responses to users' IT-related questions without delay.

Legal Research Assistant System

A research assistant system for law firms is more suitable for a RAG approach because it deals with numerous case laws, legal documents, and continuously updated regulations. It can accurately search for necessary legal information and clearly present sources.

Clinical Decision Support System

A clinical decision support system for hospitals benefits from a hybrid approach. Frequently referenced medical guidelines and protocols can be preloaded with CAG, while specific patient cases or the latest medical research can be searched through RAG, balancing accuracy and response speed.

Conclusion: Optimal Choice Based on Situation

Both RAG and CAG are valid strategies for enhancing LLMs with external knowledge. The choice between them should consider the following factors:

  • Knowledge Source Size: CAG for small scale, RAG for large scale
  • Update Frequency: CAG for static data, RAG for dynamic data
  • Citation Necessity: RAG when accurate source tracking is needed
  • Response Time: CAG when low latency is important
  • Resource Constraints: CAG to reduce infrastructure complexity

The two technologies are not mutually exclusive, and hybrid approaches can be effective in many situations. Ultimately, the optimal choice will vary depending on the requirements and constraints of the AI system.

 

#ArtificialIntelligence #LLM #RAG #CAG #KnowledgeAugmentation #RetrievalAugmentedGeneration #CacheAugmentedGeneration #AITechnology #NaturalLanguageProcessing #ContextWindow #VectorDatabase #APE

Citations:

  1. https://arxiv.org/html/2503.10677v1
  2. https://arxiv.org/pdf/2410.15040.pdf
  3. http://www.arxiv.org/pdf/2411.06237.pdf
  4. https://openreview.net/pdf/94df95d5f53caa62fc995bccd990653808aff8bd.pdf
  5. https://arxiv.org/html/2502.05431v1
  6. https://arxiv.org/html/2411.16133v1
  7. https://arxiv.org/pdf/2311.05232.pdf
  8. https://arxiv.org/html/2412.15605v1
  9. https://arxiv.org/html/2404.06809v1
  10. https://paperswithcode.com/task/rag/latest?page=11&q=
  11. https://arxiv.org/abs/2412.15605
  12. https://arxiv.org/abs/2402.14480
  13. https://arxiv.org/abs/2404.06809
  14. https://arxiv.org/abs/2502.05431
  15. https://arxiv.org/abs/2411.16133
  16. https://www.semanticscholar.org/paper/acc153f706e14b97e0e78e977b4e996f0fd8e1fc
  17. https://arxiv.org/html/2411.06237v2
  18. https://arxiv.org/html/2402.14480v1
  19. https://arxiv.org/html/2311.05232v2
  20. https://arxiv.org/html/2407.10362v3
  21. https://openreview.net/forum?id=J3xRByRqOz
  22. https://arxiv.org/html/2502.01142v1
  23. https://arxiv.org/pdf/2404.06809.pdf
  24. https://www.semanticscholar.org/paper/00faa1f86ea2b493a2aae281845e15bc7a943c90
  25. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7138549/
  26. https://www.semanticscholar.org/paper/bd88b6aa9e993ddb2c78a1b14f60aee88d5bc163
  27. https://www.semanticscholar.org/paper/91352de78d169661a2c3031bce92cdac4180a08c

 

반응형