dpv007 commited on
Commit
481dbf3
Β·
verified Β·
1 Parent(s): 941af88

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -218
app.py CHANGED
@@ -1,262 +1,156 @@
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
7
- from fastapi.responses import StreamingResponse
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(
28
- repo_id=MODEL_REPO,
29
- filename=MODEL_FILE,
30
- )
31
-
32
- print("Tokenizing system prompt for n_keep...")
33
-
34
- _tmp = Llama(
35
- model_path=model_path,
36
- n_ctx=64,
37
- verbose=False,
38
- )
39
-
40
- _system_token_count = len(
41
- _tmp.tokenize(SYSTEM_PROMPT.encode())
42
- )
43
-
44
- del _tmp
45
 
46
- print(
47
- f"System prompt is {_system_token_count} tokens "
48
- f"β†’ pinning in KV cache."
49
- )
50
-
51
- print("Loading model into memory...")
52
-
53
- llm = Llama(
54
- model_path=model_path,
55
- n_threads=2,
56
- n_ctx=2048,
57
- n_keep=_system_token_count,
58
- verbose=False,
59
- )
60
-
61
- # RAM cache
62
- cache = LlamaRAMCache(
63
- capacity_bytes=536_870_912
64
- )
65
-
66
- llm.set_cache(cache)
67
 
68
- print("RAM cache initialized.")
69
 
70
- # llama.cpp is not thread-safe
71
- _executor = concurrent.futures.ThreadPoolExecutor(
72
- max_workers=1
73
- )
74
-
75
- # ──────────────────────────────────────────────
76
- # 3. FastAPI App
77
- # ──────────────────────────────────────────────
78
- app = FastAPI(
79
- title="Qwen-2.5 0.5B Local CPU API"
80
- )
81
 
 
82
 
83
- class QueryRequest(BaseModel):
84
- prompt: str
85
- max_tokens: int = 512
86
- temperature: float = 0.7
87
 
 
88
 
89
- def format_prompt(user_text: str) -> str:
90
 
91
- return (
92
- f"{SYSTEM_PROMPT}"
93
- f"<|im_start|>user\n"
94
- f"{user_text}<|im_end|>\n"
95
- f"<|im_start|>assistant\n"
96
- )
97
 
 
98
 
99
- # ──────────────────────────────────────────────
100
- # 4. Startup Warmup
101
- # ──────────────────────────────────────────────
102
- @app.on_event("startup")
103
- async def warmup():
104
-
105
- print("Warming up model...")
106
 
107
- loop = asyncio.get_event_loop()
108
 
109
- await loop.run_in_executor(
110
- _executor,
111
- lambda: llm(
112
- format_prompt("hi"),
113
- max_tokens=1,
114
- stream=False,
115
- ),
116
- )
117
 
118
- print("Warmup complete.")
119
 
 
120
 
121
- # ───────────────────────────────────��──────────
122
- # 5. Full Generation Endpoint
123
- # ──────────────────────────────────────────────
124
- @app.post("/generate")
125
- async def generate_full(request: QueryRequest):
126
 
127
- loop = asyncio.get_event_loop()
128
 
129
- response = await loop.run_in_executor(
130
- _executor,
131
- lambda: llm(
132
- format_prompt(request.prompt),
133
- max_tokens=request.max_tokens,
134
- stream=False,
135
- temperature=request.temperature,
136
- stop=["<|im_end|>", "<|im_start|>"],
137
- ),
138
- )
139
 
140
- return {
141
- "response": response["choices"][0]["text"]
142
- }
143
 
 
144
 
145
- # ──────────────────────────────────────────────
146
- # 6. Streaming Endpoint (FIXED)
147
- # ──────────────────────────────────────────────
148
- @app.post("/stream")
149
- async def generate_stream(request: QueryRequest):
150
 
151
- formatted_prompt = format_prompt(
152
- request.prompt
153
- )
154
 
155
- loop = asyncio.get_event_loop()
156
 
157
- queue: asyncio.Queue = asyncio.Queue()
158
 
159
- def run_inference():
160
 
161
- try:
162
 
163
- stream = llm(
164
- formatted_prompt,
165
- max_tokens=request.max_tokens,
166
- stream=True,
167
- temperature=request.temperature,
168
- stop=["<|im_end|>", "<|im_start|>"],
169
- )
170
 
171
- full_text = ""
172
 
173
- for chunk in stream:
174
 
175
- token = chunk["choices"][0]["text"]
176
 
177
- if not token:
178
- continue
179
 
180
- # Properly reconstruct text
181
- full_text += token
182
 
183
- asyncio.run_coroutine_threadsafe(
184
- queue.put(full_text),
185
- loop,
186
- )
187
 
188
- finally:
189
 
190
- asyncio.run_coroutine_threadsafe(
191
- queue.put(None),
192
- loop,
193
- )
194
 
195
- async def stream_generator():
196
 
197
- # Break HF/Nginx buffering
198
- yield f": {' ' * 2048}\n\n"
199
 
200
- # Initial cursor
201
- yield "data: ▍\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
- # Start inference
204
- loop.run_in_executor(
205
- _executor,
206
- run_inference,
 
 
 
 
 
207
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
- previous_text = ""
210
-
211
- while True:
212
-
213
- text = await queue.get()
214
-
215
- if text is None:
216
- break
217
-
218
- # Send only new delta
219
- delta = text[len(previous_text):]
220
-
221
- previous_text = text
222
-
223
- if delta:
224
- yield f"data: {delta}\n\n"
225
-
226
- yield "data: [DONE]\n\n"
227
-
228
- return StreamingResponse(
229
- stream_generator(),
230
- media_type="text/event-stream",
231
- headers={
232
- "X-Accel-Buffering": "no",
233
- "Cache-Control": "no-cache",
234
- "Connection": "keep-alive",
235
- "Content-Type":
236
- "text/event-stream; charset=utf-8",
237
- },
238
- )
239
-
240
-
241
- # ──────────────────────────────────────────────
242
- # 7. Health Check
243
- # ──────────────────────────────────────────────
244
- @app.get("/")
245
- def root():
246
 
247
- return {
248
- "status": "ok",
249
- "model": MODEL_FILE,
250
- }
251
 
 
252
 
253
- # ──────────────────────────────────────────────
254
- # 8. Entrypoint
255
- # ──────────────────────────────────────────────
256
- if __name__ == "__main__":
257
 
258
- uvicorn.run(
259
- app,
260
- host="0.0.0.0",
261
- port=7860,
262
- )
 
1
+ import osimport asyncioimport concurrent.futuresfrom huggingface_hub import hf_hub_downloadfrom llama_cpp import Llama, LlamaRAMCachefrom fastapi import FastAPIfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelimport uvicorn
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ ──────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ 1. Model Configuration
6
 
7
+ ──────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
8
 
9
+ MODEL_REPO = "Qwen/Qwen2.5-0.5B-Instruct-GGUF"MODEL_FILE = "qwen2.5-0.5b-instruct-q4_k_m.gguf"
10
 
11
+ SYSTEM_PROMPT = ("<|im_start|>system\n""You are a highly capable technical assistant.""<|im_end|>\n")
 
 
 
12
 
13
+ ──────────────────────────────────────────────
14
 
15
+ 2. Download & Load Model
16
 
17
+ ──────────────────────────────────────────────
 
 
 
 
 
18
 
19
+ print("Downloading model...")model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
20
 
21
+ print("Tokenizing system prompt for n_keep...")
 
 
 
 
 
 
22
 
23
+ Temporary loader just to measure system-prompt token length
24
 
25
+ _tmp = Llama(model_path=model_path, n_ctx=64, verbose=False)_system_token_count = len(_tmp.tokenize(SYSTEM_PROMPT.encode()))del _tmp # free immediately
 
 
 
 
 
 
 
26
 
27
+ print(f"System prompt is {_system_token_count} tokens β†’ pinning in KV cache.")
28
 
29
+ print("Loading model into memory...")llm = Llama(model_path=model_path,n_threads=2,n_ctx=2048,n_keep=_system_token_count, # pin system prompt β€” never recomputedverbose=False,)
30
 
31
+ Attach RAM cache (512 MB)
 
 
 
 
32
 
33
+ cache = LlamaRAMCache(capacity_bytes=536_870_912)llm.set_cache(cache)print("RAM cache initialized.")
34
 
35
+ Single-worker thread pool β€” llama.cpp is not thread-safe
 
 
 
 
 
 
 
 
 
36
 
37
+ _executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
 
 
38
 
39
+ ──────────────────────────────────────────────
40
 
41
+ 3. FastAPI App
 
 
 
 
42
 
43
+ ──────────────────────────────────────────────
 
 
44
 
45
+ app = FastAPI(title="Qwen-2.5 0.5B Local CPU API")
46
 
47
+ class QueryRequest(BaseModel):prompt: strmax_tokens: int = 512temperature: float = 0.7
48
 
49
+ def format_prompt(user_text: str) -> str:return (f"{SYSTEM_PROMPT}"f"<|im_start|>user\n{user_text}<|im_end|>\n"f"<|im_start|>assistant\n")
50
 
51
+ ──────────────────────────────────────────────
52
 
53
+ 4. Startup Warmup β€” eliminates cold-start
 
 
 
 
 
 
54
 
55
+ ──────────────────────────────────────────────
56
 
57
+ @app.on_event("startup")async def warmup():"""Run one cheap inference pass at boot so that:- BLAS threads are spawned and hot- CPU instruction / data caches are primed- KV allocator is initializedFirst real user request arrives to a warm engine."""print("Warming up model (1 token)...")loop = asyncio.get_event_loop()await loop.run_in_executor(_executor,lambda: llm(format_prompt("hi"), max_tokens=1, stream=False),)print("Warmup complete. Server is ready.")
58
 
59
+ ──────────────────────────────────────────────
60
 
61
+ ENDPOINT 1: Full (non-streaming) response
 
62
 
63
+ ──────────────────────────────────────────────
 
64
 
65
+ @app.post("/generate")async def generate_full(request: QueryRequest):"""Returns the complete response once inference finishes.Runs in the thread pool so it never blocks the event loop."""loop = asyncio.get_event_loop()response = await loop.run_in_executor(_executor,lambda: llm(format_prompt(request.prompt),max_tokens=request.max_tokens,stream=False,temperature=request.temperature,stop=["<|im_end|>", "<|im_start|>"],),)return {"response": response["choices"][0]["text"]}
 
 
 
66
 
67
+ ──────────────────────────────────────────────
68
 
69
+ ENDPOINT 2: True streaming (SSE)
 
 
 
70
 
71
+ ──────────────────────────────────────────────
72
 
73
+ @app.post("/stream")async def generate_stream(request: QueryRequest):"""Streams tokens via Server-Sent Events as they are produced.
 
74
 
75
+ Key design decisions
76
+ ────────────────────
77
+ β€’ Inference runs in _executor (thread pool) so llama.cpp never
78
+ blocks the async event loop β€” the event loop can flush bytes
79
+ to the network between tokens instead of batching them.
80
+ β€’ asyncio.Queue bridges the sync inference thread and the
81
+ async generator that feeds StreamingResponse.
82
+ β€’ 2 KB SSE comment breaks Nginx / HF Space's proxy buffer
83
+ immediately so the client sees bytes without waiting for a
84
+ full buffer to fill.
85
+ β€’ A blinking-cursor token is sent right away so the UI feels
86
+ responsive before the first real token arrives.
87
+ """
88
+ formatted_prompt = format_prompt(request.prompt)
89
+ loop = asyncio.get_event_loop()
90
+ queue: asyncio.Queue = asyncio.Queue()
91
 
92
+ def run_inference():
93
+ """Runs in thread pool; puts tokens into the async queue."""
94
+ try:
95
+ stream = llm(
96
+ formatted_prompt,
97
+ max_tokens=request.max_tokens,
98
+ stream=True,
99
+ temperature=request.temperature,
100
+ stop=["<|im_end|>", "<|im_start|>"],
101
  )
102
+ for chunk in stream:
103
+ text = chunk["choices"][0]["text"]
104
+ if text:
105
+ asyncio.run_coroutine_threadsafe(queue.put(text), loop)
106
+ finally:
107
+ # Always send sentinel so the generator can exit cleanly
108
+ asyncio.run_coroutine_threadsafe(queue.put(None), loop)
109
+
110
+ async def stream_generator():
111
+ # Break proxy/Nginx buffer immediately
112
+ yield f": {' ' * 2048}\n\n"
113
+
114
+ # Show a cursor so the UI isn't blank while the first token
115
+ # is being computed (forward pass over the full prompt)
116
+ yield "data: ▍\n\n"
117
+
118
+ # Kick off inference in the background thread
119
+ loop.run_in_executor(_executor, run_inference)
120
+
121
+ # Overwrite the placeholder cursor with the real stream
122
+ first = True
123
+ while True:
124
+ token = await queue.get()
125
+ if token is None:
126
+ break
127
+ if first:
128
+ # Clear the cursor by prepending a backspace-width span
129
+ # (works in most chat UIs; harmless if it doesn't)
130
+ yield f"data: \r{token}\n\n"
131
+ first = False
132
+ else:
133
+ yield f"data: {token}\n\n"
134
+
135
+ yield "data: [DONE]\n\n"
136
+
137
+ return StreamingResponse(
138
+ stream_generator(),
139
+ media_type="text/event-stream",
140
+ headers={
141
+ "X-Accel-Buffering": "no", # disable Nginx buffering
142
+ "Cache-Control": "no-cache",
143
+ "Connection": "keep-alive",
144
+ "Content-Type": "text/event-stream; charset=utf-8",
145
+ },
146
+ )
147
 
148
+ @app.get("/")def root():return {"status": "ok", "model": MODEL_FILE}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
+ ──────────────────────────────────────────────
 
 
 
151
 
152
+ 5. Entrypoint
153
 
154
+ ──────────────────────────────────────────────
 
 
 
155
 
156
+ if name == "main":uvicorn.run(app, host="0.0.0.0", port=7860)