dpv007 commited on
Commit
941af88
Β·
verified Β·
1 Parent(s): 5d8db16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -38
app.py CHANGED
@@ -1,17 +1,11 @@
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,14 +20,10 @@ SYSTEM_PROMPT = (
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,
@@ -54,8 +44,7 @@ _system_token_count = len(
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
 
@@ -69,30 +58,22 @@ llm = Llama(
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"
@@ -116,7 +97,7 @@ def format_prompt(user_text: str) -> str:
116
 
117
 
118
  # ──────────────────────────────────────────────
119
- # 5. Startup Warmup
120
  # ──────────────────────────────────────────────
121
  @app.on_event("startup")
122
  async def warmup():
@@ -138,7 +119,7 @@ async def warmup():
138
 
139
 
140
  # ──────────────────────────────────────────────
141
- # 6. Full Response Endpoint
142
  # ──────────────────────────────────────────────
143
  @app.post("/generate")
144
  async def generate_full(request: QueryRequest):
@@ -162,7 +143,7 @@ async def generate_full(request: QueryRequest):
162
 
163
 
164
  # ──────────────────────────────────────────────
165
- # 7. Streaming Endpoint (FIXED)
166
  # ──────────────────────────────────────────────
167
  @app.post("/stream")
168
  async def generate_stream(request: QueryRequest):
@@ -196,7 +177,7 @@ async def generate_stream(request: QueryRequest):
196
  if not token:
197
  continue
198
 
199
- # reconstruct proper spacing
200
  full_text += token
201
 
202
  asyncio.run_coroutine_threadsafe(
@@ -213,13 +194,13 @@ async def generate_stream(request: QueryRequest):
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,
@@ -234,7 +215,7 @@ async def generate_stream(request: QueryRequest):
234
  if text is None:
235
  break
236
 
237
- # stream only new text
238
  delta = text[len(previous_text):]
239
 
240
  previous_text = text
@@ -258,7 +239,7 @@ async def generate_stream(request: QueryRequest):
258
 
259
 
260
  # ──────────────────────────���───────────────────
261
- # 8. Health Check
262
  # ──────────────────────────────────────────────
263
  @app.get("/")
264
  def root():
@@ -266,12 +247,11 @@ def root():
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
 
 
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
  "<|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,
 
44
  del _tmp
45
 
46
  print(
47
+ f"System prompt is {_system_token_count} tokens "
 
48
  f"β†’ pinning in KV cache."
49
  )
50
 
 
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"
 
97
 
98
 
99
  # ──────────────────────────────────────────────
100
+ # 4. Startup Warmup
101
  # ──────────────────────────────────────────────
102
  @app.on_event("startup")
103
  async def warmup():
 
119
 
120
 
121
  # ──────────────────────────────────────────────
122
+ # 5. Full Generation Endpoint
123
  # ──────────────────────────────────────────────
124
  @app.post("/generate")
125
  async def generate_full(request: QueryRequest):
 
143
 
144
 
145
  # ──────────────────────────────────────────────
146
+ # 6. Streaming Endpoint (FIXED)
147
  # ──────────────────────────────────────────────
148
  @app.post("/stream")
149
  async def generate_stream(request: QueryRequest):
 
177
  if not token:
178
  continue
179
 
180
+ # Properly reconstruct text
181
  full_text += token
182
 
183
  asyncio.run_coroutine_threadsafe(
 
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,
 
215
  if text is None:
216
  break
217
 
218
+ # Send only new delta
219
  delta = text[len(previous_text):]
220
 
221
  previous_text = text
 
239
 
240
 
241
  # ──────────────────────────���───────────────────
242
+ # 7. Health Check
243
  # ──────────────────────────────────────────────
244
  @app.get("/")
245
  def root():
 
247
  return {
248
  "status": "ok",
249
  "model": MODEL_FILE,
 
250
  }
251
 
252
 
253
  # ──────────────────────────────────────────────
254
+ # 8. Entrypoint
255
  # ──────────────────────────────────────────────
256
  if __name__ == "__main__":
257