콘텐츠로 건너뛰기

RAG를 위한 chunking 전략

웹사이트 RAG를 위한 고정밀 chunking 설계: fixed, semantic, hierarchical, adaptive 전략과 평가.

chunking • rag • retrieval • embeddings

Chunking은 정규화된 raw page content를 retrieval unit으로 바꿉니다. 잘못된 선택은 비용을 늘리고, 너무 많은 fragment를 만들며, 너무 큰 block으로 recall을 떨어뜨리거나, boundary fracture로 precision을 희석합니다. 보편적으로 가장 좋은 방법은 없습니다. 전략은 corpus structure, volatility, query pattern과 맞아야 합니다. 이 guide는 production RAG pipeline을 위한 design space, trade-off, evaluation workflow, optimization lever를 정리합니다.

Chunking이 중요한 이유

목표:

  • 관련 사실이 top-k retrieval에 나타날 확률을 최대화합니다.
  • 생성 답변이 grounded되도록 semantic cohesion을 보존합니다.
  • token utilization을 최적화해 boilerplate embedding 반복을 피합니다.
  • 안정적인 chunk ID로 deterministic incremental update를 가능하게 합니다.

잘 맞지 않는 chunking은 높은 redundancy, 낮은 Recall@k, boundary fact hallucination, 부풀려진 embedding spend로 나타납니다.

고정 창 chunking

간단한 N-token window, 예를 들어 500 token입니다. 장점: deterministic하고 구현이 쉬우며 update behavior가 안정적입니다. 단점: boundary가 concept을 자르고, truncation을 줄이려면 redundant overlap이 필요해 비용이 커집니다. 제한적으로 사용하세요. semantic signal이 신뢰하기 어려운 heterogenous 또는 poorly structured content의 baseline으로 좋습니다.

겹치는 sliding window

Window size W와 overlap O, 예를 들어 500 / 50 token은 boundary에서 fact truncation을 줄입니다. 약 15%를 넘는 overlap은 recall gain이 줄어드는 반면 index size를 계속 키웁니다. O를 낮추기 위해 duplication_ratio = distinct_token_count / total_token_count를 추적하세요.

의미 경계 감지

H2/H3 heading, list grouping, code block, table boundary 같은 structural signal을 따라 segment합니다. min/max token bound를 강제하고, 너무 작은 sibling은 merge하고 너무 큰 section은 split합니다. 이점은 더 높은 cohesion과 더 적은 overlap입니다. 위험은 malformed markup과 inconsistent heading hierarchy입니다. heading이 없을 때 hierarchy repair와 paragraph splitting fallback으로 완화하세요.

계층형 chunking

두 단계 index입니다. coarse section embedding, 예를 들어 tutorial section 전체와 fine-grained subchunk를 함께 둡니다. retrieval flow: coarse ANN → top N section filter → 그 안에서 fine retrieval. 장점: 큰 corpus에서 global search space를 줄이고 latency를 개선합니다. 복잡도: 움직이는 부분이 더 많고 cascade scoring logic이 필요합니다.

Adaptive / dynamic chunking

local semantic density와 structural cue에 따라 chunk size를 조정합니다. 예시 logic: heading section에서 시작하고, >800 token이면 semantic similarity로 scored된 paragraph cluster로 split합니다. <120 token이면 topic divergence가 threshold를 넘지 않는 한 다음 sibling과 merge합니다. embedding 또는 similarity pre-pass가 필요합니다. ingestion 시 한 번 비용을 내고 장기 retrieval efficiency를 높입니다.

Embedding 고려 사항

metadata를 유지하세요: token_count, model_version, content_hash. truncation을 피하려면 token을 미리 계산하고 model call 전에 split합니다. dense model은 boilerplate가 과도하면 성능이 떨어지므로 chunk 전 navigation artifact를 제거하세요. vector_density, 즉 unique terms / tokens를 모니터링해 signal이 낮은 fragment를 드러내고 re-merge candidate로 삼습니다.

평가 방법

전략별 benchmark:

지표목적
Recall@k사실 보존
Precision@kcontext noise
Chunk Count비용 지표
Duplication Ratiooverlap 조정
Avg Tokens per Chunkwindow 활용
Latency (Retrieval)index 효율

gold query set에서 실행하세요. recall gain이 cost와 latency delta를 상회할 때만 전략을 채택합니다.

구현 playbook

  1. Baseline: Fixed 500 + 10% overlap; benchmark를 수집합니다.
  2. Semantic Boundary 도입: heading이 신뢰할 수 있는 곳에서 window를 교체하고 다시 측정합니다.
  3. corpus가 >250k chunk이거나 latency가 target을 넘으면 Hierarchical Layer를 추가합니다.
  4. section size variance가 큰 곳에 adaptive logic을 배포합니다.
  5. 분기별 재평가: 품질 delta당 cost를 새로운 model capability와 비교합니다.

rollback을 위해 iteration마다 chunk manifest diff를 저장합니다.

핵심 요점

  • Semantic boundary는 보통 precision/cost에서 pure fixed window를 이깁니다.
  • Overlap은 감으로 정하지 말고 duplication을 측정해 조정하는 dial입니다.
  • Hierarchical retrieval은 latency가 선형 증가하지 않게 scale을 돕습니다.
  • Stable chunk ID는 안전한 incremental embedding refresh를 가능하게 합니다.
  • 전략 변경은 code deploy처럼 평가하세요: benchmark, compare, log.