|
| 1 | +"""Neural reranker for second-stage retrieval refinement. |
| 2 | +
|
| 3 | +Uses a cross-encoder model to re-score (query, passage) pairs with full |
| 4 | +attention, producing much more accurate relevance scores than embedding |
| 5 | +cosine similarity alone. |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +import os |
| 10 | +import time |
| 11 | +from typing import Any, Dict, List, Optional |
| 12 | + |
| 13 | +import requests |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class NvidiaReranker: |
| 19 | + """NVIDIA NIM reranker using the /reranking endpoint.""" |
| 20 | + |
| 21 | + _DEFAULT_URL = ( |
| 22 | + "https://ai.api.nvidia.com/v1/retrieval/" |
| 23 | + "nvidia/llama-3_2-nv-rerankqa-1b-v2/reranking" |
| 24 | + ) |
| 25 | + |
| 26 | + def __init__(self, config: Optional[Dict[str, Any]] = None): |
| 27 | + config = config or {} |
| 28 | + self.model = config.get("model", "nvidia/llama-3.2-nv-rerankqa-1b-v2") |
| 29 | + api_key_env = config.get("api_key_env", "NVIDIA_API_KEY") |
| 30 | + self.api_key = config.get("api_key") or os.getenv(api_key_env) |
| 31 | + if not self.api_key: |
| 32 | + raise ValueError( |
| 33 | + f"NVIDIA API key required for reranker. Set config['api_key'] or {api_key_env} env var." |
| 34 | + ) |
| 35 | + # Build URL from model name: replace / with _ and dots with _ |
| 36 | + # e.g. nvidia/llama-3.2-nv-rerankqa-1b-v2 -> nvidia/llama-3_2-nv-rerankqa-1b-v2 |
| 37 | + model_path = self.model.replace(".", "_") |
| 38 | + self.url = config.get( |
| 39 | + "url", |
| 40 | + f"https://ai.api.nvidia.com/v1/retrieval/{model_path}/reranking", |
| 41 | + ) |
| 42 | + self.timeout = config.get("timeout", 30) |
| 43 | + self.max_retries = config.get("max_retries", 2) |
| 44 | + |
| 45 | + def rerank( |
| 46 | + self, |
| 47 | + query: str, |
| 48 | + passages: List[str], |
| 49 | + top_n: int = 0, |
| 50 | + ) -> List[Dict[str, Any]]: |
| 51 | + """Rerank passages against a query. |
| 52 | +
|
| 53 | + Args: |
| 54 | + query: The search query. |
| 55 | + passages: List of passage texts to rerank. |
| 56 | + top_n: Number of top results to return (0 = return all, re-sorted). |
| 57 | +
|
| 58 | + Returns: |
| 59 | + List of dicts with keys: index (original position), logit, text. |
| 60 | + Sorted by logit descending. |
| 61 | + """ |
| 62 | + if not passages: |
| 63 | + return [] |
| 64 | + if len(passages) == 1: |
| 65 | + return [{"index": 0, "logit": 0.0, "text": passages[0]}] |
| 66 | + |
| 67 | + payload = { |
| 68 | + "model": self.model, |
| 69 | + "query": {"text": query}, |
| 70 | + "passages": [{"text": p} for p in passages], |
| 71 | + } |
| 72 | + if top_n > 0: |
| 73 | + payload["top_n"] = top_n |
| 74 | + |
| 75 | + headers = { |
| 76 | + "Authorization": f"Bearer {self.api_key}", |
| 77 | + "Content-Type": "application/json", |
| 78 | + "Accept": "application/json", |
| 79 | + } |
| 80 | + |
| 81 | + last_exc = None |
| 82 | + for attempt in range(self.max_retries + 1): |
| 83 | + try: |
| 84 | + t0 = time.monotonic() |
| 85 | + resp = requests.post( |
| 86 | + self.url, |
| 87 | + json=payload, |
| 88 | + headers=headers, |
| 89 | + timeout=self.timeout, |
| 90 | + ) |
| 91 | + elapsed_ms = (time.monotonic() - t0) * 1000 |
| 92 | + resp.raise_for_status() |
| 93 | + data = resp.json() |
| 94 | + |
| 95 | + rankings = data.get("rankings", []) |
| 96 | + results = [] |
| 97 | + for r in rankings: |
| 98 | + idx = r.get("index", 0) |
| 99 | + results.append({ |
| 100 | + "index": idx, |
| 101 | + "logit": r.get("logit", 0.0), |
| 102 | + "text": passages[idx] if idx < len(passages) else "", |
| 103 | + }) |
| 104 | + results.sort(key=lambda x: x["logit"], reverse=True) |
| 105 | + logger.debug( |
| 106 | + "Reranked %d passages in %.0fms (top logit=%.2f)", |
| 107 | + len(passages), elapsed_ms, |
| 108 | + results[0]["logit"] if results else 0.0, |
| 109 | + ) |
| 110 | + return results |
| 111 | + |
| 112 | + except Exception as exc: |
| 113 | + last_exc = exc |
| 114 | + if attempt < self.max_retries: |
| 115 | + delay = min(2 ** attempt, 4) |
| 116 | + logger.warning( |
| 117 | + "Reranker retry %d/%d after %ss: %s", |
| 118 | + attempt + 1, self.max_retries, delay, exc, |
| 119 | + ) |
| 120 | + time.sleep(delay) |
| 121 | + else: |
| 122 | + logger.error("Reranker failed after %d attempts: %s", self.max_retries + 1, exc) |
| 123 | + |
| 124 | + raise RuntimeError(f"Reranker failed: {last_exc}") from last_exc |
| 125 | + |
| 126 | + |
| 127 | +def create_reranker(config: Optional[Dict[str, Any]] = None) -> Optional[NvidiaReranker]: |
| 128 | + """Factory: create a reranker from config, or return None if disabled.""" |
| 129 | + if not config: |
| 130 | + return None |
| 131 | + provider = config.get("provider", "nvidia") |
| 132 | + if provider == "nvidia": |
| 133 | + return NvidiaReranker(config) |
| 134 | + logger.warning("Unknown reranker provider: %s", provider) |
| 135 | + return None |
0 commit comments