Kami574 commited on
Commit
54229cc
·
verified ·
1 Parent(s): a658097

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -16
app.py CHANGED
@@ -9,25 +9,26 @@ model_path = hf_hub_download(
9
  filename="Atlas-FirstAid.Q4_K_M.gguf"
10
  )
11
 
12
- # Load once at startup, not inside the GPU-decorated function.
13
- # Since this build is CPU-only, loading inside the GPU context
14
- # gave no benefit — it just added load time to the first request.
15
- llm = Llama(
16
- model_path=model_path,
17
- n_ctx=2048,
18
- n_threads=4, # bumped from 2 — ZeroGPU containers typically
19
- # have more CPU cores available than that
20
- n_batch=512, # faster prompt (input) processing
21
- n_gpu_layers=0, # explicit: this build has no CUDA, so don't
22
- # even attempt GPU offload — avoids wasted checks
23
- verbose=False,
24
- )
25
-
26
 
27
- @spaces.GPU(duration=20) # trimmed from 30 — shorter hold on the quota
28
  def chat_response(message, history):
 
 
 
 
 
 
 
 
 
 
 
 
29
  messages = []
30
 
 
31
  for msg in history:
32
  messages.append({
33
  "role": msg["role"],
@@ -39,14 +40,17 @@ def chat_response(message, history):
39
  "content": message,
40
  })
41
 
 
42
  response_stream = llm.create_chat_completion(
43
  messages=messages,
44
  temperature=0.7,
45
  max_tokens=512,
46
- stream=True
47
  )
48
 
49
  partial_message = ""
 
 
50
  for chunk in response_stream:
51
  if "choices" in chunk and chunk["choices"]:
52
  delta = chunk["choices"][0].get("delta", {})
 
9
  filename="Atlas-FirstAid.Q4_K_M.gguf"
10
  )
11
 
12
+ # Initialize globally as None
13
+ llm = None
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ @spaces.GPU(duration=30)
16
  def chat_response(message, history):
17
+ global llm
18
+
19
+ # Lazy load the model inside the GPU context so CUDA is detected
20
+ if llm is None:
21
+ llm = Llama(
22
+ model_path=model_path,
23
+ n_ctx=2048,
24
+ n_threads=2,
25
+ n_gpu_layers=-1,
26
+ verbose=False,
27
+ )
28
+
29
  messages = []
30
 
31
+ # Preserve conversation history (Gradio 5 dict format)
32
  for msg in history:
33
  messages.append({
34
  "role": msg["role"],
 
40
  "content": message,
41
  })
42
 
43
+ # Enable streaming for instant response times
44
  response_stream = llm.create_chat_completion(
45
  messages=messages,
46
  temperature=0.7,
47
  max_tokens=512,
48
+ stream=True
49
  )
50
 
51
  partial_message = ""
52
+
53
+ # Iterate through the stream and yield tokens instantly
54
  for chunk in response_stream:
55
  if "choices" in chunk and chunk["choices"]:
56
  delta = chunk["choices"][0].get("delta", {})