AI Agent commited on
Commit
a37260b
·
1 Parent(s): b584c76

Fix OOM crash causing missing jobs by limiting PyTorch concurrency

Browse files
Files changed (4) hide show
  1. agents/crew.py +7 -6
  2. agents/embed_llm.py +10 -6
  3. app.py +2 -2
  4. start.sh +6 -0
agents/crew.py CHANGED
@@ -285,12 +285,13 @@ def run_query_crew(query: str, top_k: int = None, max_tokens: int = None, use_ve
285
  if not retrieval_is_empty:
286
  try:
287
  reranker = _get_reranker()
288
-
289
- # Prepare pairs of (query, chunk_text)
290
- pairs = [[query, chunk["text"]] for chunk in unique_chunks]
291
-
292
- # Predict scores using the CrossEncoder
293
- scores = reranker.predict(pairs)
 
294
 
295
  # Assign scores back to the chunks
296
  for i, chunk in enumerate(unique_chunks):
 
285
  if not retrieval_is_empty:
286
  try:
287
  reranker = _get_reranker()
288
+ import threading
289
+ # Lock the PyTorch inference block to prevent OOM
290
+ if not hasattr(_get_reranker, '_lock'):
291
+ _get_reranker._lock = threading.Lock()
292
+ with _get_reranker._lock:
293
+ # Predict scores using the CrossEncoder
294
+ scores = reranker.predict([(query, chunk["text"]) for chunk in unique_chunks])
295
 
296
  # Assign scores back to the chunks
297
  for i, chunk in enumerate(unique_chunks):
agents/embed_llm.py CHANGED
@@ -82,14 +82,18 @@ _embed_dim = _get_dim()
82
  log.info("SentenceTransformer model ready — dim=%d", _embed_dim)
83
 
84
 
 
 
 
85
  def _embed_sentences(sentences: list[str]) -> np.ndarray:
86
  """Embed a list of sentences and return dense vectors as ndarray (N, dim)."""
87
- vecs = _st_model.encode(
88
- sentences,
89
- batch_size=BATCH_SIZE,
90
- show_progress_bar=False,
91
- normalize_embeddings=True,
92
- )
 
93
  return vecs if isinstance(vecs, np.ndarray) else np.array(vecs)
94
 
95
 
 
82
  log.info("SentenceTransformer model ready — dim=%d", _embed_dim)
83
 
84
 
85
+ import threading
86
+ _embed_lock = threading.Lock()
87
+
88
  def _embed_sentences(sentences: list[str]) -> np.ndarray:
89
  """Embed a list of sentences and return dense vectors as ndarray (N, dim)."""
90
+ with _embed_lock:
91
+ vecs = _st_model.encode(
92
+ sentences,
93
+ batch_size=BATCH_SIZE,
94
+ show_progress_bar=False,
95
+ normalize_embeddings=True,
96
+ )
97
  return vecs if isinstance(vecs, np.ndarray) else np.array(vecs)
98
 
99
 
app.py CHANGED
@@ -133,7 +133,7 @@ _session_uploads: dict[str, int] = {}
133
 
134
  # Global thread pool to allow concurrent RAG execution
135
  from concurrent.futures import ThreadPoolExecutor
136
- _query_executor = ThreadPoolExecutor(max_workers=8)
137
 
138
  # Auto-ingest background progress tracker
139
  _auto_ingest_status: dict = {
@@ -889,7 +889,7 @@ def query_stream(job_id):
889
  return
890
  idx += 1
891
 
892
- if job["error"] or job["done"]:
893
  break
894
 
895
  time.sleep(0.5)
 
133
 
134
  # Global thread pool to allow concurrent RAG execution
135
  from concurrent.futures import ThreadPoolExecutor
136
+ _query_executor = ThreadPoolExecutor(max_workers=2)
137
 
138
  # Auto-ingest background progress tracker
139
  _auto_ingest_status: dict = {
 
889
  return
890
  idx += 1
891
 
892
+ if job.get("error") or job.get("done"):
893
  break
894
 
895
  time.sleep(0.5)
start.sh CHANGED
@@ -41,6 +41,12 @@ if [ "$HF_MODE_FLAG" -eq 1 ]; then
41
  export TOP_K_GRAPH=3
42
  export EMBED_FP16=false # CPU only — FP16 unsupported
43
  export TORCH_COMPILE_SKIP=1 # Skip torch.compile() on CPU (no benefit, adds 30s startup)
 
 
 
 
 
 
44
  MODE_LABEL="HuggingFace / CPU"
45
  else
46
  export GEN_MODEL_ID="${GEN_MODEL_ID:-Jackrong/Qwen3.5-2B-Claude-4.6-Opus-Reasoning-Distilled-GGUF}"
 
41
  export TOP_K_GRAPH=3
42
  export EMBED_FP16=false # CPU only — FP16 unsupported
43
  export TORCH_COMPILE_SKIP=1 # Skip torch.compile() on CPU (no benefit, adds 30s startup)
44
+
45
+ # Crucial to prevent CPU thrashing and PyTorch OOM when multiple threads query
46
+ export OMP_NUM_THREADS=2
47
+ export MKL_NUM_THREADS=2
48
+ export OPENBLAS_NUM_THREADS=2
49
+
50
  MODE_LABEL="HuggingFace / CPU"
51
  else
52
  export GEN_MODEL_ID="${GEN_MODEL_ID:-Jackrong/Qwen3.5-2B-Claude-4.6-Opus-Reasoning-Distilled-GGUF}"