Update app.py
Browse files
app.py
CHANGED
|
@@ -10,8 +10,6 @@ import uvicorn
|
|
| 10 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
# 1. Model Configuration
|
| 12 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 13 |
-
# Upgraded: 1.5B model β 3x smarter, fits easily in 16 GB free RAM
|
| 14 |
-
# Switch back to 0.5B by changing these two lines if needed
|
| 15 |
MODEL_REPO = "Qwen/Qwen2.5-1.5B-Instruct-GGUF"
|
| 16 |
MODEL_FILE = "qwen2.5-1.5b-instruct-q4_k_m.gguf"
|
| 17 |
|
|
@@ -31,29 +29,28 @@ print("Tokenizing system prompt for n_keep...")
|
|
| 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=8,
|
| 41 |
-
n_ctx=16384,
|
| 42 |
n_keep=_system_token_count,
|
| 43 |
-
n_batch=1024, # large batch = fastest prompt
|
| 44 |
-
n_ubatch=512,
|
| 45 |
-
use_mmap=True,
|
| 46 |
-
use_mlock=True,
|
| 47 |
verbose=False,
|
| 48 |
)
|
| 49 |
|
| 50 |
-
# 8 GB RAM cache β massive response reuse, near-instant repeat queries
|
| 51 |
cache = LlamaRAMCache(capacity_bytes=8_589_934_592)
|
| 52 |
llm.set_cache(cache)
|
| 53 |
print("RAM cache initialized (8 GB).")
|
| 54 |
|
| 55 |
-
#
|
| 56 |
-
|
|
|
|
| 57 |
|
| 58 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 59 |
# 3. FastAPI App
|
|
@@ -76,15 +73,20 @@ def format_prompt(user_text: str) -> str:
|
|
| 76 |
|
| 77 |
|
| 78 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 79 |
-
# 4. Startup Warmup β
|
| 80 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 81 |
@app.on_event("startup")
|
| 82 |
async def warmup():
|
| 83 |
-
print("Warming up model
|
| 84 |
loop = asyncio.get_event_loop()
|
|
|
|
| 85 |
await loop.run_in_executor(
|
| 86 |
_executor,
|
| 87 |
-
lambda: llm(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
)
|
| 89 |
print("Warmup complete. Server is ready.")
|
| 90 |
|
|
@@ -98,7 +100,7 @@ def root():
|
|
| 98 |
|
| 99 |
|
| 100 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 101 |
-
# ENDPOINT 1: Full
|
| 102 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 103 |
@app.post("/generate")
|
| 104 |
async def generate_full(request: QueryRequest):
|
|
@@ -117,13 +119,16 @@ async def generate_full(request: QueryRequest):
|
|
| 117 |
|
| 118 |
|
| 119 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 120 |
-
# ENDPOINT 2:
|
| 121 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 122 |
@app.post("/stream")
|
| 123 |
async def generate_stream(request: QueryRequest):
|
| 124 |
formatted_prompt = format_prompt(request.prompt)
|
| 125 |
loop = asyncio.get_event_loop()
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
def run_inference():
|
| 129 |
try:
|
|
@@ -137,12 +142,19 @@ async def generate_stream(request: QueryRequest):
|
|
| 137 |
for chunk in stream:
|
| 138 |
text = chunk["choices"][0]["text"]
|
| 139 |
if text:
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
finally:
|
| 142 |
asyncio.run_coroutine_threadsafe(queue.put(None), loop)
|
| 143 |
|
| 144 |
async def stream_generator():
|
|
|
|
| 145 |
yield f": {' ' * 2048}\n\n"
|
|
|
|
|
|
|
| 146 |
loop.run_in_executor(_executor, run_inference)
|
| 147 |
|
| 148 |
while True:
|
|
@@ -150,6 +162,9 @@ async def generate_stream(request: QueryRequest):
|
|
| 150 |
if token is None:
|
| 151 |
break
|
| 152 |
yield f"data: {token}\n\n"
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
yield "data: [DONE]\n\n"
|
| 155 |
|
|
|
|
| 10 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
# 1. Model Configuration
|
| 12 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 13 |
MODEL_REPO = "Qwen/Qwen2.5-1.5B-Instruct-GGUF"
|
| 14 |
MODEL_FILE = "qwen2.5-1.5b-instruct-q4_k_m.gguf"
|
| 15 |
|
|
|
|
| 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 |
print(f"System prompt is {_system_token_count} tokens β pinning in KV cache.")
|
| 33 |
|
| 34 |
print("Loading model into memory...")
|
| 35 |
llm = Llama(
|
| 36 |
model_path=model_path,
|
| 37 |
+
n_threads=8,
|
| 38 |
+
n_ctx=16384,
|
| 39 |
n_keep=_system_token_count,
|
| 40 |
+
n_batch=1024, # large batch = fastest prefill (prompt processing)
|
| 41 |
+
n_ubatch=512,
|
| 42 |
+
use_mmap=True,
|
| 43 |
+
use_mlock=True,
|
| 44 |
verbose=False,
|
| 45 |
)
|
| 46 |
|
|
|
|
| 47 |
cache = LlamaRAMCache(capacity_bytes=8_589_934_592)
|
| 48 |
llm.set_cache(cache)
|
| 49 |
print("RAM cache initialized (8 GB).")
|
| 50 |
|
| 51 |
+
# llama.cpp is not thread-safe β single worker serializes calls correctly
|
| 52 |
+
# (multiple workers would corrupt state)
|
| 53 |
+
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
| 54 |
|
| 55 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
# 3. FastAPI App
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 76 |
+
# 4. Startup Warmup β prime CPU caches & KV allocator
|
| 77 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 78 |
@app.on_event("startup")
|
| 79 |
async def warmup():
|
| 80 |
+
print("Warming up model...")
|
| 81 |
loop = asyncio.get_event_loop()
|
| 82 |
+
# Warm with a realistic-length prompt so prefill path is fully primed
|
| 83 |
await loop.run_in_executor(
|
| 84 |
_executor,
|
| 85 |
+
lambda: llm(
|
| 86 |
+
format_prompt("Explain what recursion is in one sentence."),
|
| 87 |
+
max_tokens=4,
|
| 88 |
+
stream=False,
|
| 89 |
+
),
|
| 90 |
)
|
| 91 |
print("Warmup complete. Server is ready.")
|
| 92 |
|
|
|
|
| 100 |
|
| 101 |
|
| 102 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 103 |
+
# ENDPOINT 1: Full response
|
| 104 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 105 |
@app.post("/generate")
|
| 106 |
async def generate_full(request: QueryRequest):
|
|
|
|
| 119 |
|
| 120 |
|
| 121 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 122 |
+
# ENDPOINT 2: Streaming (SSE)
|
| 123 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 124 |
@app.post("/stream")
|
| 125 |
async def generate_stream(request: QueryRequest):
|
| 126 |
formatted_prompt = format_prompt(request.prompt)
|
| 127 |
loop = asyncio.get_event_loop()
|
| 128 |
+
|
| 129 |
+
# Use a small queue (maxsize=1) so the inference thread blocks the moment
|
| 130 |
+
# the consumer (event loop) is not keeping up β prevents runaway buffering
|
| 131 |
+
queue: asyncio.Queue = asyncio.Queue(maxsize=1)
|
| 132 |
|
| 133 |
def run_inference():
|
| 134 |
try:
|
|
|
|
| 142 |
for chunk in stream:
|
| 143 |
text = chunk["choices"][0]["text"]
|
| 144 |
if text:
|
| 145 |
+
# run_coroutine_threadsafe + result() makes the inference
|
| 146 |
+
# thread WAIT until the event loop has consumed this token
|
| 147 |
+
# before producing the next one β zero buffering delay
|
| 148 |
+
fut = asyncio.run_coroutine_threadsafe(queue.put(text), loop)
|
| 149 |
+
fut.result() # block until token is in the queue
|
| 150 |
finally:
|
| 151 |
asyncio.run_coroutine_threadsafe(queue.put(None), loop)
|
| 152 |
|
| 153 |
async def stream_generator():
|
| 154 |
+
# Break Nginx / HF Space proxy buffer
|
| 155 |
yield f": {' ' * 2048}\n\n"
|
| 156 |
+
|
| 157 |
+
# Start inference in background β don't await so we proceed immediately
|
| 158 |
loop.run_in_executor(_executor, run_inference)
|
| 159 |
|
| 160 |
while True:
|
|
|
|
| 162 |
if token is None:
|
| 163 |
break
|
| 164 |
yield f"data: {token}\n\n"
|
| 165 |
+
# Force Uvicorn to flush this chunk to the network RIGHT NOW
|
| 166 |
+
# without this, the event loop may batch multiple tokens together
|
| 167 |
+
await asyncio.sleep(0)
|
| 168 |
|
| 169 |
yield "data: [DONE]\n\n"
|
| 170 |
|