dpv007 commited on
Commit
5d8db16
Β·
verified Β·
1 Parent(s): 0e77622

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -78
app.py CHANGED
@@ -1,11 +1,17 @@
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
  # ──────────────────────────────────────────────
@@ -20,41 +26,77 @@ SYSTEM_PROMPT = (
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):
@@ -64,44 +106,45 @@ class QueryRequest(BaseModel):
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(
@@ -112,37 +155,30 @@ async def generate_full(request: QueryRequest):
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,
@@ -150,38 +186,61 @@ async def generate_stream(request: QueryRequest):
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
 
@@ -189,18 +248,35 @@ async def generate_stream(request: QueryRequest):
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
  @app.get("/")
200
  def root():
201
- return {"status": "ok", "model": MODEL_FILE}
 
 
 
 
 
 
 
202
  # ──────────────────────────────────────────────
203
- # 5. Entrypoint
204
  # ──────────────────────────────────────────────
205
  if __name__ == "__main__":
206
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
1
  import os
2
  import asyncio
3
  import concurrent.futures
4
+
5
  from huggingface_hub import hf_hub_download
6
+ from llama_cpp import (
7
+ Llama,
8
+ LlamaDiskCache,
9
+ )
10
+
11
  from fastapi import FastAPI
12
  from fastapi.responses import StreamingResponse
13
  from pydantic import BaseModel
14
+
15
  import uvicorn
16
 
17
  # ──────────────────────────────────────────────
 
26
  "<|im_end|>\n"
27
  )
28
 
29
+ # Persistent cache location
30
+ CACHE_DIR = "/data/kv_cache"
31
+
32
  # ──────────────────────────────────────────────
33
  # 2. Download & Load Model
34
  # ──────────────────────────────────────────────
35
  print("Downloading model...")
36
+
37
+ model_path = hf_hub_download(
38
+ repo_id=MODEL_REPO,
39
+ filename=MODEL_FILE,
40
+ )
41
 
42
  print("Tokenizing system prompt for n_keep...")
 
 
 
 
43
 
44
+ _tmp = Llama(
45
+ model_path=model_path,
46
+ n_ctx=64,
47
+ verbose=False,
48
+ )
49
+
50
+ _system_token_count = len(
51
+ _tmp.tokenize(SYSTEM_PROMPT.encode())
52
+ )
53
+
54
+ del _tmp
55
+
56
+ print(
57
+ f"System prompt is "
58
+ f"{_system_token_count} tokens "
59
+ f"β†’ pinning in KV cache."
60
+ )
61
 
62
  print("Loading model into memory...")
63
+
64
  llm = Llama(
65
  model_path=model_path,
66
  n_threads=2,
67
  n_ctx=2048,
68
+ n_keep=_system_token_count,
69
  verbose=False,
70
  )
71
 
72
+ # ──────────────────────────────────────────────
73
+ # 3. Persistent Disk KV Cache
74
+ # ──────────────────────────────────────────────
75
+ os.makedirs(CACHE_DIR, exist_ok=True)
76
+
77
+ cache = LlamaDiskCache(
78
+ cache_dir=CACHE_DIR,
79
+ capacity_bytes=2 * 1024 * 1024 * 1024, # 2 GB
80
+ )
81
+
82
  llm.set_cache(cache)
 
83
 
84
+ print(
85
+ f"Persistent KV cache initialized "
86
+ f"at {CACHE_DIR}"
87
+ )
88
+
89
+ # llama.cpp is NOT thread-safe
90
+ _executor = concurrent.futures.ThreadPoolExecutor(
91
+ max_workers=1
92
+ )
93
 
94
  # ──────────────────────────────────────────────
95
+ # 4. FastAPI App
96
  # ──────────────────────────────────────────────
97
+ app = FastAPI(
98
+ title="Qwen-2.5 0.5B Local CPU API"
99
+ )
100
 
101
 
102
  class QueryRequest(BaseModel):
 
106
 
107
 
108
  def format_prompt(user_text: str) -> str:
109
+
110
  return (
111
  f"{SYSTEM_PROMPT}"
112
+ f"<|im_start|>user\n"
113
+ f"{user_text}<|im_end|>\n"
114
  f"<|im_start|>assistant\n"
115
  )
116
 
117
 
118
  # ──────────────────────────────────────────────
119
+ # 5. Startup Warmup
120
  # ──────────────────────────────────────────────
121
  @app.on_event("startup")
122
  async def warmup():
123
+
124
+ print("Warming up model...")
125
+
 
 
 
 
 
126
  loop = asyncio.get_event_loop()
127
+
128
  await loop.run_in_executor(
129
  _executor,
130
+ lambda: llm(
131
+ format_prompt("hi"),
132
+ max_tokens=1,
133
+ stream=False,
134
+ ),
135
  )
136
+
137
+ print("Warmup complete.")
138
 
139
 
140
  # ──────────────────────────────────────────────
141
+ # 6. Full Response Endpoint
142
  # ────────────────────────────���─────────────────
143
  @app.post("/generate")
144
  async def generate_full(request: QueryRequest):
145
+
 
 
 
146
  loop = asyncio.get_event_loop()
147
+
148
  response = await loop.run_in_executor(
149
  _executor,
150
  lambda: llm(
 
155
  stop=["<|im_end|>", "<|im_start|>"],
156
  ),
157
  )
158
+
159
+ return {
160
+ "response": response["choices"][0]["text"]
161
+ }
162
 
163
 
164
  # ──────────────────────────────────────────────
165
+ # 7. Streaming Endpoint (FIXED)
166
  # ──────────────────────────────────────────────
167
  @app.post("/stream")
168
  async def generate_stream(request: QueryRequest):
169
+
170
+ formatted_prompt = format_prompt(
171
+ request.prompt
172
+ )
173
+
 
 
 
 
 
 
 
 
 
 
 
 
174
  loop = asyncio.get_event_loop()
175
+
176
  queue: asyncio.Queue = asyncio.Queue()
177
 
178
  def run_inference():
179
+
180
  try:
181
+
182
  stream = llm(
183
  formatted_prompt,
184
  max_tokens=request.max_tokens,
 
186
  temperature=request.temperature,
187
  stop=["<|im_end|>", "<|im_start|>"],
188
  )
189
+
190
+ full_text = ""
191
+
192
  for chunk in stream:
193
+
194
+ token = chunk["choices"][0]["text"]
195
+
196
+ if not token:
197
+ continue
198
+
199
+ # reconstruct proper spacing
200
+ full_text += token
201
+
202
+ asyncio.run_coroutine_threadsafe(
203
+ queue.put(full_text),
204
+ loop,
205
+ )
206
+
207
  finally:
208
+
209
+ asyncio.run_coroutine_threadsafe(
210
+ queue.put(None),
211
+ loop,
212
+ )
213
 
214
  async def stream_generator():
215
+
216
+ # break proxy buffering immediately
217
  yield f": {' ' * 2048}\n\n"
218
 
219
+ # instant UI feedback
 
220
  yield "data: ▍\n\n"
221
 
222
+ # start inference thread
223
+ loop.run_in_executor(
224
+ _executor,
225
+ run_inference,
226
+ )
227
+
228
+ previous_text = ""
229
 
 
 
230
  while True:
231
+
232
+ text = await queue.get()
233
+
234
+ if text is None:
235
  break
236
+
237
+ # stream only new text
238
+ delta = text[len(previous_text):]
239
+
240
+ previous_text = text
241
+
242
+ if delta:
243
+ yield f"data: {delta}\n\n"
244
 
245
  yield "data: [DONE]\n\n"
246
 
 
248
  stream_generator(),
249
  media_type="text/event-stream",
250
  headers={
251
+ "X-Accel-Buffering": "no",
252
  "Cache-Control": "no-cache",
253
  "Connection": "keep-alive",
254
+ "Content-Type":
255
+ "text/event-stream; charset=utf-8",
256
  },
257
  )
258
 
259
+
260
+ # ──────────────────────────────────────────────
261
+ # 8. Health Check
262
+ # ──────────────────────────────────────────────
263
  @app.get("/")
264
  def root():
265
+
266
+ return {
267
+ "status": "ok",
268
+ "model": MODEL_FILE,
269
+ "cache_dir": CACHE_DIR,
270
+ }
271
+
272
+
273
  # ──────────────────────────────────────────────
274
+ # 9. Entrypoint
275
  # ──────────────────────────────────────────────
276
  if __name__ == "__main__":
277
+
278
+ uvicorn.run(
279
+ app,
280
+ host="0.0.0.0",
281
+ port=7860,
282
+ )