ArushCodes commited on
Commit
04f3ee0
·
verified ·
1 Parent(s): b0d31a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -49
app.py CHANGED
@@ -1,105 +1,124 @@
1
  import os
2
  import sys
 
 
3
  import multiprocessing
4
  import subprocess
5
 
6
  # ---------------------------------------------------------------------------
7
- # ⚡ 1. OS & CPU INSTRUCTION TUNING (Must be set BEFORE importing llama_cpp)
8
  # ---------------------------------------------------------------------------
9
- physical_cores = max(1, multiprocessing.cpu_count() // 2)
10
-
11
- # Lock math libraries strictly to physical CPU cores
12
- os.environ["OMP_NUM_THREADS"] = str(physical_cores)
13
- os.environ["MKL_NUM_THREADS"] = str(physical_cores)
14
- os.environ["OPENBLAS_NUM_THREADS"] = str(physical_cores)
15
- os.environ["VECLIB_MAXIMUM_THREADS"] = str(physical_cores)
16
 
17
- # Core Pinning: Prevents cross-core cache invalidation & context switches
 
 
 
18
  os.environ["OMP_PROC_BIND"] = "TRUE"
19
- os.environ["OMP_PLACES"] = "cores"
20
 
21
- # Install prebuilt CPU wheel and psutil for process priority
22
  subprocess.run([
23
  sys.executable, "-m", "pip", "install",
24
- "llama-cpp-python", "psutil",
25
  "--extra-index-url", "https://abetlen.github.io/llama-cpp-python/whl/cpu",
26
  ], check=True)
27
 
28
- import time
29
- import re
30
- import psutil
31
  import gradio as gr
32
  import llama_cpp
33
  from llama_cpp import Llama
34
  from huggingface_hub import hf_hub_download
35
 
36
- # ---------------------------------------------------------------------------
37
- # ⚡ 2. HIGH OS SCHEDULER PRIORITY
38
- # ---------------------------------------------------------------------------
39
  try:
40
  p = psutil.Process()
41
  if sys.platform == "win32":
42
  p.nice(psutil.HIGH_PRIORITY_CLASS)
43
  else:
44
- p.nice(-15) # Highest CPU scheduling priority on Linux/Mac
45
  except Exception:
46
  pass
47
 
48
- NUMA_STRATEGY = getattr(llama_cpp, "GGML_NUMA_STRATEGY_DISTRIBUTE", True)
 
 
 
49
 
50
- # Download GGUF Model
51
  model_path = hf_hub_download(
52
  "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF",
53
  "Qwen3-Coder-30B-A3B-Instruct-UD-IQ3_XXS.gguf",
54
  )
55
 
56
- # ---------------------------------------------------------------------------
57
- # ⚡ 3. MAXIMIZED CPU ENGINE CONFIGURATION
58
- # ---------------------------------------------------------------------------
59
  llm = Llama(
60
  model_path=model_path,
61
- n_gpu_layers=0,
62
  n_ctx=4096,
63
- chat_format="chatml",
64
 
65
- # Core Pinning & Scheduling
66
- n_threads=physical_cores, # Pure physical cores for text generation
67
- n_threads_batch=multiprocessing.cpu_count(), # Burst ALL logical cores for prompt evaluation
68
  numa=NUMA_STRATEGY,
69
 
70
- # RAM Pinning & Memory Bandwidth Maxing
71
- use_mlock=True, # Force model weights locked in physical RAM (no swap/disk paging)
72
- use_mmap=True, # High-speed direct memory mapping
 
 
 
73
 
74
- # Quantized KV Cache & Flash Attention
75
- flash_attn=True,
76
- type_k=llama_cpp.GGML_TYPE_Q4_0,
77
- type_v=llama_cpp.GGML_TYPE_Q4_0,
78
-
79
- # Batch Memory Alignment
80
- n_batch=512,
81
- n_ubatch=512,
82
  )
83
 
84
- # Clean thoughts and performance metadata from history
 
 
85
  def clean_assistant_reply(text):
86
  if not text:
87
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  cleaned = re.sub(r'<think>.*?</think>\n*', '', text, flags=re.DOTALL)
89
- cleaned = cleaned.replace('</think>', '')
 
 
90
  cleaned = re.sub(r'\n\n---\n\*⏱️.*?\*$', '', cleaned)
 
91
  return cleaned.strip()
92
 
 
 
 
93
  def respond(message, history, system_message, max_tokens, temperature, top_p):
94
  messages = [{"role": "system", "content": system_message}]
95
 
 
96
  for item in history:
97
  if isinstance(item, dict):
 
98
  content = item.get("content", "")
99
- if item.get("role") == "assistant":
100
  content = clean_assistant_reply(content)
101
- messages.append({"role": item.get("role"), "content": content})
102
-
103
  elif isinstance(item, (list, tuple)):
104
  if item[0]:
105
  messages.append({"role": "user", "content": item[0]})
@@ -126,6 +145,7 @@ def respond(message, history, system_message, max_tokens, temperature, top_p):
126
  token_count += 1
127
  yield response
128
 
 
129
  end_time = time.time()
130
  elapsed_time = end_time - start_time
131
 
@@ -135,6 +155,9 @@ def respond(message, history, system_message, max_tokens, temperature, top_p):
135
  response += stats_footer
136
  yield response
137
 
 
 
 
138
  chatbot = gr.ChatInterface(
139
  fn=respond,
140
  additional_inputs=[
@@ -143,9 +166,8 @@ chatbot = gr.ChatInterface(
143
  gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
144
  gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
145
  ],
146
- title="Qwopus 3.5 Coder (Max-Performance CPU Edition)",
147
  )
148
 
149
  if __name__ == "__main__":
150
- chatbot.launch()
151
-
 
1
  import os
2
  import sys
3
+ import time
4
+ import re
5
  import multiprocessing
6
  import subprocess
7
 
8
  # ---------------------------------------------------------------------------
9
+ # ⚡ 1. INSTALL & ENVIRONMENT TUNING
10
  # ---------------------------------------------------------------------------
11
+ # Auto-detect physical CPU cores to avoid hyperthreading contention
12
+ try:
13
+ import psutil
14
+ PHYSICAL_CORES = psutil.cpu_count(logical=False) or max(1, multiprocessing.cpu_count() // 2)
15
+ except Exception:
16
+ PHYSICAL_CORES = max(1, multiprocessing.cpu_count() // 2)
 
17
 
18
+ # Lock thread pools strictly to physical CPU cores
19
+ os.environ["OMP_NUM_THREADS"] = str(PHYSICAL_CORES)
20
+ os.environ["MKL_NUM_THREADS"] = str(PHYSICAL_CORES)
21
+ os.environ["OPENBLAS_NUM_THREADS"] = str(PHYSICAL_CORES)
22
  os.environ["OMP_PROC_BIND"] = "TRUE"
 
23
 
24
+ # Install prebuilt CPU wheel and dependencies at runtime
25
  subprocess.run([
26
  sys.executable, "-m", "pip", "install",
27
+ "llama-cpp-python", "psutil", "gradio", "huggingface_hub",
28
  "--extra-index-url", "https://abetlen.github.io/llama-cpp-python/whl/cpu",
29
  ], check=True)
30
 
 
 
 
31
  import gradio as gr
32
  import llama_cpp
33
  from llama_cpp import Llama
34
  from huggingface_hub import hf_hub_download
35
 
36
+ # Raise OS scheduler priority for the current process
 
 
37
  try:
38
  p = psutil.Process()
39
  if sys.platform == "win32":
40
  p.nice(psutil.HIGH_PRIORITY_CLASS)
41
  else:
42
+ p.nice(-15)
43
  except Exception:
44
  pass
45
 
46
+ # ---------------------------------------------------------------------------
47
+ # ⚡ 2. MODEL DOWNLOAD & LLAMA-CPP INITIALIZATION
48
+ # ---------------------------------------------------------------------------
49
+ NUMA_STRATEGY = getattr(llama_cpp, "GGML_NUMA_STRATEGY_DISTRIBUTE", False)
50
 
 
51
  model_path = hf_hub_download(
52
  "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF",
53
  "Qwen3-Coder-30B-A3B-Instruct-UD-IQ3_XXS.gguf",
54
  )
55
 
56
+ # Load GGUF model optimized for CPU & MoE execution
 
 
57
  llm = Llama(
58
  model_path=model_path,
59
+ n_gpu_layers=0, # 0 for CPU execution
60
  n_ctx=4096,
61
+ chat_format="chatml", # ChatML format prevents KV cache issues
62
 
63
+ # Threading optimizations
64
+ n_threads=PHYSICAL_CORES,
65
+ n_threads_batch=PHYSICAL_CORES,
66
  numa=NUMA_STRATEGY,
67
 
68
+ # Memory & Cache Management
69
+ use_mlock=False, # Set True if running locally with spare RAM
70
+ use_mmap=True,
71
+ flash_attn=False, # Disabled on CPU to reduce attention computation overhead
72
+ type_k=llama_cpp.GGML_TYPE_Q4_0, # Q4 KV cache cuts RAM consumption in half
73
+ type_v=llama_cpp.GGML_TYPE_Q4_0,
74
 
75
+ # Batch Memory Alignment (ubatch=64 prevents CPU L3 cache eviction)
76
+ n_batch=256,
77
+ n_ubatch=64,
 
 
 
 
 
78
  )
79
 
80
+ # ---------------------------------------------------------------------------
81
+ # ⚡ 3. ROBUST HISTORY CLEANER (FIXES GRADIO 5 TYPEERROR & THINK LOOPS)
82
+ # ---------------------------------------------------------------------------
83
  def clean_assistant_reply(text):
84
  if not text:
85
+ return ""
86
+
87
+ # Safely handle Gradio 5 / Multimodal list & dict formats
88
+ if isinstance(text, list):
89
+ extracted = []
90
+ for part in text:
91
+ if isinstance(part, str):
92
+ extracted.append(part)
93
+ elif isinstance(part, dict):
94
+ extracted.append(part.get("text", part.get("content", "")))
95
+ text = "".join(extracted)
96
+ elif not isinstance(text, str):
97
+ text = str(text)
98
+
99
+ # 1. Strip reasoning blocks (<think>...</think>)
100
  cleaned = re.sub(r'<think>.*?</think>\n*', '', text, flags=re.DOTALL)
101
+ cleaned = cleaned.replace("</think>", "")
102
+
103
+ # 2. Strip previous timing stats footers
104
  cleaned = re.sub(r'\n\n---\n\*⏱️.*?\*$', '', cleaned)
105
+
106
  return cleaned.strip()
107
 
108
+ # ---------------------------------------------------------------------------
109
+ # ⚡ 4. GRADIO RESPOND FUNCTION (WITH TOK/S TRACKING)
110
+ # ---------------------------------------------------------------------------
111
  def respond(message, history, system_message, max_tokens, temperature, top_p):
112
  messages = [{"role": "system", "content": system_message}]
113
 
114
+ # Parse chat history safely
115
  for item in history:
116
  if isinstance(item, dict):
117
+ role = item.get("role", "user")
118
  content = item.get("content", "")
119
+ if role == "assistant":
120
  content = clean_assistant_reply(content)
121
+ messages.append({"role": role, "content": content})
 
122
  elif isinstance(item, (list, tuple)):
123
  if item[0]:
124
  messages.append({"role": "user", "content": item[0]})
 
145
  token_count += 1
146
  yield response
147
 
148
+ # Calculate generation speed
149
  end_time = time.time()
150
  elapsed_time = end_time - start_time
151
 
 
155
  response += stats_footer
156
  yield response
157
 
158
+ # ---------------------------------------------------------------------------
159
+ # ⚡ 5. GRADIO INTERFACE LAUNCH
160
+ # ---------------------------------------------------------------------------
161
  chatbot = gr.ChatInterface(
162
  fn=respond,
163
  additional_inputs=[
 
166
  gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
167
  gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
168
  ],
169
+ title="Qwopus 3.5 Coder (Ultra-Optimized CPU/MoE Edition)",
170
  )
171
 
172
  if __name__ == "__main__":
173
+ chatbot.launch()