NvidiaRanker

NvidiaRanker

NVIDIA 호스팅 모델을 사용해 문서를 검색어와의 유사도에 따라 순위를 매기는 컴포넌트예요.

출처: 문서

본문

NvidiaRanker는 지정한 검색어에 대한 의미적 관련성에 따라 Document의 순위를 매겨요. NVIDIA NIMs가 제공하는 랭킹 모델을 사용하죠. model 파라미터를 설정하지 않으면 호스팅된 기본값 nv-rerank-qa-mistral-4b:1이 사용돼요.

top_k 파라미터로 반환할 최대 문서 수를 설정할 수도 있어요.

NvidiaRanker에 설정할 수 있는 나머지 커스터마이즈 파라미터는 API 참조에서 확인하세요.

Haystack에서 이 통합을 쓰려면 설치해요.

pip install nvidia-haystack

이 컴포넌트는 기본적으로 NVIDIA_API_KEY 환경 변수를 사용해요. 아니면 초기화할 때 api_key로 NVIDIA API 키를 넘길 수 있어요.

ranker = NvidiaRanker(api_key=Secret.from_token("<your-api-key>"))

더 알아보기 (Learn more)

단독으로 쓰기

이 예제는 NvidiaRanker로 간단한 문서 두 개의 순위를 매겨요. Ranker를 실행하려면 query를 넘기고 documents를 제공한 다음 top_k 파라미터로 반환할 문서 수를 정해요.

from haystack_integrations.components.rankers.nvidia import NvidiaRanker
from haystack import Document
from haystack.utils import Secret


ranker = NvidiaRanker(
    model="nvidia/nv-rerankqa-mistral-4b-v3",
    api_key=Secret.from_env_var("NVIDIA_API_KEY"),
)

query = "What is the capital of Germany?"
documents = [
    Document(content="Berlin is the capital of Germany."),
    Document(content="The capital of Germany is Berlin."),
    Document(content="Germany's capital is Berlin."),
]

result = ranker.run(query, documents, top_k=2)
print(result["documents"])

파이프라인에서 쓰기

아래는 InMemoryDocumentStore에서 키워드 검색(InMemoryBM25Retriever)으로 문서를 가져온 뒤, NvidiaRanker로 검색된 문서를 검색어와의 유사도대로 순위를 매기는 파이프라인 예제예요. 파이프라인은 Ranker의 기본 설정을 사용해요.

from haystack import Document, Pipeline
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack_integrations.components.rankers.nvidia import NvidiaRanker


docs = [
    Document(content="Paris is in France"),
    Document(content="Berlin is in Germany"),
    Document(content="Lyon is in France"),
]

document_store = InMemoryDocumentStore()
document_store.write_documents(docs)

retriever = InMemoryBM25Retriever(document_store=document_store)
ranker = NvidiaRanker()

document_ranker_pipeline = Pipeline()
document_ranker_pipeline.add_component(instance=retriever, name="retriever")
document_ranker_pipeline.add_component(instance=ranker, name="ranker")

document_ranker_pipeline.connect("retriever.documents", "ranker.documents")

query = "Cities in France"
res = document_ranker_pipeline.run(
    data={
        "retriever": {"query": query, "top_k": 3},
        "ranker": {"query": query, "top_k": 2},
    },
)

top_k 파라미터

위 예제에서 Retriever와 Ranker의 top_k 값은 서로 달라요. Retriever의 top_k는 돌려주는 문서 수를 정하고, Ranker는 이 문서들을 정렬해요.

Ranker에는 같은 값이나 더 작은 top_k를 설정할 수 있어요. Ranker의 top_k는 (파이프라인의 마지막 컴포넌트라면) 반환하거나 다음 컴포넌트로 넘기는 문서 수예요. 위 파이프라인에서 Ranker는 마지막 컴포넌트이므로, 실행 결과로 Ranker의 top_k대로 상위 두 문서가 나와요.

top_k 값을 조정하면 성능 최적화에 도움이 돼요. 이 경우 Retriever의 top_k를 작게 하면 Ranker가 처리할 문서가 줄어들어 파이프라인이 빨라질 수 있어요.