🚀 완전 관리형 Milvus인 Zilliz Cloud를 무료로 체험해보세요—10배 더 빠른 성능을 경험하세요! 지금 체험하기>>

milvus-logo
LFAI
  • Home
  • Blog
  • 임베딩 모델과 PyMilvus 통합 소개

임베딩 모델과 PyMilvus 통합 소개

  • Engineering
June 05, 2024
Stephen Batifol

Milvus는 AI 애플리케이션을 위해 특별히 설계된 오픈 소스 벡터 데이터베이스입니다. 머신 러닝, 딥 러닝, 그 외 어떤 AI 관련 프로젝트를 진행하든 Milvus는 대규모 벡터 데이터를 처리할 수 있는 강력하고 효율적인 방법을 제공합니다.

이제 Milvus용 Python SDK인 PyMilvus의 모델 모듈 통합을 통해 임베딩 및 재랭크 모델을 더욱 쉽게 추가할 수 있습니다. 이 통합을 통해 데이터를 검색 가능한 벡터로 변환하거나 검색 증강 생성(RAG)과 같이 보다 정확한 결과를 위해 결과를 재랭크하는 작업을 간소화할 수 있습니다.

이 블로그에서는 밀도 임베딩 모델, 스파스 임베딩 모델, 리랭커를 검토하고 Python 애플리케이션에서 로컬로 실행할 수 있는 Milvus의 경량 버전인 Milvus Lite를 사용해 실제로 이를 사용하는 방법을 보여드립니다.

고밀도 임베딩과 스파스 임베딩

통합 기능을 사용하는 방법을 안내하기 전에 벡터 임베딩의 두 가지 주요 범주를 살펴보겠습니다.

벡터 임베딩은 일반적으로 두 가지 주요 카테고리로 나뉩니다: 고밀도 임 베딩과 스파스 임베딩입니다.

  • 고밀도 임베딩은 대부분의 요소 또는 모든 요소가 0이 아닌 고차원 벡터로, 텍스트 의미나 퍼지 의미를 인코딩하는 데 이상적입니다.

  • 스파스 임베딩은 0 요소가 많은 고차원 벡터로, 정확하거나 인접한 개념을 인코딩하는 데 더 적합합니다.

Milvus는 두 가지 유형의 임베딩을 모두 지원하며 하이브리드 검색을 제공합니다. 하이브리드 검색을 사용하면 동일한 컬렉션 내에서 다양한 벡터 필드에 걸쳐 검색을 수행할 수 있습니다. 이러한 벡터는 데이터의 여러 측면을 나타내거나, 다양한 임베딩 모델을 사용하거나, 리랭커를 사용해 결과를 결합하는 등 서로 다른 데이터 처리 방법을 사용할 수 있습니다.

임베딩 및 재랭크 통합을 사용하는 방법

다음 섹션에서는 통합 기능을 사용해 임베딩을 생성하고 벡터 검색을 수행하는 세 가지 실제 예시를 보여드리겠습니다.

예 1: 기본 임베딩 함수를 사용하여 고밀도 벡터 생성하기

Milvus에서 임베딩 및 리랭크 기능을 사용하려면 model 패키지와 함께 pymilvus 클라이언트를 설치해야 합니다.

pip install "pymilvus[model]"

이 단계에서는 Milvus Lite를 설치하여 Python 애플리케이션 내에서 Milvus를 로컬로 실행할 수 있습니다. 또한 임베딩 및 리랭킹을 위한 모든 유틸리티가 포함된 모델 서브 패키지도 포함되어 있습니다.

모델 서브 패키지는 OpenAI, Sentence Transformers, BGE-M3, BM25, SPLADE, Jina AI 사전 학습 모델 등 다양한 임베딩 모델을 지원합니다.

이 예에서는 간결성을 위해 all-MiniLM-L6-v2 Sentence Transformer 모델을 기반으로 한 DefaultEmbeddingFunction 을 사용합니다. 이 모델의 용량은 약 70MB이며 처음 사용할 때 다운로드됩니다:

from pymilvus import model

# This will download "all-MiniLM-L6-v2", a lightweight model.
ef = model.DefaultEmbeddingFunction()

# Data from which embeddings are to be generated
docs = [
   "Artificial intelligence was founded as an academic discipline in 1956.",
   "Alan Turing was the first person to conduct substantial research in AI.",
   "Born in Maida Vale, London, Turing was raised in southern England.",
]

embeddings = ef.encode_documents(docs)

print("Embeddings:", embeddings)
# Print dimension and shape of embeddings
print("Dim:", ef.dim, embeddings[0].shape)

예상 출력은 다음과 같아야 합니다:

Embeddings: [array([-3.09392996e-02, -1.80662833e-02,  1.34775648e-02,  2.77156215e-02,
      -4.86349640e-03, -3.12581174e-02, -3.55921760e-02,  5.76934684e-03,
       2.80773244e-03,  1.35783911e-01,  3.59678417e-02,  6.17732145e-02,
...
      -4.61330153e-02, -4.85207550e-02,  3.13997865e-02,  7.82178566e-02,
      -4.75336798e-02,  5.21207601e-02,  9.04406682e-02, -5.36676683e-02],
     dtype=float32)]
Dim: 384 (384,)

예제 2: BM25 모델을 사용하여 스파스 벡터 생성하기

BM25는 단어 발생 빈도를 사용하여 쿼리와 문서 간의 관련성을 결정하는 잘 알려진 방법입니다. 이 예에서는 BM25EmbeddingFunction 을 사용하여 쿼리와 문서에 대한 스파스 임베딩을 생성하는 방법을 보여드리겠습니다.

BM25에서는 문서의 통계를 계산하여 문서의 패턴을 나타낼 수 있는 IDF(역문서 빈도)를 얻는 것이 중요합니다. IDF는 모든 문서에서 단어가 얼마나 많은 정보를 제공하는지, 그 단어가 흔한지 또는 드문지를 측정합니다.

from pymilvus.model.sparse import BM25EmbeddingFunction

# 1. Prepare a small corpus to search
docs = [
   "Artificial intelligence was founded as an academic discipline in 1956.",
   "Alan Turing was the first person to conduct substantial research in AI.",
   "Born in Maida Vale, London, Turing was raised in southern England.",
]
query = "Where was Turing born?"
bm25_ef = BM25EmbeddingFunction()

# 2. Fit the corpus to get BM25 model parameters on your documents.
bm25_ef.fit(docs)

# 3. Store the fitted parameters to expedite future processing.
bm25_ef.save("bm25_params.json")

# 4. Load the saved params
new_bm25_ef = BM25EmbeddingFunction()
new_bm25_ef.load("bm25_params.json")

docs_embeddings = new_bm25_ef.encode_documents(docs)
query_embeddings = new_bm25_ef.encode_queries([query])
print("Dim:", new_bm25_ef.dim, list(docs_embeddings)[0].shape)

예 3: 리랭커 사용

검색 시스템은 가장 관련성이 높은 결과를 빠르고 효율적으로 찾는 것을 목표로 합니다. 전통적으로 BM25 또는 TF-IDF와 같은 방법은 키워드 매칭을 기반으로 검색 결과의 순위를 매기는 데 사용되어 왔습니다. 임베딩 기반 코사인 유사도와 같은 최근의 방법은 간단하지만 언어의 미묘한 차이, 그리고 가장 중요한 문서와 쿼리의 의도 간의 상호 작용을 놓칠 수 있습니다.

이때 리랭커를 사용하면 도움이 됩니다. 리랭커는 임베딩/토큰 기반 검색에서 제공되는 검색의 초기 결과 집합을 가져와서 사용자의 의도에 더 가깝게 일치하도록 재평가하는 고급 AI 모델입니다. 표면적인 수준의 용어 매칭을 넘어 검색 쿼리와 문서 콘텐츠 간의 심층적인 상호 작용을 고려합니다.

이 예에서는 Jina AI Reranker를 사용하겠습니다.

from pymilvus.model.reranker import JinaRerankFunction

jina_api_key = "<YOUR_JINA_API_KEY>"

rf = JinaRerankFunction("jina-reranker-v1-base-en", jina_api_key)

query = "What event in 1956 marked the official birth of artificial intelligence as a discipline?"

documents = [
   "In 1950, Alan Turing published his seminal paper, 'Computing Machinery and Intelligence,' proposing the Turing Test as a criterion of intelligence, a foundational concept in the philosophy and development of artificial intelligence.",
   "The Dartmouth Conference in 1956 is considered the birthplace of artificial intelligence as a field; here, John McCarthy and others coined the term 'artificial intelligence' and laid out its basic goals.",
   "In 1951, British mathematician and computer scientist Alan Turing also developed the first program designed to play chess, demonstrating an early example of AI in game strategy.",
   "The invention of the Logic Theorist by Allen Newell, Herbert A. Simon, and Cliff Shaw in 1955 marked the creation of the first true AI program, which was capable of solving logic problems, akin to proving mathematical theorems."
]

results = rf(query, documents)

for result in results:
   print(f"Index: {result.index}")
   print(f"Score: {result.score:.6f}")
   print(f"Text: {result.text}\n")

예상되는 결과는 다음과 비슷합니다:

Index: 1
Score: 0.937096
Text: The Dartmouth Conference in 1956 is considered the birthplace of artificial intelligence as a field; here, John McCarthy and others coined the term 'artificial intelligence' and laid out its basic goals.

Index: 3
Score: 0.354210
Text: The invention of the Logic Theorist by Allen Newell, Herbert A. Simon, and Cliff Shaw in 1955 marked the creation of the first true AI program, which was capable of solving logic problems, akin to proving mathematical theorems.

Index: 0
Score: 0.349866
Text: In 1950, Alan Turing published his seminal paper, 'Computing Machinery and Intelligence,' proposing the Turing Test as a criterion of intelligence, a foundational concept in the philosophy and development of artificial intelligence.

Index: 2
Score: 0.272896
Text: In 1951, British mathematician and computer scientist Alan Turing also developed the first program designed to play chess, demonstrating an early example of AI in game strategy.

GitHub에서 별표를 누르고 Discord에 참여하세요!

이 블로그 게시물이 마음에 드셨다면 GitHub에서 Milvus를 별표로 추천해 주시고, Discord에 가입해 주세요! 💙

Like the article? Spread the word

계속 읽기