FastembedSparseDocumentEmbedder

FastembedSparseDocumentEmbedder

문서 리스트에 희소 임베딩(sparse embedding)을 보강하기 위해 사용하는 컴포넌트예요.

출처: 문서

본문

  • 파이프라인에서의 일반적인 위치: 인덱싱 파이프라인에서 DocumentWriter 앞에 사용해요.
  • 필수 실행 변수: documents(문서 리스트)
  • 출력 변수: documents(희소 임베딩이 보강된 문서 리스트)

문자열에 대한 희소 임베딩을 계산하려면 FastembedSparseTextEmbedder를 사용하세요.

개요 (Overview)

FastembedSparseDocumentEmbedder는 문서 리스트의 희소 임베딩을 계산하고 얻은 벡터를 각 문서의 sparse_embedding 필드에 저장해요. FastEmbed가 지원하는 희소 임베딩 모델을 사용하죠.

이 컴포넌트로 계산한 벡터는 문서 집합에 대해 희소 임베딩 검색을 수행하는 데 필요해요. 검색 중에는 쿼리를 나타내는 희소 벡터를 문서들의 벡터와 비교해 가장 유사하거나 관련 있는 문서를 식별해요.

호환 모델 (Compatible models)

지원되는 모델은 FastEmbed 문서에서 찾을 수 있어요.

현재 지원되는 모델은 SPLADE를 기반으로 해요. SPLADE는 텍스트의 희소 표현을 만드는 기법으로, 임베딩의 각 0이 아닌 값이 BERT WordPiece 어휘에서 용어의 중요도 가중치를 나타내요. 자세한 내용은 희소 임베딩 기반 리트리버를 설명하는 문서를 참고하세요.

설치 (Installation)

이 통합을 Haystack에서 사용하려면 패키지를 설치하세요.

pip install fastembed-haystack

파라미터 (Parameters)

모델이 저장될 경로를 캐시 디렉터리로 설정할 수 있어요. 단일 onnxruntime 세션이 사용할 스레드 수를 설정할 수도 있어요.

cache_dir = "/your_cacheDirectory"
embedder = FastembedSparseDocumentEmbedder(
    model="prithivida/Splade_PP_en_v1",
    cache_dir=cache_dir,
    threads=2,
)

데이터 병렬 인코딩을 사용하려면 parallel과 batch_size 파라미터를 설정할 수 있어요.

  • parallel > 1이면 데이터 병렬 인코딩을 사용해요. 대규모 데이터셋의 오프라인 인코딩에 권장돼요.
  • parallel이 0이면 사용 가능한 모든 코어를 사용해요.
  • None이면 데이터 병렬 처리를 사용하지 않고 기본 onnxruntime 스레딩을 사용해요.

tip

같은 모델 기반의 Sparse Text Embedder와 Sparse Document Embedder를 만들면, Haystack은 뒤에서 공유 리소스를 사용해 리소스를 아껴요.

메타데이터 임베딩 (Embedding Metadata)

텍스트 문서에는 종종 메타데이터가 포함돼요. 메타데이터가 구별되고 의미적으로 의미 있다면, 문서 텍스트와 함께 임베딩해 검색을 개선할 수 있어요.

희소 Document Embedder로 쉽게 할 수 있어요.

from haystack import Document
from haystack_integrations.components.embedders.fastembed import (
    FastembedSparseDocumentEmbedder,
)

doc = Document(
    content="some text",
    meta={"title": "relevant title", "page number": 18},
)

embedder = FastembedSparseDocumentEmbedder(
    model="prithivida/Splade_PP_en_v1",
    meta_fields_to_embed=["title"],
)

docs_w_sparse_embeddings = embedder.run(documents=[doc])["documents"]

사용법 (Usage)

단독 사용 (On its own)

from haystack.dataclasses import Document
from haystack_integrations.components.embedders.fastembed import (
    FastembedSparseDocumentEmbedder,
)

document_list = [
    Document(content="I love pizza!"),
    Document(content="I like spaghetti"),
]

doc_embedder = FastembedSparseDocumentEmbedder()

result = doc_embedder.run(document_list)
print(result["documents"][0])

# Document(id=...,
# content: 'I love pizza!',
# sparse_embedding: vector with 24 non-zero elements)

파이프라인에서 사용 (In a pipeline)

현재 희소 임베딩 검색은 QdrantDocumentStore만 지원해요. 먼저 패키지를 설치하세요.

pip install qdrant-haystack

그다음 이 파이프라인을 사용해 보세요.

from haystack import Document, Pipeline
from haystack.components.writers import DocumentWriter
from haystack_integrations.components.retrievers.qdrant import (
    QdrantSparseEmbeddingRetriever,
)
from haystack_integrations.document_stores.qdrant import QdrantDocumentStore
from haystack.document_stores.types import DuplicatePolicy
from haystack_integrations.components.embedders.fastembed import (
    FastembedSparseDocumentEmbedder,
    FastembedSparseTextEmbedder,
)

document_store = QdrantDocumentStore(
    ":memory:",
    recreate_index=True,
    use_sparse_embeddings=True,
)

documents = [
    Document(content="My name is Wolfgang and I live in Berlin"),
    Document(content="I saw a black horse running"),
    Document(content="Germany has many big cities"),
    Document(content="fastembed is supported by and maintained by Qdrant."),
]

sparse_document_embedder = FastembedSparseDocumentEmbedder()
writer = DocumentWriter(document_store=document_store, policy=DuplicatePolicy.OVERWRITE)

indexing_pipeline = Pipeline()
indexing_pipeline.add_component("sparse_document_embedder", sparse_document_embedder)
indexing_pipeline.add_component("writer", writer)
indexing_pipeline.connect("sparse_document_embedder", "writer")

indexing_pipeline.run({"sparse_document_embedder": {"documents": documents}})

query_pipeline = Pipeline()
query_pipeline.add_component("sparse_text_embedder", FastembedSparseTextEmbedder())
query_pipeline.add_component(
    "sparse_retriever",
    QdrantSparseEmbeddingRetriever(document_store=document_store),
)
query_pipeline.connect(
    "sparse_text_embedder.sparse_embedding",
    "sparse_retriever.query_sparse_embedding",
)

query = "Who supports fastembed?"

result = query_pipeline.run({"sparse_text_embedder": {"text": query}})

print(result["sparse_retriever"]["documents"][0])  # noqa: T201

# Document(id=...,
# content: 'fastembed is supported by and maintained by Qdrant.',
# score: 0.758..)

추가 자료 (Additional References)

🧑‍🍳 Cookbook: Sparse Embedding Retrieval with Qdrant and FastEmbed

더 알아보기 (Learn more)