Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
|
|
|
| 3 |
from huggingface_hub import hf_hub_download
|
| 4 |
from llama_cpp import Llama, LlamaRAMCache
|
| 5 |
from fastapi import FastAPI
|
|
@@ -7,97 +8,197 @@ from fastapi.responses import StreamingResponse
|
|
| 7 |
from pydantic import BaseModel
|
| 8 |
import uvicorn
|
| 9 |
|
|
|
|
| 10 |
# 1. Model Configuration
|
| 11 |
-
|
| 12 |
-
|
|
|
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
print("Downloading model...")
|
| 15 |
-
model_path = hf_hub_download(repo_id=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
# 2. Initialize Model with Strict CPU Limits
|
| 18 |
print("Loading model into memory...")
|
| 19 |
llm = Llama(
|
| 20 |
model_path=model_path,
|
| 21 |
-
n_threads=2,
|
| 22 |
-
n_ctx=2048,
|
| 23 |
-
|
|
|
|
| 24 |
)
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
cache = LlamaRAMCache(capacity_bytes=
|
| 28 |
llm.set_cache(cache)
|
| 29 |
print("RAM cache initialized.")
|
| 30 |
|
| 31 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
app = FastAPI(title="Qwen-2.5 0.5B Local CPU API")
|
| 33 |
|
|
|
|
| 34 |
class QueryRequest(BaseModel):
|
| 35 |
prompt: str
|
| 36 |
max_tokens: int = 512
|
| 37 |
temperature: float = 0.7
|
| 38 |
|
|
|
|
| 39 |
def format_prompt(user_text: str) -> str:
|
| 40 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
# ENDPOINT 1:
|
| 44 |
-
#
|
| 45 |
@app.post("/generate")
|
| 46 |
-
def generate_full(request: QueryRequest):
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
)
|
| 56 |
return {"response": response["choices"][0]["text"]}
|
| 57 |
|
| 58 |
-
|
| 59 |
-
#
|
| 60 |
-
#
|
|
|
|
| 61 |
@app.post("/stream")
|
| 62 |
async def generate_stream(request: QueryRequest):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
formatted_prompt = format_prompt(request.prompt)
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
async def stream_generator():
|
| 67 |
-
#
|
| 68 |
-
# In SSE format, lines starting with a colon are ignored as comments by the client.
|
| 69 |
yield f": {' ' * 2048}\n\n"
|
| 70 |
-
|
| 71 |
-
#
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
#
|
| 86 |
-
#
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
| 89 |
yield "data: [DONE]\n\n"
|
| 90 |
|
| 91 |
return StreamingResponse(
|
| 92 |
-
stream_generator(),
|
| 93 |
media_type="text/event-stream",
|
| 94 |
headers={
|
| 95 |
-
"X-Accel-Buffering": "no",
|
| 96 |
"Cache-Control": "no-cache",
|
| 97 |
"Connection": "keep-alive",
|
| 98 |
-
"Content-Type": "text/event-stream; charset=utf-8"
|
| 99 |
-
}
|
| 100 |
)
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
if __name__ == "__main__":
|
| 103 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
+
import concurrent.futures
|
| 4 |
from huggingface_hub import hf_hub_download
|
| 5 |
from llama_cpp import Llama, LlamaRAMCache
|
| 6 |
from fastapi import FastAPI
|
|
|
|
| 8 |
from pydantic import BaseModel
|
| 9 |
import uvicorn
|
| 10 |
|
| 11 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 12 |
# 1. Model Configuration
|
| 13 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 14 |
+
MODEL_REPO = "Qwen/Qwen2.5-0.5B-Instruct-GGUF"
|
| 15 |
+
MODEL_FILE = "qwen2.5-0.5b-instruct-q4_k_m.gguf"
|
| 16 |
|
| 17 |
+
SYSTEM_PROMPT = (
|
| 18 |
+
"<|im_start|>system\n"
|
| 19 |
+
"You are a highly capable technical assistant."
|
| 20 |
+
"<|im_end|>\n"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
+
# 2. Download & Load Model
|
| 25 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
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 # free immediately
|
| 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=2,
|
| 41 |
+
n_ctx=2048,
|
| 42 |
+
n_keep=_system_token_count, # pin system prompt β never recomputed
|
| 43 |
+
verbose=False,
|
| 44 |
)
|
| 45 |
|
| 46 |
+
# Attach RAM cache (512 MB)
|
| 47 |
+
cache = LlamaRAMCache(capacity_bytes=536_870_912)
|
| 48 |
llm.set_cache(cache)
|
| 49 |
print("RAM cache initialized.")
|
| 50 |
|
| 51 |
+
# Single-worker thread pool β llama.cpp is not thread-safe
|
| 52 |
+
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
| 53 |
+
|
| 54 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 55 |
+
# 3. FastAPI App
|
| 56 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 57 |
app = FastAPI(title="Qwen-2.5 0.5B Local CPU API")
|
| 58 |
|
| 59 |
+
|
| 60 |
class QueryRequest(BaseModel):
|
| 61 |
prompt: str
|
| 62 |
max_tokens: int = 512
|
| 63 |
temperature: float = 0.7
|
| 64 |
|
| 65 |
+
|
| 66 |
def format_prompt(user_text: str) -> str:
|
| 67 |
+
return (
|
| 68 |
+
f"{SYSTEM_PROMPT}"
|
| 69 |
+
f"<|im_start|>user\n{user_text}<|im_end|>\n"
|
| 70 |
+
f"<|im_start|>assistant\n"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 75 |
+
# 4. Startup Warmup β eliminates cold-start
|
| 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(
|
| 89 |
+
_executor,
|
| 90 |
+
lambda: llm(format_prompt("hi"), max_tokens=1, stream=False),
|
| 91 |
+
)
|
| 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,
|
| 107 |
+
lambda: llm(
|
| 108 |
+
format_prompt(request.prompt),
|
| 109 |
+
max_tokens=request.max_tokens,
|
| 110 |
+
stream=False,
|
| 111 |
+
temperature=request.temperature,
|
| 112 |
+
stop=["<|im_end|>", "<|im_start|>"],
|
| 113 |
+
),
|
| 114 |
)
|
| 115 |
return {"response": response["choices"][0]["text"]}
|
| 116 |
|
| 117 |
+
|
| 118 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 119 |
+
# ENDPOINT 2: True streaming (SSE)
|
| 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 |
+
|
| 126 |
+
Key design decisions
|
| 127 |
+
ββββββββββββββββββββ
|
| 128 |
+
β’ Inference runs in _executor (thread pool) so llama.cpp never
|
| 129 |
+
blocks the async event loop β the event loop can flush bytes
|
| 130 |
+
to the network between tokens instead of batching them.
|
| 131 |
+
β’ asyncio.Queue bridges the sync inference thread and the
|
| 132 |
+
async generator that feeds StreamingResponse.
|
| 133 |
+
β’ 2 KB SSE comment breaks Nginx / HF Space's proxy buffer
|
| 134 |
+
immediately so the client sees bytes without waiting for a
|
| 135 |
+
full buffer to fill.
|
| 136 |
+
β’ A blinking-cursor token is sent right away so the UI feels
|
| 137 |
+
responsive before the first real token arrives.
|
| 138 |
+
"""
|
| 139 |
formatted_prompt = format_prompt(request.prompt)
|
| 140 |
+
loop = asyncio.get_event_loop()
|
| 141 |
+
queue: asyncio.Queue = asyncio.Queue()
|
| 142 |
+
|
| 143 |
+
def run_inference():
|
| 144 |
+
"""Runs in thread pool; puts tokens into the async queue."""
|
| 145 |
+
try:
|
| 146 |
+
stream = llm(
|
| 147 |
+
formatted_prompt,
|
| 148 |
+
max_tokens=request.max_tokens,
|
| 149 |
+
stream=True,
|
| 150 |
+
temperature=request.temperature,
|
| 151 |
+
stop=["<|im_end|>", "<|im_start|>"],
|
| 152 |
+
)
|
| 153 |
+
for chunk in stream:
|
| 154 |
+
text = chunk["choices"][0]["text"]
|
| 155 |
+
if text:
|
| 156 |
+
asyncio.run_coroutine_threadsafe(queue.put(text), loop)
|
| 157 |
+
finally:
|
| 158 |
+
# Always send sentinel so the generator can exit cleanly
|
| 159 |
+
asyncio.run_coroutine_threadsafe(queue.put(None), loop)
|
| 160 |
+
|
| 161 |
async def stream_generator():
|
| 162 |
+
# Break proxy/Nginx buffer immediately
|
|
|
|
| 163 |
yield f": {' ' * 2048}\n\n"
|
| 164 |
+
|
| 165 |
+
# Show a cursor so the UI isn't blank while the first token
|
| 166 |
+
# is being computed (forward pass over the full prompt)
|
| 167 |
+
yield "data: β\n\n"
|
| 168 |
+
|
| 169 |
+
# Kick off inference in the background thread
|
| 170 |
+
loop.run_in_executor(_executor, run_inference)
|
| 171 |
+
|
| 172 |
+
# Overwrite the placeholder cursor with the real stream
|
| 173 |
+
first = True
|
| 174 |
+
while True:
|
| 175 |
+
token = await queue.get()
|
| 176 |
+
if token is None:
|
| 177 |
+
break
|
| 178 |
+
if first:
|
| 179 |
+
# Clear the cursor by prepending a backspace-width span
|
| 180 |
+
# (works in most chat UIs; harmless if it doesn't)
|
| 181 |
+
yield f"data: \r{token}\n\n"
|
| 182 |
+
first = False
|
| 183 |
+
else:
|
| 184 |
+
yield f"data: {token}\n\n"
|
| 185 |
+
|
| 186 |
yield "data: [DONE]\n\n"
|
| 187 |
|
| 188 |
return StreamingResponse(
|
| 189 |
+
stream_generator(),
|
| 190 |
media_type="text/event-stream",
|
| 191 |
headers={
|
| 192 |
+
"X-Accel-Buffering": "no", # disable Nginx buffering
|
| 193 |
"Cache-Control": "no-cache",
|
| 194 |
"Connection": "keep-alive",
|
| 195 |
+
"Content-Type": "text/event-stream; charset=utf-8",
|
| 196 |
+
},
|
| 197 |
)
|
| 198 |
|
| 199 |
+
|
| 200 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 201 |
+
# 5. Entrypoint
|
| 202 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 203 |
if __name__ == "__main__":
|
| 204 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|