dpv007 commited on
Commit
e66a5ee
Β·
verified Β·
1 Parent(s): b93868a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -19
app.py CHANGED
@@ -10,8 +10,6 @@ import uvicorn
10
  # ──────────────────────────────────────────────
11
  # 1. Model Configuration
12
  # ──────────────────────────────────────────────
13
- # Upgraded: 1.5B model β€” 3x smarter, fits easily in 16 GB free RAM
14
- # Switch back to 0.5B by changing these two lines if needed
15
  MODEL_REPO = "Qwen/Qwen2.5-1.5B-Instruct-GGUF"
16
  MODEL_FILE = "qwen2.5-1.5b-instruct-q4_k_m.gguf"
17
 
@@ -31,29 +29,28 @@ print("Tokenizing system prompt for n_keep...")
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
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=8, # max out CPU threads
41
- n_ctx=16384, # 16k context β€” long conversations, big documents
42
  n_keep=_system_token_count,
43
- n_batch=1024, # large batch = fastest prompt ingestion
44
- n_ubatch=512, # micro-batch for KV compute
45
- use_mmap=True, # memory-map weights β€” fast load, low overhead
46
- use_mlock=True, # lock ALL weights in RAM β€” zero swap risk
47
  verbose=False,
48
  )
49
 
50
- # 8 GB RAM cache β€” massive response reuse, near-instant repeat queries
51
  cache = LlamaRAMCache(capacity_bytes=8_589_934_592)
52
  llm.set_cache(cache)
53
  print("RAM cache initialized (8 GB).")
54
 
55
- # 4 parallel workers
56
- _executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)
 
57
 
58
  # ──────────────────────────────────────────────
59
  # 3. FastAPI App
@@ -76,15 +73,20 @@ def format_prompt(user_text: str) -> str:
76
 
77
 
78
  # ──────────────────────────────────────────────
79
- # 4. Startup Warmup β€” eliminates cold-start
80
  # ──────────────────────────────────────────────
81
  @app.on_event("startup")
82
  async def warmup():
83
- print("Warming up model (1 token)...")
84
  loop = asyncio.get_event_loop()
 
85
  await loop.run_in_executor(
86
  _executor,
87
- lambda: llm(format_prompt("hi"), max_tokens=1, stream=False),
 
 
 
 
88
  )
89
  print("Warmup complete. Server is ready.")
90
 
@@ -98,7 +100,7 @@ def root():
98
 
99
 
100
  # ──────────────────────────────────────────────
101
- # ENDPOINT 1: Full (non-streaming) response
102
  # ──────────────────────────────────────────────
103
  @app.post("/generate")
104
  async def generate_full(request: QueryRequest):
@@ -117,13 +119,16 @@ async def generate_full(request: QueryRequest):
117
 
118
 
119
  # ──────────────────────────────────────────────
120
- # ENDPOINT 2: True streaming (SSE)
121
  # ──────────────────────────────────────────────
122
  @app.post("/stream")
123
  async def generate_stream(request: QueryRequest):
124
  formatted_prompt = format_prompt(request.prompt)
125
  loop = asyncio.get_event_loop()
126
- queue: asyncio.Queue = asyncio.Queue()
 
 
 
127
 
128
  def run_inference():
129
  try:
@@ -137,12 +142,19 @@ async def generate_stream(request: QueryRequest):
137
  for chunk in stream:
138
  text = chunk["choices"][0]["text"]
139
  if text:
140
- asyncio.run_coroutine_threadsafe(queue.put(text), loop)
 
 
 
 
141
  finally:
142
  asyncio.run_coroutine_threadsafe(queue.put(None), loop)
143
 
144
  async def stream_generator():
 
145
  yield f": {' ' * 2048}\n\n"
 
 
146
  loop.run_in_executor(_executor, run_inference)
147
 
148
  while True:
@@ -150,6 +162,9 @@ async def generate_stream(request: QueryRequest):
150
  if token is None:
151
  break
152
  yield f"data: {token}\n\n"
 
 
 
153
 
154
  yield "data: [DONE]\n\n"
155
 
 
10
  # ──────────────────────────────────────────────
11
  # 1. Model Configuration
12
  # ──────────────────────────────────────────────
 
 
13
  MODEL_REPO = "Qwen/Qwen2.5-1.5B-Instruct-GGUF"
14
  MODEL_FILE = "qwen2.5-1.5b-instruct-q4_k_m.gguf"
15
 
 
29
  _tmp = Llama(model_path=model_path, n_ctx=64, verbose=False)
30
  _system_token_count = len(_tmp.tokenize(SYSTEM_PROMPT.encode()))
31
  del _tmp
 
32
  print(f"System prompt is {_system_token_count} tokens β†’ pinning in KV cache.")
33
 
34
  print("Loading model into memory...")
35
  llm = Llama(
36
  model_path=model_path,
37
+ n_threads=8,
38
+ n_ctx=16384,
39
  n_keep=_system_token_count,
40
+ n_batch=1024, # large batch = fastest prefill (prompt processing)
41
+ n_ubatch=512,
42
+ use_mmap=True,
43
+ use_mlock=True,
44
  verbose=False,
45
  )
46
 
 
47
  cache = LlamaRAMCache(capacity_bytes=8_589_934_592)
48
  llm.set_cache(cache)
49
  print("RAM cache initialized (8 GB).")
50
 
51
+ # llama.cpp is not thread-safe β€” single worker serializes calls correctly
52
+ # (multiple workers would corrupt state)
53
+ _executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
54
 
55
  # ──────────────────────────────────────────────
56
  # 3. FastAPI App
 
73
 
74
 
75
  # ──────────────────────────────────────────────
76
+ # 4. Startup Warmup β€” prime CPU caches & KV allocator
77
  # ──────────────────────────────────────────────
78
  @app.on_event("startup")
79
  async def warmup():
80
+ print("Warming up model...")
81
  loop = asyncio.get_event_loop()
82
+ # Warm with a realistic-length prompt so prefill path is fully primed
83
  await loop.run_in_executor(
84
  _executor,
85
+ lambda: llm(
86
+ format_prompt("Explain what recursion is in one sentence."),
87
+ max_tokens=4,
88
+ stream=False,
89
+ ),
90
  )
91
  print("Warmup complete. Server is ready.")
92
 
 
100
 
101
 
102
  # ──────────────────────────────────────────────
103
+ # ENDPOINT 1: Full response
104
  # ──────────────────────────────────────────────
105
  @app.post("/generate")
106
  async def generate_full(request: QueryRequest):
 
119
 
120
 
121
  # ──────────────────────────────────────────────
122
+ # ENDPOINT 2: Streaming (SSE)
123
  # ──────────────────────────────────────────────
124
  @app.post("/stream")
125
  async def generate_stream(request: QueryRequest):
126
  formatted_prompt = format_prompt(request.prompt)
127
  loop = asyncio.get_event_loop()
128
+
129
+ # Use a small queue (maxsize=1) so the inference thread blocks the moment
130
+ # the consumer (event loop) is not keeping up β€” prevents runaway buffering
131
+ queue: asyncio.Queue = asyncio.Queue(maxsize=1)
132
 
133
  def run_inference():
134
  try:
 
142
  for chunk in stream:
143
  text = chunk["choices"][0]["text"]
144
  if text:
145
+ # run_coroutine_threadsafe + result() makes the inference
146
+ # thread WAIT until the event loop has consumed this token
147
+ # before producing the next one β€” zero buffering delay
148
+ fut = asyncio.run_coroutine_threadsafe(queue.put(text), loop)
149
+ fut.result() # block until token is in the queue
150
  finally:
151
  asyncio.run_coroutine_threadsafe(queue.put(None), loop)
152
 
153
  async def stream_generator():
154
+ # Break Nginx / HF Space proxy buffer
155
  yield f": {' ' * 2048}\n\n"
156
+
157
+ # Start inference in background β€” don't await so we proceed immediately
158
  loop.run_in_executor(_executor, run_inference)
159
 
160
  while True:
 
162
  if token is None:
163
  break
164
  yield f"data: {token}\n\n"
165
+ # Force Uvicorn to flush this chunk to the network RIGHT NOW
166
+ # without this, the event loop may batch multiple tokens together
167
+ await asyncio.sleep(0)
168
 
169
  yield "data: [DONE]\n\n"
170