Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
import os
|
| 2 |
import asyncio
|
| 3 |
import concurrent.futures
|
| 4 |
from huggingface_hub import hf_hub_download
|
|
@@ -27,29 +26,31 @@ print("Downloading model...")
|
|
| 27 |
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 28 |
|
| 29 |
print("Tokenizing system prompt for n_keep...")
|
| 30 |
-
# Temporary loader just to measure system-prompt token length
|
| 31 |
_tmp = Llama(model_path=model_path, n_ctx=64, verbose=False)
|
| 32 |
_system_token_count = len(_tmp.tokenize(SYSTEM_PROMPT.encode()))
|
| 33 |
-
del _tmp
|
| 34 |
|
| 35 |
print(f"System prompt is {_system_token_count} tokens β pinning in KV cache.")
|
| 36 |
|
| 37 |
print("Loading model into memory...")
|
| 38 |
llm = Llama(
|
| 39 |
model_path=model_path,
|
| 40 |
-
n_threads=
|
| 41 |
-
n_ctx=
|
| 42 |
-
n_keep=_system_token_count,
|
|
|
|
|
|
|
|
|
|
| 43 |
verbose=False,
|
| 44 |
)
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
cache = LlamaRAMCache(capacity_bytes=
|
| 48 |
llm.set_cache(cache)
|
| 49 |
-
print("RAM cache initialized.")
|
| 50 |
|
| 51 |
-
#
|
| 52 |
-
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=
|
| 53 |
|
| 54 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 55 |
# 3. FastAPI App
|
|
@@ -76,13 +77,6 @@ def format_prompt(user_text: str) -> str:
|
|
| 76 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
@app.on_event("startup")
|
| 78 |
async def warmup():
|
| 79 |
-
"""
|
| 80 |
-
Run one cheap inference pass at boot so that:
|
| 81 |
-
- BLAS threads are spawned and hot
|
| 82 |
-
- CPU instruction / data caches are primed
|
| 83 |
-
- KV allocator is initialized
|
| 84 |
-
First real user request arrives to a warm engine.
|
| 85 |
-
"""
|
| 86 |
print("Warming up model (1 token)...")
|
| 87 |
loop = asyncio.get_event_loop()
|
| 88 |
await loop.run_in_executor(
|
|
@@ -92,15 +86,19 @@ async def warmup():
|
|
| 92 |
print("Warmup complete. Server is ready.")
|
| 93 |
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 96 |
# ENDPOINT 1: Full (non-streaming) response
|
| 97 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 98 |
@app.post("/generate")
|
| 99 |
async def generate_full(request: QueryRequest):
|
| 100 |
-
"""
|
| 101 |
-
Returns the complete response once inference finishes.
|
| 102 |
-
Runs in the thread pool so it never blocks the event loop.
|
| 103 |
-
"""
|
| 104 |
loop = asyncio.get_event_loop()
|
| 105 |
response = await loop.run_in_executor(
|
| 106 |
_executor,
|
|
@@ -120,27 +118,11 @@ async def generate_full(request: QueryRequest):
|
|
| 120 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 121 |
@app.post("/stream")
|
| 122 |
async def generate_stream(request: QueryRequest):
|
| 123 |
-
"""
|
| 124 |
-
Streams tokens via Server-Sent Events as they are produced.
|
| 125 |
-
Key design decisions
|
| 126 |
-
ββββββββββββββββββββ
|
| 127 |
-
β’ Inference runs in _executor (thread pool) so llama.cpp never
|
| 128 |
-
blocks the async event loop β the event loop can flush bytes
|
| 129 |
-
to the network between tokens instead of batching them.
|
| 130 |
-
β’ asyncio.Queue bridges the sync inference thread and the
|
| 131 |
-
async generator that feeds StreamingResponse.
|
| 132 |
-
β’ 2 KB SSE comment breaks Nginx / HF Space's proxy buffer
|
| 133 |
-
immediately so the client sees bytes without waiting for a
|
| 134 |
-
full buffer to fill.
|
| 135 |
-
β’ A blinking-cursor token is sent right away so the UI feels
|
| 136 |
-
responsive before the first real token arrives.
|
| 137 |
-
"""
|
| 138 |
formatted_prompt = format_prompt(request.prompt)
|
| 139 |
loop = asyncio.get_event_loop()
|
| 140 |
queue: asyncio.Queue = asyncio.Queue()
|
| 141 |
|
| 142 |
def run_inference():
|
| 143 |
-
"""Runs in thread pool; puts tokens into the async queue."""
|
| 144 |
try:
|
| 145 |
stream = llm(
|
| 146 |
formatted_prompt,
|
|
@@ -154,33 +136,17 @@ async def generate_stream(request: QueryRequest):
|
|
| 154 |
if text:
|
| 155 |
asyncio.run_coroutine_threadsafe(queue.put(text), loop)
|
| 156 |
finally:
|
| 157 |
-
# Always send sentinel so the generator can exit cleanly
|
| 158 |
asyncio.run_coroutine_threadsafe(queue.put(None), loop)
|
| 159 |
|
| 160 |
async def stream_generator():
|
| 161 |
-
# Break proxy/Nginx buffer immediately
|
| 162 |
yield f": {' ' * 2048}\n\n"
|
| 163 |
-
|
| 164 |
-
# Show a cursor so the UI isn't blank while the first token
|
| 165 |
-
# is being computed (forward pass over the full prompt)
|
| 166 |
-
yield "data: β\n\n"
|
| 167 |
-
|
| 168 |
-
# Kick off inference in the background thread
|
| 169 |
loop.run_in_executor(_executor, run_inference)
|
| 170 |
|
| 171 |
-
# Overwrite the placeholder cursor with the real stream
|
| 172 |
-
first = True
|
| 173 |
while True:
|
| 174 |
token = await queue.get()
|
| 175 |
if token is None:
|
| 176 |
break
|
| 177 |
-
|
| 178 |
-
# Clear the cursor by prepending a backspace-width span
|
| 179 |
-
# (works in most chat UIs; harmless if it doesn't)
|
| 180 |
-
yield f"data: \r{token}\n\n"
|
| 181 |
-
first = False
|
| 182 |
-
else:
|
| 183 |
-
yield f"data: {token}\n\n"
|
| 184 |
|
| 185 |
yield "data: [DONE]\n\n"
|
| 186 |
|
|
@@ -188,18 +154,16 @@ async def generate_stream(request: QueryRequest):
|
|
| 188 |
stream_generator(),
|
| 189 |
media_type="text/event-stream",
|
| 190 |
headers={
|
| 191 |
-
"X-Accel-Buffering": "no",
|
| 192 |
"Cache-Control": "no-cache",
|
| 193 |
"Connection": "keep-alive",
|
| 194 |
"Content-Type": "text/event-stream; charset=utf-8",
|
| 195 |
},
|
| 196 |
)
|
| 197 |
|
| 198 |
-
|
| 199 |
-
def root():
|
| 200 |
-
return {"status": "ok", "model": MODEL_FILE}
|
| 201 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 202 |
-
#
|
| 203 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
if __name__ == "__main__":
|
| 205 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import concurrent.futures
|
| 3 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 26 |
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 27 |
|
| 28 |
print("Tokenizing system prompt for n_keep...")
|
|
|
|
| 29 |
_tmp = Llama(model_path=model_path, n_ctx=64, verbose=False)
|
| 30 |
_system_token_count = len(_tmp.tokenize(SYSTEM_PROMPT.encode()))
|
| 31 |
+
del _tmp
|
| 32 |
|
| 33 |
print(f"System prompt is {_system_token_count} tokens β pinning in KV cache.")
|
| 34 |
|
| 35 |
print("Loading model into memory...")
|
| 36 |
llm = Llama(
|
| 37 |
model_path=model_path,
|
| 38 |
+
n_threads=4, # more threads = faster token generation
|
| 39 |
+
n_ctx=8192, # 8k context (was 2048) β uses ~1 GB extra RAM
|
| 40 |
+
n_keep=_system_token_count,
|
| 41 |
+
n_batch=512, # larger batch = faster prompt processing
|
| 42 |
+
use_mmap=True, # memory-map the model file β faster cold load
|
| 43 |
+
use_mlock=True, # lock model weights in RAM β prevents OS swapping
|
| 44 |
verbose=False,
|
| 45 |
)
|
| 46 |
|
| 47 |
+
# 4 GB RAM cache (was 512 MB) β repeat queries return instantly
|
| 48 |
+
cache = LlamaRAMCache(capacity_bytes=4_294_967_296)
|
| 49 |
llm.set_cache(cache)
|
| 50 |
+
print("RAM cache initialized (4 GB).")
|
| 51 |
|
| 52 |
+
# More workers = handle parallel requests without queuing
|
| 53 |
+
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
|
| 54 |
|
| 55 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
# 3. FastAPI App
|
|
|
|
| 77 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 78 |
@app.on_event("startup")
|
| 79 |
async def warmup():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
print("Warming up model (1 token)...")
|
| 81 |
loop = asyncio.get_event_loop()
|
| 82 |
await loop.run_in_executor(
|
|
|
|
| 86 |
print("Warmup complete. Server is ready.")
|
| 87 |
|
| 88 |
|
| 89 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 90 |
+
# 5. Health check
|
| 91 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 92 |
+
@app.get("/")
|
| 93 |
+
def root():
|
| 94 |
+
return {"status": "ok", "model": MODEL_FILE}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 98 |
# ENDPOINT 1: Full (non-streaming) response
|
| 99 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 100 |
@app.post("/generate")
|
| 101 |
async def generate_full(request: QueryRequest):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
loop = asyncio.get_event_loop()
|
| 103 |
response = await loop.run_in_executor(
|
| 104 |
_executor,
|
|
|
|
| 118 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 119 |
@app.post("/stream")
|
| 120 |
async def generate_stream(request: QueryRequest):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
formatted_prompt = format_prompt(request.prompt)
|
| 122 |
loop = asyncio.get_event_loop()
|
| 123 |
queue: asyncio.Queue = asyncio.Queue()
|
| 124 |
|
| 125 |
def run_inference():
|
|
|
|
| 126 |
try:
|
| 127 |
stream = llm(
|
| 128 |
formatted_prompt,
|
|
|
|
| 136 |
if text:
|
| 137 |
asyncio.run_coroutine_threadsafe(queue.put(text), loop)
|
| 138 |
finally:
|
|
|
|
| 139 |
asyncio.run_coroutine_threadsafe(queue.put(None), loop)
|
| 140 |
|
| 141 |
async def stream_generator():
|
|
|
|
| 142 |
yield f": {' ' * 2048}\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
loop.run_in_executor(_executor, run_inference)
|
| 144 |
|
|
|
|
|
|
|
| 145 |
while True:
|
| 146 |
token = await queue.get()
|
| 147 |
if token is None:
|
| 148 |
break
|
| 149 |
+
yield f"data: {token}\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
yield "data: [DONE]\n\n"
|
| 152 |
|
|
|
|
| 154 |
stream_generator(),
|
| 155 |
media_type="text/event-stream",
|
| 156 |
headers={
|
| 157 |
+
"X-Accel-Buffering": "no",
|
| 158 |
"Cache-Control": "no-cache",
|
| 159 |
"Connection": "keep-alive",
|
| 160 |
"Content-Type": "text/event-stream; charset=utf-8",
|
| 161 |
},
|
| 162 |
)
|
| 163 |
|
| 164 |
+
|
|
|
|
|
|
|
| 165 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 166 |
+
# 6. Entrypoint
|
| 167 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 168 |
if __name__ == "__main__":
|
| 169 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|