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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +189 -140
app.py CHANGED
@@ -1,156 +1,205 @@
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(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
+ Key design decisions
126
+ ────────────────────
127
+ β€’ Inference runs in _executor (thread pool) so llama.cpp never
128
+ blocks the async event loop β€” the event loop can flush bytes
129
+ to the network between tokens instead of batching them.
130
+ β€’ asyncio.Queue bridges the sync inference thread and the
131
+ async generator that feeds StreamingResponse.
132
+ β€’ 2 KB SSE comment breaks Nginx / HF Space's proxy buffer
133
+ immediately so the client sees bytes without waiting for a
134
+ full buffer to fill.
135
+ β€’ A blinking-cursor token is sent right away so the UI feels
136
+ responsive before the first real token arrives.
137
+ """
138
+ formatted_prompt = format_prompt(request.prompt)
139
+ loop = asyncio.get_event_loop()
140
+ queue: asyncio.Queue = asyncio.Queue()
141
+
142
+ def run_inference():
143
+ """Runs in thread pool; puts tokens into the async queue."""
144
+ try:
145
+ stream = llm(
146
+ formatted_prompt,
147
+ max_tokens=request.max_tokens,
148
+ stream=True,
149
+ temperature=request.temperature,
150
+ stop=["<|im_end|>", "<|im_start|>"],
151
+ )
152
+ for chunk in stream:
153
+ text = chunk["choices"][0]["text"]
154
+ if text:
155
+ asyncio.run_coroutine_threadsafe(queue.put(text), loop)
156
+ finally:
157
+ # Always send sentinel so the generator can exit cleanly
158
+ asyncio.run_coroutine_threadsafe(queue.put(None), loop)
159
+
160
+ async def stream_generator():
161
+ # Break proxy/Nginx buffer immediately
162
+ yield f": {' ' * 2048}\n\n"
163
+
164
+ # Show a cursor so the UI isn't blank while the first token
165
+ # is being computed (forward pass over the full prompt)
166
+ yield "data: ▍\n\n"
167
+
168
+ # Kick off inference in the background thread
169
+ loop.run_in_executor(_executor, run_inference)
170
+
171
+ # Overwrite the placeholder cursor with the real stream
172
+ first = True
173
+ while True:
174
+ token = await queue.get()
175
+ if token is None:
176
+ break
177
+ if first:
178
+ # Clear the cursor by prepending a backspace-width span
179
+ # (works in most chat UIs; harmless if it doesn't)
180
+ yield f"data: \r{token}\n\n"
181
+ first = False
182
+ else:
183
+ yield f"data: {token}\n\n"
184
+
185
+ yield "data: [DONE]\n\n"
186
+
187
+ return StreamingResponse(
188
+ stream_generator(),
189
+ media_type="text/event-stream",
190
+ headers={
191
+ "X-Accel-Buffering": "no", # disable Nginx buffering
192
+ "Cache-Control": "no-cache",
193
+ "Connection": "keep-alive",
194
+ "Content-Type": "text/event-stream; charset=utf-8",
195
+ },
196
+ )
197
+
198
+ @app.get("/")
199
+ def root():
200
+ return {"status": "ok", "model": MODEL_FILE}
201
+ # ────────────────────────��─────────────────────
202
+ # 5. Entrypoint
203
+ # ──────────────────────────────────────────────
204
+ if __name__ == "__main__":
205
+ uvicorn.run(app, host="0.0.0.0", port=7860)