fix(8822): the embedding model runs one call at a time, on at most 8 threads
onnxruntime keeps a memory arena per run in flight and never returns it, so overlapping requests grew the app a step at a time and it never came down: measured in the live container, 32 concurrent callers reached 17.3 GB where the same work one call at a time stayed flat at 1.07 GB. Every model call now runs on a single worker thread, and the model loads with a thread pool capped at 8 instead of one thread per host core. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,7 @@ import math
|
||||
import os
|
||||
|
||||
from collections.abc import Sequence
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
|
||||
@@ -60,6 +61,23 @@ _CACHE_DIR = os.environ.get("FASTEMBED_CACHE_DIR", "/data/fastembed-cache")
|
||||
_model = None # lazy singleton; first call downloads model files
|
||||
_model_lock = asyncio.Lock()
|
||||
|
||||
# ONE MODEL CALL AT A TIME, ON A FEW THREADS.
|
||||
#
|
||||
# onnxruntime keeps a memory arena for each run in flight and never hands it
|
||||
# back to the system, so the process keeps the memory of its busiest moment.
|
||||
# With calls running side by side, every burst of overlapping requests grows
|
||||
# the arena a step: 32 concurrent callers took a process past 17 GB, where
|
||||
# the same work done one call at a time stays at about 1 GB. Every model call
|
||||
# therefore runs on this single worker thread, and the others queue for it.
|
||||
#
|
||||
# Queuing costs little: each call already spreads across `_MODEL_THREADS`
|
||||
# cores, so calls run side by side only competed for the same CPUs. The cap
|
||||
# keeps the model from sizing its thread pool to every core of a large shared
|
||||
# host; a query embeds in milliseconds on a few cores, and more threads than
|
||||
# this only add hand-off overhead.
|
||||
_MODEL_THREADS = min(8, len(os.sched_getaffinity(0)))
|
||||
_model_worker = ThreadPoolExecutor(max_workers=1, thread_name_prefix="embed")
|
||||
|
||||
|
||||
async def _get_model():
|
||||
"""Return the singleton fastembed.TextEmbedding instance, loading on first call."""
|
||||
@@ -74,6 +92,7 @@ async def _get_model():
|
||||
TextEmbedding,
|
||||
model_name=_MODEL_NAME,
|
||||
cache_dir=_CACHE_DIR,
|
||||
threads=_MODEL_THREADS,
|
||||
)
|
||||
logger.info("Loaded fastembed model %s (cache: %s)", _MODEL_NAME, _CACHE_DIR)
|
||||
return _model
|
||||
@@ -150,9 +169,12 @@ async def get_embeddings(texts: list[str]) -> list[list[float]]:
|
||||
calls. Raises like get_embedding; callers catch and degrade.
|
||||
"""
|
||||
embedder = await _get_model()
|
||||
# embed() is synchronous CPU work; offload so we don't block the event loop.
|
||||
vecs = await asyncio.to_thread(lambda: list(embedder.embed(texts)))
|
||||
return [v.tolist() for v in vecs]
|
||||
# embed() is synchronous CPU work: it runs off the event loop, on the one
|
||||
# model worker, so calls never overlap (see `_model_worker`).
|
||||
vecs = await asyncio.get_running_loop().run_in_executor(
|
||||
_model_worker, lambda: [v.tolist() for v in embedder.embed(texts)],
|
||||
)
|
||||
return vecs
|
||||
|
||||
|
||||
def _cosine_similarity(a: list[float], b: list[float]) -> float:
|
||||
|
||||
Reference in New Issue
Block a user