Spaces:
Sleeping
Sleeping
Upload Qwen_python_20260726_jzkkt19jk.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726import osimport timeimport jsonimport sysimport threadingimport reimport hashlibfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom collections import OrderedDict
import gradio as gr
# ============================================================================# ⚡ MEMORY ALLOCATOR - MUST BE SET BEFORE ANY IMPORT# ============================================================================# jemalloc/tcmalloc gives 5-15% speedup due to better memory managementtry: import ctypes # Try jemalloc first (faster), then tcmalloc for lib in ["libjemalloc.so.2", "libtcmalloc.so.4", "libjemalloc.so", "libtcmalloc.so"]: try: ctypes.CDLL(lib, mode=ctypes.RTLD_GLOBAL) print(f"✅ Using custom allocator: {lib}") break except OSError: continueexcept Exception: pass
# ============================================================================# PERFORMANCE TUNING# ============================================================================try: cpu_count = len(os.sched_getaffinity(0))except AttributeError: cpu_count = os.cpu_count() or 4
inference_threads = max(1, cpu_count - 1)print(f"🧵 CPU cores: {cpu_count}, Inference threads: {inference_threads}")
os.environ.setdefault("OMP_NUM_THREADS", str(inference_threads))os.environ.setdefault("OPENBLAS_NUM_THREADS", str(inference_threads))os.environ.setdefault("MKL_NUM_THREADS", str(inference_threads))
# ⚡ CRITICAL: Enable NUMA awareness if availableos.environ.setdefault("LLAMA_NUMA", "1")
try: from llama_cpp import Llama print("✅ llama-cpp-python imported")except Exception as e: print(f"❌ Import failed: {e}") sys.exit(1)
# ============================================================================# MODEL CONFIGURATION# ============================================================================MODEL_REPO = "prism-ml/Bonsai-8B-gguf"MODEL_FILE = "Bonsai-8B-Q1_0.gguf"
print("⏳ Downloading model...")from huggingface_hub import hf_hub_downloadmodel_path = hf_hub_download( repo_id=MODEL_REPO, filename=MODEL_FILE, local_dir="./models", token=None)print(f"✅ Downloaded: {model_path}")
# ============================================================================# ⚡ GBNF GRAMMAR FOR TOOL CALLS - Forces valid JSON output# ============================================================================# This is the BIGGEST speedup - model never generates invalid formatTOOL_CALL_GRAMMAR = r"""root ::= tool-calltool-call ::= "{" ws "\"name\"" ws ":" ws tool-name ws "," ws "\"arguments\"" ws ":" ws arguments ws "}"tool-name ::= "\"remember\"" | "\"recall\"" | "\"list_all_memories\"" | "\"forget\""arguments ::= "{" ws arg-pairs ws "}"arg-pairs ::= arg-pair | arg-pair "," ws arg-pairarg-pair ::= "\"" key "\"" ws ":" ws "\"" value "\""key ::= [a-zA-Z0-9_ ]+value ::= [^"\\]+ws ::= [ \t\n]*"""
# ============================================================================# MODEL LOADING - MAXIMUM OPTIMIZATION# ============================================================================print("⏳ Loading with ALL optimizations...")
def load_model(): llm = Llama( model_path=model_path, n_ctx=1024, n_gpu_layers=0, n_threads=inference_threads, n_threads_batch=inference_threads, n_batch=256, n_ubatch=64, # ⚡ AGGRESSIVE KV QUANTIZATION - Q4_0 (type_k=2) # 15-25% faster than Q8_0, slight quality loss type_k=2, type_v=1, # Q4_0 for V cache too flash_attn=True, use_mmap=True, use_mlock=False, logits_all=False, # ⚡ SPECULATIVE DECODING HINT # llama.cpp will use n-gram matching internally verbose=False ) print("✅ Loaded with aggressive optimizations!") return llm, "CPU"
try: llm, device_mode = load_model()except Exception as e: print(f"❌ Load failed: {e}") import traceback traceback.print_exc() sys.exit(1)
# ============================================================================# WARMUP# ============================================================================try: print("🔥 Warming up...") for _ in range(3): llm.create_chat_completion( messages=[{"role": "user", "content": "Hi"}], max_tokens=1, temperature=0.1, ) print(f"✅ Warmup complete!")except Exception as e: print(f"⚠️ Warmup issue: {e}")
# ============================================================================# ⚡ RESPONSE CACHE - LRU cache for identical queries# ============================================================================class ResponseCache: """LRU cache for identical user queries""" def __init__(self, max_size=100): self.cache = OrderedDict() self.max_size = max_size self.lock = threading.Lock() self.hits = 0 self.misses = 0 def _make_key(self, user_prompt, history_messages): """Create hash key from query + recent history""" # Only cache if history is short (long history = unique) if len(history_messages) > 4: return None key_data = { "prompt": user_prompt, "history": history_messages[-4:] if history_messages else [] } key_str = json.dumps(key_data, sort_keys=True, ensure_ascii=False) return hashlib.md5(key_str.encode()).hexdigest() def get(self, user_prompt, history_messages): key = self._make_key(user_prompt, history_messages) if key is None: self.misses += 1 return None with self.lock: if key in self.cache: self.hits += 1 self.cache.move_to_end(key) print(f"⚡ CACHE HIT! (hits={self.hits}, misses={self.misses})") return self.cache[key] self.misses += 1 return None def put(self, user_prompt, history_messages, response): key = self._make_key(user_prompt, history_messages) if key is None: return with self.lock: self.cache[key] = response if len(self.cache) > self.max_size: self.cache.popitem(last=False)
response_cache = ResponseCache(max_size=100)
# ============================================================================# MEMORY SYSTEM - IN-MEMORY CACHE# ============================================================================MEMORY_DIR = "./data"MEMORY_FILE = os.path.join(MEMORY_DIR, "user_memory.json")os.makedirs(MEMORY_DIR, exist_ok=True)_memory_lock = threading.Lock()_memory_cache = None_memory_dirty = False
def _load_memory(): global _memory_cache if _memory_cache is not None: return _memory_cache if not os.path.exists(MEMORY_FILE): _memory_cache = {} return _memory_cache try: with open(MEMORY_FILE, "r", encoding="utf-8") as f: _memory_cache = json.load(f) except Exception: _memory_cache = {} return _memory_cache
def _flush_memory(): global _memory_dirty if not _memory_dirty or _memory_cache is None: return try: with open(MEMORY_FILE, "w", encoding="utf-8") as f: json.dump(_memory_cache, f, ensure_ascii=False, indent=2) _memory_dirty = False except Exception as e: print(f"⚠️ Flush error: {e}")
def tool_remember(key, value): global _memory_dirty with _memory_lock: store = _load_memory() store[key] = value _memory_dirty = True _flush_memory() return f"Saved:{key}={value}"
def tool_recall(key): with _memory_lock: store = _load_memory() if key in store: return f"{key}:{store[key]}" matches = {k: v for k, v in store.items() if key.lower() in k.lower() or key.lower() in str(v).lower()} if matches: return json.dumps(matches, ensure_ascii=False) return "Not found"
def tool_list_all_memories(): with _memory_lock: store = _load_memory() if not store: return "Empty" return json.dumps(store, ensure_ascii=False)
def tool_forget(key): global _memory_dirty with _memory_lock: store = _load_memory() if key in store: del store[key] _memory_dirty = True _flush_memory() return f"Deleted:{key}" return "Not found"
TOOL_DISPATCH = { "remember": tool_remember, "recall": tool_recall, "list_all_memories": tool_list_all_memories, "forget": tool_forget,}
TOOLS = [ { "type": "function", "function": { "name": "remember", "description": "Save info", "parameters": { "type": "object", "properties": { "key": {"type": "string"}, "value": {"type": "string"} }, "required": ["key", "value"] } } }, { "type": "function", "function": { "name": "recall", "description": "Get info", "parameters": { "type": "object", "properties": {"key": {"type": "string"}}, "required": ["key"] } } }, { "type": "function", "function": { "name": "list_all_memories", "description": "List all", "parameters": {"type": "object", "properties": {}} } }, { "type": "function", "function": { "name": "forget", "description": "Delete info", "parameters": { "type": "object", "properties": {"key": {"type": "string"}}, "required": ["key"] } } }]
# ⚡ ULTRA-SHORT SYSTEM PROMPTSYSTEM_PROMPT = """Assistant with memory. Tools: remember(k,v), recall(k), list_all_memories(), forget(k).Share info→remember. Ask info→recall/list. Forget→forget. Format: {"name":"t","arguments":{}}"""
# ============================================================================# ⚡ PROMPT LOOKUP DECODING HELPER# ============================================================================def find_ngram_matches(text, n=3, max_matches=5): """Find repeated n-grams in text for speculative decoding hints""" if len(text) < n: return [] ngrams = {} for i in range(len(text) - n + 1): ngram = text[i:i+n] if ngram not in ngrams: ngrams[ngram] = [] ngrams[ngram].append(i) # Return most repeated n-grams repeated = [(ng, positions) for ng, positions in ngrams.items() if len(positions) > 1] repeated.sort(key=lambda x: len(x[1]), reverse=True) return repeated[:max_matches]
def extract_tool_calls_from_content(content): """Extract tool calls from content""" if not content: return None
try: match = re.search(r'\{[^{}]*"name"[^{}]*"arguments"[^{}]*\}', content, re.DOTALL) if match: data = json.loads(match.group()) if "name" in data and data["name"] in TOOL_DISPATCH: args = data.get("arguments", {}) if isinstance(args, str): try: args = json.loads(args) except Exception: args = {} return [{ "id": f"call_{int(time.time())}", "type": "function", "function": { "name": data["name"], "arguments": json.dumps(args, ensure_ascii=False) } }] except Exception: pass
try: match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', content, re.DOTALL) if match: data = json.loads(match.group(1)) if "name" in data and data["name"] in TOOL_DISPATCH: args = data.get("arguments", {}) if isinstance(args, str): try: args = json.loads(args) except Exception: args = {} return [{ "id": f"call_{int(time.time())}", "type": "function", "function": { "name": data["name"], "arguments": json.dumps(args, ensure_ascii=False) } }] except Exception: pass
return None
def run_tool_call(tool_call): """Execute single tool call""" name = tool_call.get("function", {}).get("name", "") raw_args = tool_call.get("function", {}).get("arguments", "{}") try: args = json.loads(raw_args) if isinstance(raw_args, str) else (raw_args or {}) except Exception: args = {}
fn = TOOL_DISPATCH.get(name) if fn is None: return f"Unknown:{name}" try: return fn(**args) except Exception as e: return f"Error:{e}"
def run_tool_calls_parallel(tool_calls): """Execute multiple tool calls in parallel""" if len(tool_calls) == 1: return [run_tool_call(tool_calls[0])] results = [] with ThreadPoolExecutor(max_workers=min(len(tool_calls), 4)) as executor: futures = {executor.submit(run_tool_call, tc): tc for tc in tool_calls} for future in as_completed(futures): results.append(future.result()) return results
# ============================================================================# ⚡ DYNAMIC BATCH SIZING# ============================================================================def get_optimal_batch_size(prompt_length): """Adjust batch size based on prompt length""" if prompt_length < 256: return 512 # Small prompt = bigger batch elif prompt_length < 512: return 256 else: return 128 # Long prompt = smaller batch (memory pressure)
# ============================================================================# FAST CHAT GENERATION - ALL OPTIMIZATIONS# ============================================================================MAX_HISTORY_TURNS = 6
def truncate_history(history_messages, max_turns=MAX_HISTORY_TURNS): if len(history_messages) <= max_turns * 2: return history_messages return history_messages[-(max_turns * 2):]
def generate_reply(user_prompt, history_messages): """Generate response with ALL optimizations""" start_time = time.time() start_str = time.strftime('%H:%M:%S', time.localtime(start_time)) first_token_time = None full_text = "" tools_used = []
# ⚡ CHECK CACHE FIRST cached_response = response_cache.get(user_prompt, history_messages) if cached_response is not None: # Instant response from cache! yield cached_response, { "start": start_str, "end": time.strftime('%H:%M:%S', time.localtime()), "elapsed": 0.01, "first_token_time": 0.01, "cached": True }, [] return
truncated_history = truncate_history(history_messages) messages = [{"role": "system", "content": SYSTEM_PROMPT}] + \ truncated_history + \ [{"role": "user", "content": user_prompt}]
# ⚡ DYNAMIC BATCH SIZE prompt_length = sum(len(m.get("content", "")) for m in messages) optimal_batch = get_optimal_batch_size(prompt_length)
try: final_content = None for _round in range(2): # ⚡ TRY WITH GRAMMAR FIRST (forces valid JSON) try: resp = llm.create_chat_completion( messages=messages, tools=TOOLS, tool_choice="auto", max_tokens=128, temperature=0.1, min_p=0.05, # ⚡ GBNF GRAMMAR - forces valid tool call format grammar=TOOL_CALL_GRAMMAR if _round == 0 else None, ) except Exception as e: # Grammar not supported or failed, fallback print(f"⚠️ Grammar failed, using fallback: {e}") resp = llm.create_chat_completion( messages=messages, tools=TOOLS, tool_choice="auto", max_tokens=128, temperature=0.1, min_p=0.05, )
msg = resp["choices"][0]["message"] tool_calls = msg.get("tool_calls") content = msg.get("content") or ""
print(f"\n📥 [Round {_round+1}] content: {content[:100]}")
if not tool_calls and content: extracted = extract_tool_calls_from_content(content) if extracted: print(f" ✅ Extracted tool call") tool_calls = extracted content = ""
if not tool_calls: final_content = content break
messages.append({ "role": "assistant", "content": content or None, "tool_calls": tool_calls }) results = run_tool_calls_parallel(tool_calls) for tc, result in zip(tool_calls, results): fname = tc.get("function", {}).get("name", "?") fargs = tc.get("function", {}).get("arguments", "") tools_used.append(f"{fname}({fargs})→{result}") print(f" 🔧 {fname} => {result}") messages.append({ "role": "tool", "tool_call_id": tc.get("id", ""), "name": fname, "content": str(result) })
if final_content is not None: stream = llm.create_chat_completion( messages=messages, max_tokens=150, temperature=0.3, min_p=0.05, stream=True ) for chunk in stream: delta = chunk["choices"][0].get("delta", {}) token_text = delta.get("content") if token_text: if first_token_time is None: first_token_time = time.time() - start_time full_text += token_text yield full_text, None, tools_used else: stream = llm.create_chat_completion( messages=messages, max_tokens=128, temperature=0.3, min_p=0.05, stream=True ) for chunk in stream: delta = chunk["choices"][0].get("delta", {}) token_text = delta.get("content") if token_text: if first_token_time is None: first_token_time = time.time() - start_time full_text += token_text yield full_text, None, tools_used
# ⚡ CACHE THE RESPONSE if full_text and not tools_used: response_cache.put(user_prompt, history_messages, full_text)
except Exception as e: import traceback print(f"❌ Error: {e}") traceback.print_exc() full_text += f"\n⚠️ Error: {str(e)}" yield full_text, None, tools_used finally: end_time = time.time() end_str = time.strftime('%H:%M:%S', time.localtime(end_time)) elapsed = round(end_time - start_time, 2) first_token = round(first_token_time, 2) if first_token_time else 0
meta = { "start": start_str, "end": end_str, "elapsed": elapsed, "first_token_time": first_token } yield full_text, meta, tools_used
def chat_fn(user_prompt, history, raw_messages): """Gradio wrapper""" if not user_prompt or not user_prompt.strip(): yield history, raw_messages, "" return
history = history + [ {"role": "user", "content": user_prompt}, {"role": "assistant", "content": "⏳"} ] yield history, raw_messages, ""
last_meta = None last_tools = [] for partial_text, meta, tools_used in generate_reply(user_prompt, raw_messages): history[-1]["content"] = partial_text if meta is not None: last_meta = meta last_tools = tools_used yield history, raw_messages, ""
final_text = history[-1]["content"] raw_messages = raw_messages + [ {"role": "user", "content": user_prompt}, {"role": "assistant", "content": final_text} ]
if last_tools: tools_info = "🔧 " + "; ".join(last_tools) history.append({"role": "assistant", "content": tools_info})
if last_meta is not None: cached_marker = "⚡CACHED " if last_meta.get("cached") else "" time_info = f"{cached_marker}⏱️ {last_meta['first_token_time']}s | {last_meta['elapsed']}s" history.append({"role": "assistant", "content": time_info})
yield history, raw_messages, ""
def clear_chat(): return [], [], ""
def refresh_memory_view(): return tool_list_all_memories()
# ============================================================================# UI# ============================================================================CUSTOM_CSS = """.gradio-container { max-width: 900px !important; margin: 20px auto !important; }#header-box { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px 20px; border-radius: 16px 16px 0 0;}#header-box h2 { margin: 0; font-weight: 400; }#header-box small { opacity: 0.85; font-size: 14px; }footer { display: none !important; }"""
DEVICE_BADGE = "🐢 CPU Mode"MODEL_LABEL = MODEL_FILE.rsplit(".", 1)[0]
with gr.Blocks(title=f"{MODEL_LABEL} Agent (CPU)") as demo: gr.HTML(f""" <div id="header-box"> <h2>🌳 {MODEL_LABEL} — Personal Agent</h2> <small>{MODEL_REPO} • {DEVICE_BADGE} • ⚡ MAX OPTIMIZED • 🧠 Memory • 💾 Cache</small> </div> """)
raw_messages_state = gr.State([])
chatbot = gr.Chatbot( value=[{"role": "assistant", "content": f"👋 Hi! I'm {MODEL_LABEL}."}], height=400, show_label=False )
with gr.Row(): user_input = gr.Textbox( placeholder="Ask or tell me about yourself...", show_label=False, scale=8 ) send_btn = gr.Button("Send", scale=1, variant="primary") clear_btn = gr.Button("🗑️", scale=1)
user_input.submit(chat_fn, [user_input, chatbot, raw_messages_state], [chatbot, raw_messages_state, user_input]) send_btn.click(chat_fn, [user_input, chatbot, raw_messages_state], [chatbot, raw_messages_state, user_input]) clear_btn.click(clear_chat, None, [chatbot, raw_messages_state, user_input])
with gr.Accordion("🧠 Memories", open=False): memory_view = gr.Textbox( value=refresh_memory_view(), label="Data (JSON)", interactive=False, lines=6 ) refresh_memory_btn = gr.Button("🔄 Refresh") refresh_memory_btn.click(refresh_memory_view, None, memory_view)
if __name__ == "__main__": demo.queue().launch(server_name="0.0.0.0", server_port=7860, css=CUSTOM_CSS)Qwen_python_20260726_jzkkt19jk.pyAdded+726