Spaces:
Sleeping
Sleeping
Optimize PyTorch threading, run generation in thread, and pre-warm model at startup
Browse files- backend/engines/llm_client.py +7 -4
- backend/main.py +11 -0
backend/engines/llm_client.py
CHANGED
|
@@ -1,6 +1,10 @@
|
|
| 1 |
from typing import Optional
|
| 2 |
import torch
|
| 3 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
_llm_pipeline = None
|
| 6 |
|
|
@@ -34,12 +38,13 @@ class OllamaClient:
|
|
| 34 |
]
|
| 35 |
|
| 36 |
generation_kwargs = {
|
| 37 |
-
"max_new_tokens":
|
| 38 |
"temperature": 0.1,
|
| 39 |
"do_sample": False
|
| 40 |
}
|
| 41 |
|
| 42 |
-
|
|
|
|
| 43 |
result_text = outputs[0]["generated_text"][-1]["content"]
|
| 44 |
|
| 45 |
cleaned_text = result_text.strip()
|
|
@@ -52,5 +57,3 @@ class OllamaClient:
|
|
| 52 |
cleaned_text = "\n".join(lines).strip()
|
| 53 |
|
| 54 |
return cleaned_text
|
| 55 |
-
|
| 56 |
-
|
|
|
|
| 1 |
from typing import Optional
|
| 2 |
import torch
|
| 3 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 4 |
+
import asyncio
|
| 5 |
+
|
| 6 |
+
# Prevent PyTorch from overloading multi-core virtual CPUs which causes thrashing and extreme slowness
|
| 7 |
+
torch.set_num_threads(1)
|
| 8 |
|
| 9 |
_llm_pipeline = None
|
| 10 |
|
|
|
|
| 38 |
]
|
| 39 |
|
| 40 |
generation_kwargs = {
|
| 41 |
+
"max_new_tokens": 384, # Reduced from 512 to significantly speed up inference
|
| 42 |
"temperature": 0.1,
|
| 43 |
"do_sample": False
|
| 44 |
}
|
| 45 |
|
| 46 |
+
# Run CPU-bound text generation in a separate thread so it doesn't block the FastAPI event loop
|
| 47 |
+
outputs = await asyncio.to_thread(pipe, messages, **generation_kwargs)
|
| 48 |
result_text = outputs[0]["generated_text"][-1]["content"]
|
| 49 |
|
| 50 |
cleaned_text = result_text.strip()
|
|
|
|
| 57 |
cleaned_text = "\n".join(lines).strip()
|
| 58 |
|
| 59 |
return cleaned_text
|
|
|
|
|
|
backend/main.py
CHANGED
|
@@ -59,3 +59,14 @@ app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static")
|
|
| 59 |
@app.get("/")
|
| 60 |
def serve_frontend():
|
| 61 |
return FileResponse(str(FRONTEND_DIR / "index.html"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
@app.get("/")
|
| 60 |
def serve_frontend():
|
| 61 |
return FileResponse(str(FRONTEND_DIR / "index.html"))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Pre-warm the LLM referee model at startup so the first request doesn't experience model loading lag
|
| 65 |
+
try:
|
| 66 |
+
print("Pre-warming the LLM referee model...")
|
| 67 |
+
from backend.engines.llm_client import OllamaClient
|
| 68 |
+
OllamaClient()._get_pipeline()
|
| 69 |
+
print("LLM referee model warmed up successfully.")
|
| 70 |
+
except Exception as e:
|
| 71 |
+
print(f"Failed to pre-warm LLM model: {e}")
|
| 72 |
+
|