Spaces:
Running

Hamdy005 commited on
Commit
ba5fa56
·
1 Parent(s): 7225216

feat: add asynchronous batch reranking infrastructure and startup warmup

Browse files
Files changed (6) hide show
  1. main.py +12 -2
  2. rag/batch_workers.py +220 -17
  3. rag/constants.py +2 -0
  4. rag/rag.py +33 -5
  5. rag/reranker.py +41 -17
  6. rag/schemas.py +12 -1
main.py CHANGED
@@ -43,12 +43,22 @@ async def lifespan(app: FastAPI):
43
 
44
 
45
  try:
46
- from src.rag.rag import get_embedder
47
  get_embedder()
48
- logger.info("Embedder loaded successfully.")
 
49
  except Exception as e:
50
  logger.warning(f"Embedder failed to load: {e}")
51
 
 
 
 
 
 
 
 
 
 
52
  # Eagerly load ASR models so warmup runs at startup, not on first request
53
  try:
54
  from src.asr.models import get_audio_model_en
 
43
 
44
 
45
  try:
46
+ from src.rag.rag import get_embedder, warmup_embedder
47
  get_embedder()
48
+ warmup_embedder()
49
+ logger.info("Embedder loaded and warmed up successfully.")
50
  except Exception as e:
51
  logger.warning(f"Embedder failed to load: {e}")
52
 
53
+ # Eagerly load and warm up reranker model at startup
54
+ try:
55
+ from src.rag.reranker import get_reranker, warmup_reranker
56
+ get_reranker()
57
+ warmup_reranker()
58
+ logger.info("Reranker loaded and warmed up successfully at startup.")
59
+ except Exception as e:
60
+ logger.warning(f"Reranker failed to load or warmup at startup: {e}")
61
+
62
  # Eagerly load ASR models so warmup runs at startup, not on first request
63
  try:
64
  from src.asr.models import get_audio_model_en
rag/batch_workers.py CHANGED
@@ -1,22 +1,29 @@
1
  """
2
- Embedding Batch Workers — Async batching infrastructure for embedding inference.
3
 
4
  Architecture:
5
- - Single asyncio.Queue for all embedding jobs.
6
- - Dedicated async worker coroutines drain the queue in micro-batches.
7
- - Workers offload heavy inference to a thread via run_in_executor.
8
  - A shared in-memory job_store dict tracks job status + results.
9
- - Warmup loop periodically does a dummy forward pass to keep OpenMP threads alive.
 
10
  """
11
 
12
  import asyncio
13
  import time
14
  import uuid
15
  from loguru import logger
16
- from typing import Any
17
 
18
- from .constants import BATCH_MAX_SIZE, BATCH_WINDOW_S, WARMUP_INTERVAL_S
19
- from .schemas import EmbeddingJob
 
 
 
 
 
 
20
 
21
 
22
  # ═══════════════════════ Job Store ════════════════════════
@@ -26,7 +33,7 @@ job_store: dict[str, dict[str, Any]] = {}
26
  {
27
  "<job_id>": {
28
  "status": "pending" | "processing" | "done" | "error",
29
- "result": <list[list[float]] for EmbeddingJob> | None,
30
  "error": <str> | None,
31
  }
32
  }
@@ -58,9 +65,11 @@ def is_request_in_flight() -> bool:
58
  return _request_in_flight_count > 0
59
 
60
 
61
- # ═══════════════════════ Queue ════════════════════════
62
 
63
  embedding_queue: asyncio.Queue[EmbeddingJob] = asyncio.Queue()
 
 
64
 
65
 
66
  # ═══════════════════════ Workers ════════════════════════
@@ -148,18 +157,116 @@ async def embedding_worker():
148
  set_request_in_flight(False)
149
 
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  # ═══════════════════════ Warmup Loop ════════════════════════
153
 
154
 
155
  async def _warmup_loop():
156
  """
157
- Periodically does a dummy forward pass to prevent OpenMP/MKL thread pool
158
- spin-down during idle periods.
159
 
160
  Skipped entirely if a real request is in flight.
161
  """
162
  from src.rag.rag import warmup_embedder
 
163
 
164
  loop = asyncio.get_event_loop()
165
 
@@ -170,11 +277,12 @@ async def _warmup_loop():
170
  t0 = time.monotonic()
171
  try:
172
  await loop.run_in_executor(None, warmup_embedder)
 
173
  except Exception as e:
174
  logger.warning(f"Warmup cycle error (non-fatal): {e}")
175
  continue
176
  elapsed_ms = (time.monotonic() - t0) * 1000
177
- logger.info(f"Warmup cycle done ({elapsed_ms:.0f}ms)")
178
 
179
 
180
  # ═══════════════════════ Startup ════════════════════════
@@ -187,15 +295,110 @@ def start_workers():
187
  Launch all async worker coroutines. Call once during app startup.
188
 
189
  - 1 embedding worker (batched SentenceTransformer inference)
190
- - 1 warmup loop (keeps OpenMP threads alive)
 
191
  """
192
- global _workers_started
193
  if _workers_started:
194
  return
195
  _workers_started = True
196
 
197
- # Use only 1 worker to save RAM on this environment
 
 
 
 
 
198
  asyncio.create_task(embedding_worker(), name="embedding_worker_0")
 
199
  asyncio.create_task(_warmup_loop(), name="warmup_loop")
200
 
201
- logger.info("Batch workers started (embedding worker + warmup loop)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ Batch Workers — Async batching infrastructure for embedding and reranking inference.
3
 
4
  Architecture:
5
+ - Single asyncio.Queue for embedding jobs and reranking jobs.
6
+ - Dedicated async worker coroutines drain queues in micro-batches.
7
+ - Workers offload heavy inference to threads via run_in_executor.
8
  - A shared in-memory job_store dict tracks job status + results.
9
+ - Warmup loop periodically does a dummy forward pass for both embedder
10
+ and reranker to keep PyTorch/OpenMP threads alive during idle periods.
11
  """
12
 
13
  import asyncio
14
  import time
15
  import uuid
16
  from loguru import logger
17
+ from typing import Any, Optional
18
 
19
+ from .constants import (
20
+ BATCH_MAX_SIZE,
21
+ BATCH_WINDOW_S,
22
+ WARMUP_INTERVAL_S,
23
+ RERANK_BATCH_MAX_SIZE,
24
+ RERANK_BATCH_WINDOW_S,
25
+ )
26
+ from .schemas import EmbeddingJob, RerankJob
27
 
28
 
29
  # ═══════════════════════ Job Store ════════════════════════
 
33
  {
34
  "<job_id>": {
35
  "status": "pending" | "processing" | "done" | "error",
36
+ "result": <list[list[float]] for EmbeddingJob | list[dict] for RerankJob> | None,
37
  "error": <str> | None,
38
  }
39
  }
 
65
  return _request_in_flight_count > 0
66
 
67
 
68
+ # ═══════════════════════ Queues & Loop ════════════════════════
69
 
70
  embedding_queue: asyncio.Queue[EmbeddingJob] = asyncio.Queue()
71
+ rerank_queue: asyncio.Queue[RerankJob] = asyncio.Queue()
72
+ _main_loop: Optional[asyncio.AbstractEventLoop] = None
73
 
74
 
75
  # ═══════════════════════ Workers ════════════════════════
 
157
  set_request_in_flight(False)
158
 
159
 
160
+ async def rerank_worker():
161
+ """
162
+ Drains up to {RERANK_BATCH_MAX_SIZE} rerank jobs every {RERANK_BATCH_WINDOW_S * 1000:.0f}ms.
163
+
164
+ Batch reranking forward pass:
165
+ 1. Collect (query, doc_text) pairs across all jobs in the micro-batch.
166
+ 2. Call _score_pairs_batch(all_pairs) in thread pool.
167
+ 3. Distribute scores back to jobs, add 'rerank_score', sort descending, slice top_k.
168
+ 4. Results are written into job_store and each job's done Event is set.
169
+ """
170
+ from src.rag.reranker import _score_pairs_batch
171
+
172
+ loop = asyncio.get_event_loop()
173
+
174
+ while True:
175
+ first_job: RerankJob = await rerank_queue.get()
176
+ batch: list[RerankJob] = [first_job]
177
+
178
+ deadline = loop.time() + RERANK_BATCH_WINDOW_S
179
+ while len(batch) < RERANK_BATCH_MAX_SIZE:
180
+ remaining = deadline - loop.time()
181
+ if remaining <= 0:
182
+ break
183
+ try:
184
+ job = await asyncio.wait_for(rerank_queue.get(), timeout=remaining)
185
+ batch.append(job)
186
+ except asyncio.TimeoutError:
187
+ break
188
+
189
+ try:
190
+ set_request_in_flight(True)
191
+
192
+ all_pairs: list[list[str]] = []
193
+ job_pair_counts: list[int] = []
194
+
195
+ for job in batch:
196
+ cnt = 0
197
+ for rec in job.records:
198
+ text = str(rec.get(job.content_key, ""))
199
+ all_pairs.append([job.query, text])
200
+ cnt += 1
201
+ job_pair_counts.append(cnt)
202
+
203
+ if all_pairs:
204
+ all_scores = await loop.run_in_executor(
205
+ None, _score_pairs_batch, all_pairs
206
+ )
207
+ else:
208
+ all_scores = []
209
+
210
+ idx = 0
211
+ for i, job in enumerate(batch):
212
+ n = job_pair_counts[i]
213
+ job_scores = all_scores[idx : idx + n]
214
+ idx += n
215
+
216
+ scored_records: list[tuple[float, dict[str, Any]]] = []
217
+ for s, rec in zip(job_scores, job.records):
218
+ r_copy = dict(rec)
219
+ r_copy["rerank_score"] = float(s)
220
+ scored_records.append((float(s), r_copy))
221
+
222
+ scored_records.sort(key=lambda x: x[0], reverse=True)
223
+ top_records = [r for _, r in scored_records[: job.top_k]]
224
+
225
+ if job.job_id not in job_store:
226
+ job_store[job.job_id] = {"status": "pending", "result": None, "error": None}
227
+
228
+ job_store[job.job_id].update({
229
+ "status": "done",
230
+ "result": top_records,
231
+ })
232
+ job.done.set()
233
+
234
+ except Exception as e:
235
+ logger.error(f"Reranking batch failed: {e}", exc_info=True)
236
+ for job in batch:
237
+ fallback_records = []
238
+ for r in job.records[: job.top_k]:
239
+ r_copy = dict(r)
240
+ if "rerank_score" not in r_copy:
241
+ r_copy["rerank_score"] = float(r_copy.get("similarity", 0.0))
242
+ fallback_records.append(r_copy)
243
+
244
+ if job.job_id not in job_store:
245
+ job_store[job.job_id] = {"status": "error", "result": fallback_records, "error": str(e)}
246
+ else:
247
+ job_store[job.job_id].update({
248
+ "status": "error",
249
+ "result": fallback_records,
250
+ "error": str(e),
251
+ })
252
+ if not job.done.is_set():
253
+ job.done.set()
254
+ finally:
255
+ set_request_in_flight(False)
256
+
257
 
258
  # ═══════════════════════ Warmup Loop ════════════════════════
259
 
260
 
261
  async def _warmup_loop():
262
  """
263
+ Periodically does a dummy forward pass for both embedder and reranker models
264
+ to prevent OpenMP/MKL thread pool spin-down during idle periods.
265
 
266
  Skipped entirely if a real request is in flight.
267
  """
268
  from src.rag.rag import warmup_embedder
269
+ from src.rag.reranker import warmup_reranker
270
 
271
  loop = asyncio.get_event_loop()
272
 
 
277
  t0 = time.monotonic()
278
  try:
279
  await loop.run_in_executor(None, warmup_embedder)
280
+ await loop.run_in_executor(None, warmup_reranker)
281
  except Exception as e:
282
  logger.warning(f"Warmup cycle error (non-fatal): {e}")
283
  continue
284
  elapsed_ms = (time.monotonic() - t0) * 1000
285
+ logger.info(f"Warmup cycle done (embedder + reranker) ({elapsed_ms:.0f}ms)")
286
 
287
 
288
  # ═══════════════════════ Startup ════════════════════════
 
295
  Launch all async worker coroutines. Call once during app startup.
296
 
297
  - 1 embedding worker (batched SentenceTransformer inference)
298
+ - 1 reranker worker (batched Jina cross-encoder inference)
299
+ - 1 warmup loop (keeps OpenMP threads alive for embedder and reranker)
300
  """
301
+ global _workers_started, _main_loop
302
  if _workers_started:
303
  return
304
  _workers_started = True
305
 
306
+ try:
307
+ _main_loop = asyncio.get_running_loop()
308
+ except RuntimeError:
309
+ _main_loop = asyncio.get_event_loop()
310
+
311
+ # Launch worker tasks on the running event loop
312
  asyncio.create_task(embedding_worker(), name="embedding_worker_0")
313
+ asyncio.create_task(rerank_worker(), name="rerank_worker_0")
314
  asyncio.create_task(_warmup_loop(), name="warmup_loop")
315
 
316
+ logger.info("Batch workers started (embedding worker + rerank worker + warmup loop)")
317
+
318
+
319
+ # ═══════════════════════ Submission Helpers ════════════════════════
320
+
321
+
322
+ async def rerank_async(
323
+ query: str,
324
+ records: list[dict[str, Any]],
325
+ top_k: int,
326
+ content_key: str = "content",
327
+ timeout: float = 30.0,
328
+ ) -> list[dict[str, Any]]:
329
+ """
330
+ Async interface to route reranking through the batch worker queue.
331
+ Falls back to synchronous rerank_dicts if workers are not started or on timeout/failure.
332
+ """
333
+ from src.rag.reranker import rerank_dicts
334
+
335
+ if not records:
336
+ return []
337
+ if len(records) <= 1 or not _workers_started:
338
+ return rerank_dicts(query, records, top_k=top_k, content_key=content_key)
339
+
340
+ job_id = str(uuid.uuid4())
341
+ job = RerankJob(
342
+ job_id=job_id,
343
+ query=query,
344
+ records=records,
345
+ top_k=top_k,
346
+ content_key=content_key,
347
+ )
348
+ job_store[job_id] = {"status": "pending", "result": None, "error": None}
349
+ await rerank_queue.put(job)
350
+
351
+ try:
352
+ await asyncio.wait_for(job.done.wait(), timeout=timeout)
353
+ except asyncio.TimeoutError:
354
+ job_store.pop(job_id, None)
355
+ logger.warning("rerank_async timed out waiting for batch worker. Falling back to direct rerank_dicts.")
356
+ return rerank_dicts(query, records, top_k=top_k, content_key=content_key)
357
+
358
+ entry = job_store.pop(job_id, None)
359
+ if entry and entry.get("result") is not None:
360
+ return entry["result"]
361
+ return rerank_dicts(query, records, top_k=top_k, content_key=content_key)
362
+
363
+
364
+ def rerank_batch(
365
+ query: str,
366
+ records: list[dict[str, Any]],
367
+ top_k: int,
368
+ content_key: str = "content",
369
+ timeout: float = 30.0,
370
+ ) -> list[dict[str, Any]]:
371
+ """
372
+ Synchronous interface for batched reranking.
373
+ - If called from a worker thread while the main event loop is running, dispatches
374
+ to rerank_async via asyncio.run_coroutine_threadsafe.
375
+ - If called from the main thread event loop or if workers are not started,
376
+ safely calls rerank_dicts directly without blocking the event loop or hanging.
377
+ """
378
+ from src.rag.reranker import rerank_dicts
379
+
380
+ if not records:
381
+ return []
382
+ if len(records) <= 1 or not _workers_started or _main_loop is None or not _main_loop.is_running():
383
+ return rerank_dicts(query, records, top_k=top_k, content_key=content_key)
384
+
385
+ try:
386
+ try:
387
+ current_loop = asyncio.get_running_loop()
388
+ except RuntimeError:
389
+ current_loop = None
390
+
391
+ if current_loop is _main_loop:
392
+ # Running on main thread event loop: avoid blocking wait, use direct rerank_dicts
393
+ return rerank_dicts(query, records, top_k=top_k, content_key=content_key)
394
+
395
+ # Running in a worker thread: dispatch to main event loop queue
396
+ future = asyncio.run_coroutine_threadsafe(
397
+ rerank_async(query, records, top_k=top_k, content_key=content_key, timeout=timeout),
398
+ _main_loop,
399
+ )
400
+ return future.result(timeout=timeout)
401
+ except Exception as e:
402
+ logger.warning(f"rerank_batch dispatch failed ({e}); falling back to direct rerank_dicts.")
403
+ return rerank_dicts(query, records, top_k=top_k, content_key=content_key)
404
+
rag/constants.py CHANGED
@@ -13,6 +13,8 @@ RERANKER_MAX_LENGTH = 1024
13
  RERANKER_OVER_RETRIEVAL_FACTOR = 3 # Retrieve TOP_K * 3 candidate chunks before reranking
14
  SIMILARITY_MATCH_THRESHOLD = 0.35 # Vector cosine similarity cutoff for RPC match_material_chunks
15
  ENABLE_RERANKER = True # Cross-encoder reranker runs on ensemble results
 
 
16
 
17
  # ── Hybrid Ensemble Retrieval Configuration (Vector + BM25) ──
18
  VECTOR_SEARCH_WEIGHT = 0.60 # Weight (60%) for semantic vector search in ensemble
 
13
  RERANKER_OVER_RETRIEVAL_FACTOR = 3 # Retrieve TOP_K * 3 candidate chunks before reranking
14
  SIMILARITY_MATCH_THRESHOLD = 0.35 # Vector cosine similarity cutoff for RPC match_material_chunks
15
  ENABLE_RERANKER = True # Cross-encoder reranker runs on ensemble results
16
+ RERANK_BATCH_MAX_SIZE = 8 # Max concurrent reranking jobs batched together
17
+ RERANK_BATCH_WINDOW_S = 0.05 # Micro-batch collection window (50ms)
18
 
19
  # ── Hybrid Ensemble Retrieval Configuration (Vector + BM25) ──
20
  VECTOR_SEARCH_WEIGHT = 0.60 # Weight (60%) for semantic vector search in ensemble
rag/rag.py CHANGED
@@ -47,6 +47,7 @@ from .constants import (
47
  )
48
  from .ensemble import get_ensemble_retriever
49
  from .reranker import rerank_dicts
 
50
  from .schemas import EmbeddingJob
51
 
52
 
@@ -154,8 +155,8 @@ def similarity_search(query: str, material_id: str, k: int = 5) -> list[dict]:
154
 
155
  1. Ensemble Retrieval: invokes LangChain's EnsembleRetriever (Vector 60% + BM25 40%)
156
  to retrieve and fuse candidate documents.
157
- 2. Cross-Encoder Reranking: scores the candidate chunks against the query using
158
- the Jina reranker model and returns the final top_k chunks.
159
  """
160
  if not query or not material_id:
161
  return []
@@ -178,8 +179,35 @@ def similarity_search(query: str, material_id: str, k: int = 5) -> list[dict]:
178
  for doc in docs[:fetch_k]
179
  ]
180
 
181
- # 2. Reranker call in rag.py: scores the (k * 3) candidates and returns top_k (e.g. 4)
182
- return rerank_dicts(query=query, records=candidates, top_k=k)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
 
185
  # ── LLM ────────────────────────────────────────────────
@@ -882,7 +910,7 @@ async def rag_answer_stream(
882
 
883
  if not is_topic:
884
  # --- Material-based query (PDF/URL): hybrid ensemble search (60% vector + 40% BM25) ---
885
- results = await asyncio.to_thread(similarity_search, query, material_id, k=TOP_K_CHUNKS)
886
  if results:
887
  has_chunks = True
888
  retrieval_chunks = [r["content"] for r in results]
 
47
  )
48
  from .ensemble import get_ensemble_retriever
49
  from .reranker import rerank_dicts
50
+ from .batch_workers import rerank_batch, rerank_async
51
  from .schemas import EmbeddingJob
52
 
53
 
 
155
 
156
  1. Ensemble Retrieval: invokes LangChain's EnsembleRetriever (Vector 60% + BM25 40%)
157
  to retrieve and fuse candidate documents.
158
+ 2. Cross-Encoder Reranking: scores candidate chunks against the query using
159
+ the batched Jina reranker worker (or direct reranker fallback) and returns top_k chunks.
160
  """
161
  if not query or not material_id:
162
  return []
 
179
  for doc in docs[:fetch_k]
180
  ]
181
 
182
+ # 2. Reranker call in rag.py: batch worker scores candidates across concurrent requests
183
+ return rerank_batch(query=query, records=candidates, top_k=k)
184
+
185
+
186
+ async def similarity_search_async(query: str, material_id: str, k: int = 5) -> list[dict]:
187
+ """Retrieve top_k chunks asynchronously using Ensemble Retrieval and batch reranking."""
188
+ if not query or not material_id:
189
+ return []
190
+
191
+ fetch_k = k * RERANKER_OVER_RETRIEVAL_FACTOR
192
+
193
+ # 1. Ensemble retrieval call in rag.py (retrieves from Vector 60% and BM25 40%)
194
+ ensemble_retriever = get_ensemble_retriever(material_id=material_id, k=k)
195
+ docs = await ensemble_retriever.ainvoke(query)
196
+ if not docs:
197
+ return []
198
+
199
+ # Take top (k * 3) ensemble-ranked candidate chunks to pass to reranking
200
+ candidates = [
201
+ {
202
+ "content": doc.page_content,
203
+ "chunk_id": doc.metadata.get("chunk_id"),
204
+ "similarity": float(doc.metadata.get("similarity", 0.0)),
205
+ }
206
+ for doc in docs[:fetch_k]
207
+ ]
208
+
209
+ # 2. Async batch reranker call in rag.py
210
+ return await rerank_async(query=query, records=candidates, top_k=k)
211
 
212
 
213
  # ── LLM ────────────────────────────────────────────────
 
910
 
911
  if not is_topic:
912
  # --- Material-based query (PDF/URL): hybrid ensemble search (60% vector + 40% BM25) ---
913
+ results = await similarity_search_async(query, material_id, k=TOP_K_CHUNKS)
914
  if results:
915
  has_chunks = True
916
  retrieval_chunks = [r["content"] for r in results]
rag/reranker.py CHANGED
@@ -30,13 +30,13 @@ _RERANKER_MODEL = RERANKER_MODEL
30
 
31
 
32
  @lru_cache(maxsize=1)
33
- def _get_reranker():
34
  """Lazily load and cache the Jina reranker model on first call.
35
 
36
  Uses AutoModelForSequenceClassification with trust_remote_code=True,
37
  as required by the Jina v2 reranker architecture.
38
  Runs on CPU; the model is 278 M params but inference on short chunks
39
- is fast enough for synchronous per-turn use.
40
  """
41
  from transformers import AutoModelForSequenceClassification
42
  import torch
@@ -52,6 +52,44 @@ def _get_reranker():
52
  return model
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def _compute_scores(query: str, texts: list[str]) -> Optional[list[float]]:
56
  """Compute relevance scores for (query, text) pairs using the reranker model.
57
 
@@ -61,22 +99,8 @@ def _compute_scores(query: str, texts: list[str]) -> Optional[list[float]]:
61
  return []
62
 
63
  try:
64
- import torch
65
-
66
- model = _get_reranker()
67
  pairs = [[query, text] for text in texts]
68
-
69
- with torch.no_grad():
70
- scores = model.compute_score(pairs, max_length=RERANKER_MAX_LENGTH)
71
-
72
- # Handle tensor, numpy array, list, or scalar
73
- if hasattr(scores, "tolist"):
74
- scores = scores.tolist()
75
- elif isinstance(scores, (float, int)):
76
- scores = [float(scores)]
77
-
78
- return [float(s) for s in scores]
79
-
80
  except Exception as exc:
81
  logger.warning(
82
  f"Reranker inference failed ({type(exc).__name__}: {exc}). "
 
30
 
31
 
32
  @lru_cache(maxsize=1)
33
+ def get_reranker():
34
  """Lazily load and cache the Jina reranker model on first call.
35
 
36
  Uses AutoModelForSequenceClassification with trust_remote_code=True,
37
  as required by the Jina v2 reranker architecture.
38
  Runs on CPU; the model is 278 M params but inference on short chunks
39
+ is fast enough for per-turn use.
40
  """
41
  from transformers import AutoModelForSequenceClassification
42
  import torch
 
52
  return model
53
 
54
 
55
+ _get_reranker = get_reranker
56
+
57
+
58
+ def warmup_reranker():
59
+ """Warmup forward pass for Jina reranker to prime PyTorch/OpenMP thread pools."""
60
+ try:
61
+ model = get_reranker()
62
+ import torch
63
+
64
+ with torch.no_grad():
65
+ model.compute_score([["warmup query", "warmup document"]], max_length=64)
66
+ logger.info("Reranker warmup completed successfully.")
67
+ except Exception as exc:
68
+ logger.warning(f"Reranker warmup failed (non-fatal): {exc}")
69
+
70
+
71
+ def _score_pairs_batch(pairs: list[list[str]]) -> list[float]:
72
+ """Batch score arbitrary (query, text) pairs in a single forward pass."""
73
+ if not pairs:
74
+ return []
75
+
76
+ import torch
77
+
78
+ model = get_reranker()
79
+ with torch.no_grad():
80
+ scores = model.compute_score(pairs, max_length=RERANKER_MAX_LENGTH)
81
+
82
+ if hasattr(scores, "tolist"):
83
+ scores = scores.tolist()
84
+ elif isinstance(scores, (float, int)):
85
+ scores = [float(scores)]
86
+
87
+ return [float(s) for s in scores]
88
+
89
+
90
+ score_pairs_batch = _score_pairs_batch
91
+
92
+
93
  def _compute_scores(query: str, texts: list[str]) -> Optional[list[float]]:
94
  """Compute relevance scores for (query, text) pairs using the reranker model.
95
 
 
99
  return []
100
 
101
  try:
 
 
 
102
  pairs = [[query, text] for text in texts]
103
+ return _score_pairs_batch(pairs)
 
 
 
 
 
 
 
 
 
 
 
104
  except Exception as exc:
105
  logger.warning(
106
  f"Reranker inference failed ({type(exc).__name__}: {exc}). "
rag/schemas.py CHANGED
@@ -8,7 +8,7 @@ class SearchInput(BaseModel):
8
  query: str = Field(description="The search query or topic to look up")
9
 
10
 
11
- # Batch worker job dataclass
12
  @dataclass
13
  class EmbeddingJob:
14
  """Batch embedding of multiple texts (for store_embeddings)."""
@@ -17,6 +17,17 @@ class EmbeddingJob:
17
  done: asyncio.Event = field(default_factory=asyncio.Event)
18
 
19
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
 
22
  # Tutor query and response schemas
 
8
  query: str = Field(description="The search query or topic to look up")
9
 
10
 
11
+ # Batch worker job dataclasses
12
  @dataclass
13
  class EmbeddingJob:
14
  """Batch embedding of multiple texts (for store_embeddings)."""
 
17
  done: asyncio.Event = field(default_factory=asyncio.Event)
18
 
19
 
20
+ @dataclass
21
+ class RerankJob:
22
+ """Batch reranking of query-candidate pairs across concurrent requests."""
23
+ job_id: str
24
+ query: str
25
+ records: list[dict[str, Any]]
26
+ top_k: int
27
+ content_key: str = "content"
28
+ done: asyncio.Event = field(default_factory=asyncio.Event)
29
+
30
+
31
 
32
 
33
  # Tutor query and response schemas