Spaces:
Runtime error
Runtime error
Fix CPU inference and surface model errors
Browse files
app.py
CHANGED
|
@@ -10,12 +10,17 @@ import gradio as gr
|
|
| 10 |
from fastapi import FastAPI, Request
|
| 11 |
from fastapi.responses import StreamingResponse, JSONResponse
|
| 12 |
from huggingface_hub import hf_hub_download
|
| 13 |
-
import spaces
|
| 14 |
from llama_cpp import Llama
|
| 15 |
|
| 16 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 17 |
MODEL_PATH = "/tmp/lumen-dpo.gguf"
|
| 18 |
MEMORY_FILE = "/tmp/memories.json"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
SYSTEM_PROMPT = (
|
| 21 |
"""
|
|
@@ -27,6 +32,7 @@ SYSTEM_PROMPT = (
|
|
| 27 |
)
|
| 28 |
|
| 29 |
llm = None
|
|
|
|
| 30 |
infer_lock = threading.Lock()
|
| 31 |
|
| 32 |
|
|
@@ -93,24 +99,30 @@ def memories_display_text():
|
|
| 93 |
# ββ Model loading βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 94 |
|
| 95 |
def _load_model():
|
| 96 |
-
global llm
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
threading.Thread(target=_load_model, daemon=True).start()
|
| 116 |
|
|
@@ -123,10 +135,14 @@ def user_submit(message, history):
|
|
| 123 |
return "", history + [{"role": "user", "content": message}]
|
| 124 |
|
| 125 |
|
| 126 |
-
@spaces.GPU
|
| 127 |
def bot_respond(history, temperature, max_tokens):
|
| 128 |
if llm is None:
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
return
|
| 131 |
|
| 132 |
messages = [{"role": "system", "content": build_system_prompt()}]
|
|
@@ -140,22 +156,28 @@ def bot_respond(history, temperature, max_tokens):
|
|
| 140 |
|
| 141 |
response = ""
|
| 142 |
working_history = history + [{"role": "assistant", "content": ""}]
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
|
| 156 |
def model_status():
|
| 157 |
if llm is not None:
|
| 158 |
return "<p class='status ready'>β Model ready</p>"
|
|
|
|
|
|
|
| 159 |
return "<p class='status loading'>β Loading modelβ¦ (first boot takes a few minutes)</p>"
|
| 160 |
|
| 161 |
|
|
@@ -216,6 +238,7 @@ footer { display: none !important; }
|
|
| 216 |
.status { margin: 0 0 10px; font-size: 0.8em; font-weight: 500; }
|
| 217 |
.status.ready { color: #6aa87a; }
|
| 218 |
.status.loading { color: #c9994a; }
|
|
|
|
| 219 |
.chatbot-wrap .message.user { background: #2a1e14 !important; border: 1px solid #3a2c1e !important; }
|
| 220 |
.chatbot-wrap .message.bot { background: #1c1510 !important; border: 1px solid #2e2218 !important; }
|
| 221 |
.chatbot-wrap .message { border-radius: 8px !important; }
|
|
@@ -344,7 +367,8 @@ def api_delete_memory(index: int):
|
|
| 344 |
@demo.app.post("/v1/chat/completions")
|
| 345 |
async def chat_completions(request: Request):
|
| 346 |
if llm is None:
|
| 347 |
-
|
|
|
|
| 348 |
|
| 349 |
body = await request.json()
|
| 350 |
messages = body.get("messages", [])
|
|
@@ -362,10 +386,9 @@ async def chat_completions(request: Request):
|
|
| 362 |
async def event_stream():
|
| 363 |
resp_id = "chatcmpl-" + uuid.uuid4().hex
|
| 364 |
created = int(time.time())
|
| 365 |
-
q = queue_mod.Queue(
|
| 366 |
DONE = object()
|
| 367 |
|
| 368 |
-
@spaces.GPU
|
| 369 |
def produce():
|
| 370 |
try:
|
| 371 |
with infer_lock:
|
|
@@ -403,7 +426,6 @@ async def chat_completions(request: Request):
|
|
| 403 |
|
| 404 |
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
| 405 |
|
| 406 |
-
@spaces.GPU
|
| 407 |
def generate():
|
| 408 |
with infer_lock:
|
| 409 |
return llm.create_chat_completion(
|
|
@@ -413,8 +435,14 @@ async def chat_completions(request: Request):
|
|
| 413 |
stream = False,
|
| 414 |
)
|
| 415 |
|
| 416 |
-
|
| 417 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
|
| 420 |
# ββ Launch βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 10 |
from fastapi import FastAPI, Request
|
| 11 |
from fastapi.responses import StreamingResponse, JSONResponse
|
| 12 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 13 |
from llama_cpp import Llama
|
| 14 |
|
| 15 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 16 |
MODEL_PATH = "/tmp/lumen-dpo.gguf"
|
| 17 |
MEMORY_FILE = "/tmp/memories.json"
|
| 18 |
+
MAX_CPU_THREADS = 8
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
CPU_THREADS = max(1, min(MAX_CPU_THREADS, len(os.sched_getaffinity(0))))
|
| 22 |
+
except (AttributeError, OSError):
|
| 23 |
+
CPU_THREADS = max(1, min(MAX_CPU_THREADS, os.cpu_count() or 2))
|
| 24 |
|
| 25 |
SYSTEM_PROMPT = (
|
| 26 |
"""
|
|
|
|
| 32 |
)
|
| 33 |
|
| 34 |
llm = None
|
| 35 |
+
model_error = None
|
| 36 |
infer_lock = threading.Lock()
|
| 37 |
|
| 38 |
|
|
|
|
| 99 |
# ββ Model loading βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 100 |
|
| 101 |
def _load_model():
|
| 102 |
+
global llm, model_error
|
| 103 |
+
try:
|
| 104 |
+
if not os.path.exists(MODEL_PATH):
|
| 105 |
+
print("Downloading Lumen DPO model\u2026", flush=True)
|
| 106 |
+
hf_hub_download(
|
| 107 |
+
repo_id = "RavikxxBGamin/Lumen",
|
| 108 |
+
filename = "lumen-dpo.gguf",
|
| 109 |
+
token = HF_TOKEN,
|
| 110 |
+
local_dir = "/tmp",
|
| 111 |
+
)
|
| 112 |
|
| 113 |
+
print(f"Loading model with {CPU_THREADS} CPU thread(s)\u2026", flush=True)
|
| 114 |
+
llm = Llama(
|
| 115 |
+
model_path = MODEL_PATH,
|
| 116 |
+
n_ctx = 8192,
|
| 117 |
+
n_threads = CPU_THREADS,
|
| 118 |
+
verbose = False,
|
| 119 |
+
)
|
| 120 |
+
model_error = None
|
| 121 |
+
print("Model ready.", flush=True)
|
| 122 |
+
except Exception as exc:
|
| 123 |
+
llm = None
|
| 124 |
+
model_error = f"{type(exc).__name__}: {exc}"
|
| 125 |
+
print(f"Model load failed: {model_error}", flush=True)
|
| 126 |
|
| 127 |
threading.Thread(target=_load_model, daemon=True).start()
|
| 128 |
|
|
|
|
| 135 |
return "", history + [{"role": "user", "content": message}]
|
| 136 |
|
| 137 |
|
|
|
|
| 138 |
def bot_respond(history, temperature, max_tokens):
|
| 139 |
if llm is None:
|
| 140 |
+
message = (
|
| 141 |
+
f"Model failed to load: {model_error}"
|
| 142 |
+
if model_error
|
| 143 |
+
else "Model is still loading β please wait a moment and try again."
|
| 144 |
+
)
|
| 145 |
+
yield history + [{"role": "assistant", "content": message}]
|
| 146 |
return
|
| 147 |
|
| 148 |
messages = [{"role": "system", "content": build_system_prompt()}]
|
|
|
|
| 156 |
|
| 157 |
response = ""
|
| 158 |
working_history = history + [{"role": "assistant", "content": ""}]
|
| 159 |
+
try:
|
| 160 |
+
with infer_lock:
|
| 161 |
+
for chunk in llm.create_chat_completion(
|
| 162 |
+
messages = messages,
|
| 163 |
+
max_tokens = int(max_tokens),
|
| 164 |
+
temperature = float(temperature),
|
| 165 |
+
stream = True,
|
| 166 |
+
):
|
| 167 |
+
delta = chunk["choices"][0]["delta"].get("content", "")
|
| 168 |
+
response += delta
|
| 169 |
+
working_history[-1]["content"] = response
|
| 170 |
+
yield working_history
|
| 171 |
+
except Exception as exc:
|
| 172 |
+
working_history[-1]["content"] = f"Generation failed: {type(exc).__name__}: {exc}"
|
| 173 |
+
yield working_history
|
| 174 |
|
| 175 |
|
| 176 |
def model_status():
|
| 177 |
if llm is not None:
|
| 178 |
return "<p class='status ready'>β Model ready</p>"
|
| 179 |
+
if model_error:
|
| 180 |
+
return f"<p class='status error'>β Model failed to load: {model_error}</p>"
|
| 181 |
return "<p class='status loading'>β Loading modelβ¦ (first boot takes a few minutes)</p>"
|
| 182 |
|
| 183 |
|
|
|
|
| 238 |
.status { margin: 0 0 10px; font-size: 0.8em; font-weight: 500; }
|
| 239 |
.status.ready { color: #6aa87a; }
|
| 240 |
.status.loading { color: #c9994a; }
|
| 241 |
+
.status.error { color: #d96c6c; }
|
| 242 |
.chatbot-wrap .message.user { background: #2a1e14 !important; border: 1px solid #3a2c1e !important; }
|
| 243 |
.chatbot-wrap .message.bot { background: #1c1510 !important; border: 1px solid #2e2218 !important; }
|
| 244 |
.chatbot-wrap .message { border-radius: 8px !important; }
|
|
|
|
| 367 |
@demo.app.post("/v1/chat/completions")
|
| 368 |
async def chat_completions(request: Request):
|
| 369 |
if llm is None:
|
| 370 |
+
detail = f"Model failed to load: {model_error}" if model_error else "Model is still loading, try again in a moment."
|
| 371 |
+
return JSONResponse({"error": detail}, status_code=503)
|
| 372 |
|
| 373 |
body = await request.json()
|
| 374 |
messages = body.get("messages", [])
|
|
|
|
| 386 |
async def event_stream():
|
| 387 |
resp_id = "chatcmpl-" + uuid.uuid4().hex
|
| 388 |
created = int(time.time())
|
| 389 |
+
q = queue_mod.Queue()
|
| 390 |
DONE = object()
|
| 391 |
|
|
|
|
| 392 |
def produce():
|
| 393 |
try:
|
| 394 |
with infer_lock:
|
|
|
|
| 426 |
|
| 427 |
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
| 428 |
|
|
|
|
| 429 |
def generate():
|
| 430 |
with infer_lock:
|
| 431 |
return llm.create_chat_completion(
|
|
|
|
| 435 |
stream = False,
|
| 436 |
)
|
| 437 |
|
| 438 |
+
try:
|
| 439 |
+
result = await asyncio.to_thread(generate)
|
| 440 |
+
return JSONResponse(result)
|
| 441 |
+
except Exception as exc:
|
| 442 |
+
return JSONResponse(
|
| 443 |
+
{"error": f"Generation failed: {type(exc).__name__}: {exc}"},
|
| 444 |
+
status_code=500,
|
| 445 |
+
)
|
| 446 |
|
| 447 |
|
| 448 |
# ββ Launch βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|