Spaces:
Sleeping
Sleeping
Update app.py
Browse files35 unmodified lines3637383940414243444546474849505172 unmodified lines1241251261271281297 unmodified lines13713813914014114233 unmodified lines1761771781791801811821831841851861871887 unmodified lines1961971981992002012022032042052062072081 unmodified line2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782793 unmodified lines28328428528628728828929029129229329429529629729829930077 unmodified lines37837938038138238338411 unmodified lines396397398399400401402403404405406407144 unmodified lines55255355455555655755855956056156256356456557 unmodified lines62362462562662762835 unmodified linesKV_CACHE_QUANTIZATION = True # Quantize KV cache (4-bit)CONTINUOUS_BATCHING = True # Enable continuous batchingSPECULATIVE_DECODE = False # Disabled for CPU (requires draft model)MLOCK_MODEL = True # Lock model in RAM (prevent swap)USE_MMAP = True # Memory-mapped file loadingOFFLOAD_KQV = False # CPU-only, no offload neededOPTIMAL_THREADS = max(1, psutil.cpu_count(logical=False) - 1) # Physical cores - 1ROPE_SCALING = 1.0 # RoPE frequency scalingNUMA_OPTIMIZE = True # NUMA-aware memory allocationlogging.basicConfig(level=logging.INFO, format='%(asctime)s - ZEROENGINE - %(message)s')logger = logging.getLogger(__name__)# --- TELEMETRY MODULE ---class TelemetryManager:def __init__(self, api: HfApi):72 unmodified linesself.auto_cleanup_thread = Noneself.start_idle_monitor()def start_idle_monitor(self):"""Start background thread to monitor idle timeout"""def monitor():7 unmodified linesdel self.llmself.llm = Noneself.active_model_info = {"repo": "", "file": ""}logger.info("[IDLE] Model unloaded successfully")except Exception as e:logger.error(f"[IDLE] Cleanup error: {e}")33 unmodified linesreturn []def boot_kernel(self, repo: str, filename: str) -> str:"""HYPER-OPTIMIZED Boot kernel with all speed optimizations enabled"""try:if not repo or not filename:return "π΄ ERROR: Repository or filename missing"logger.info(f"[BOOT] Starting download: {filename} from {repo}")# Download with timeout protectiontry:path = hf_hub_download(7 unmodified lineslogger.error(f"[BOOT] Download failed: {e}")return f"π΄ DOWNLOAD FAILED: {str(e)}"# Validate before loadingvalid, msg = ResourceMonitor.validate_deployment(path)if not valid:logger.warning(f"[BOOT] Validation failed: {msg}")return f"π΄ VALIDATION FAILED: {msg}"logger.info("[BOOT] Validation passed, applying optimizations...")# Apply NUMA optimizationif NUMA_OPTIMIZE:1 unmodified line# Load model with MAXIMUM PERFORMANCE SETTINGSwith self.kernel_lock:# Clear previous modelif self.llm:logger.info("[BOOT] Clearing previous model...")try:del self.llmself.llm = Noneexcept Exception as e:logger.warning(f"[BOOT] Cleanup warning: {e}")# Calculate optimal batch size based on available RAMvm = psutil.virtual_memory()available_ram_gb = vm.available / (1024**3)# Dynamic batch sizing: more RAM = larger batchesoptimal_batch = min(512, int(128 * available_ram_gb / 4))try:logger.info(f"[BOOT] Initializing with {OPTIMAL_THREADS} threads, batch={optimal_batch}")# ULTRA-OPTIMIZED LLAMA.CPP INITIALIZATIONself.llm = Llama(model_path=path,n_ctx=4096, # Increased context windown_threads=OPTIMAL_THREADS, # Optimized thread countn_threads_batch=OPTIMAL_THREADS, # Batch processing threadsuse_mmap=USE_MMAP, # Memory-mapped weights (fast loading)use_mlock=MLOCK_MODEL, # Lock in RAM (prevent swap thrashing)n_batch=optimal_batch, # Dynamic batch sizen_gpu_layers=0, # CPU-only modeflash_attn=FLASH_ATTENTION, # Flash Attention (2x faster)type_k=2 if KV_CACHE_QUANTIZATION else None, # Q4 KV cache quantizationtype_v=2 if KV_CACHE_QUANTIZATION else None, # Q4 KV cache quantizationrope_scaling_type=0, # Linear RoPE scalingrope_freq_scale=ROPE_SCALING, # RoPE frequency scalenuma=NUMA_OPTIMIZE, # NUMA optimizationverbose=False,logits_all=False, # Only compute final logits (faster)embedding=False, # Disable embeddings (not needed)offload_kqv=OFFLOAD_KQV, # No offload on CPUf16_kv=False # Use quantized KV cache instead)self.active_model_info = {"repo": repo, "file": filename}self.telemetry.track_load(repo, filename)# Warm-up inference to populate cacheslogger.info("[BOOT] Warming up model caches...")try:self.llm("Test", max_tokens=1, stream=False)except:passlogger.info("[BOOT] π HYPER-OPTIMIZED MODEL READY!")return f"π’ KERNEL ONLINE: {filename} | Threads: {OPTIMAL_THREADS} | Batch: {optimal_batch} | Flash Attn: {FLASH_ATTENTION}"except Exception as e:logger.error(f"[BOOT] Model loading failed: {e}")self.llm = Nonereturn f"π΄ LOAD FAILED: {str(e)}"except Exception as e:logger.error(f"[BOOT] Unexpected error: {e}")return f"π΄ BOOT FAILURE: {str(e)}"def stitch_cache(self, ghost_text: str) -> str:if not self.llm or not ghost_text or self.is_prefilling:return "Kernel Idle/Busy"3 unmodified linestokens = self.llm.tokenize(ghost_text.encode("utf-8"))self.llm.eval(tokens)logger.info(f"Ghost cache primed: {len(tokens)} tokens")except Exception as e:logger.error(f"KV Cache priming failed: {e}")finally:self.is_prefilling = Falsethreading.Thread(target=_bg_eval, daemon=True).start()return "β‘ Ghost Cache Primed"def inference_generator(self, prompt: str, history: List[Dict], ghost_context: str, repo: str, quant: str) -> Generator:# Update activity timestampself.update_activity()# AUTO-BOOT: If model not loaded, auto-boot default modelif not self.llm:logger.info("[AUTO-BOOT] No model loaded, initiating auto-boot...")77 unmodified linesself.perf_stats["peak_tps"] = tps# Update history with streaming content + performance metricshistory[-1]["content"] = f"{response_text}\n\n`β‘ {tps} t/s | π― Peak: {self.perf_stats['peak_tps']:.1f} t/s`"yield history# Update global performance stats11 unmodified linesself.telemetry.track_generation(tokens_count)logger.info(f"β Generation complete: {tokens_count} tokens @ {tps:.1f} t/s (TTFT: {first_token_time*1000:.0f}ms)")except Exception as e:logger.error(f"Inference error: {e}")history[-1]["content"] = f"π΄ Runtime Error: {str(e)}"yield history# --- CUSTOM CSS ---CUSTOM_CSS = """144 unmodified linesboot_status = gr.Markdown("Status: `STANDBY`")gr.Markdown("---")gr.Markdown("### π» Ghost Cache")ghost_buffer = gr.Textbox(label="Background Context",placeholder="Queue priming tokens here...",lines=3)stitch_status = gr.Markdown("Cache: `EMPTY`")stitch_btn = gr.Button("STITCH", size="sm")log_output = gr.Code(label="Kernel Logs",57 unmodified lines[stitch_status])# Auto-boot enabled inference - passes repo and quant for auto-bootinference_args = [user_input, chat_box, ghost_buffer, repo_input, quant_dropdown]user_input.submit(kernel.inference_generator, inference_args, [chat_box])35 unmodified lines3637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421572 unmodified lines2882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413427 unmodified lines35035135235335435535633 unmodified lines3903913923933943953963973983994004014024034044057 unmodified lines4134144154164174184194204214224234244254264274284291 unmodified line4314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335343 unmodified lines53853954054154254354454554654754854955055155255355455555655755855977 unmodified lines63763863964064164264311 unmodified lines655656657658659660661662663664665666667668669670144 unmodified lines81581681781881982082182282382482582682782882957 unmodified lines88788888989089189289389489589689789889935 unmodified linesKV_CACHE_QUANTIZATION = True # Quantize KV cache (4-bit)CONTINUOUS_BATCHING = True # Enable continuous batchingSPECULATIVE_DECODE = False # Disabled for CPU (requires draft model)MLOCK_MODEL = False # Disabled: prevents swapping but uses more RAMUSE_MMAP = True # Memory-mapped file loadingOFFLOAD_KQV = False # CPU-only, no offload neededOPTIMAL_THREADS = max(1, psutil.cpu_count(logical=False) - 1) # Physical cores - 1ROPE_SCALING = 1.0 # RoPE frequency scalingNUMA_OPTIMIZE = True # NUMA-aware memory allocationAGGRESSIVE_GC = True # Aggressive garbage collection# Quantization detection and optimization mappingQUANT_OPTIMIZATIONS = {"BF16": {"batch_multiplier": 0.3, "ctx_size": 8192, "threads_boost": 1.2},"F16": {"batch_multiplier": 0.4, "ctx_size": 8192, "threads_boost": 1.2},"Q8_0": {"batch_multiplier": 0.7, "ctx_size": 8192, "threads_boost": 1.0},"Q6_K": {"batch_multiplier": 0.8, "ctx_size": 8192, "threads_boost": 1.0},"Q5_K_M": {"batch_multiplier": 1.0, "ctx_size": 12288, "threads_boost": 0.9},"Q5_K_S": {"batch_multiplier": 1.0, "ctx_size": 12288, "threads_boost": 0.9},"Q4_K_M": {"batch_multiplier": 1.3, "ctx_size": 16384, "threads_boost": 0.8},"Q4_K_S": {"batch_multiplier": 1.3, "ctx_size": 16384, "threads_boost": 0.8},"Q4_0": {"batch_multiplier": 1.4, "ctx_size": 16384, "threads_boost": 0.8},"Q3_K_M": {"batch_multiplier": 1.6, "ctx_size": 20480, "threads_boost": 0.7},"Q2_K": {"batch_multiplier": 2.0, "ctx_size": 24576, "threads_boost": 0.7},}logging.basicConfig(level=logging.INFO, format='%(asctime)s - ZEROENGINE - %(message)s')logger = logging.getLogger(__name__)# --- AGGRESSIVE GARBAGE COLLECTOR ---import gcgc.enable()gc.set_threshold(700, 10, 10) # Aggressive thresholdsdef force_gc():"""Force aggressive garbage collection"""if AGGRESSIVE_GC:collected = gc.collect(2) # Full collectionlogger.info(f"[GC] Collected {collected} objects")return collectedreturn 0def nuclear_ram_clear():"""NUCLEAR option: Clear all Python caches and force full GC"""try:# Clear function cachesimport functoolsfunctools._CacheInfo.__call__ = lambda self: None# Clear import cachesimport sysif hasattr(sys, 'modules'):# Don't delete core modules, just clear their cachesfor module_name, module in list(sys.modules.items()):if hasattr(module, '__dict__') and not module_name.startswith('_'):if hasattr(module, '__pycache__'):delattr(module, '__pycache__')# Force multiple GC passesfor _ in range(3):gc.collect(2)logger.info("[RAM-NUKE] π₯ Nuclear RAM clear complete")return Trueexcept Exception as e:logger.error(f"[RAM-NUKE] Failed: {e}")return False# --- MODEL CACHE MANAGER (LoRA-style lightweight caching) ---class ModelCacheManager:def __init__(self):self.cache_dir = "/tmp/zeroengine_cache"self.cache = {} # {model_path: {"adapter": bytes, "metadata": dict}}self.max_cache_size_mb = 50 # Only cache 50MB total (tiny!)os.makedirs(self.cache_dir, exist_ok=True)logger.info(f"[CACHE] Initialized at {self.cache_dir}")def extract_cache_signature(self, model_path: str) -> Optional[bytes]:"""Extract TINY signature from model (first 1MB = ~LoRA adapter size)"""try:cache_size = 1024 * 1024 # 1MBwith open(model_path, 'rb') as f:signature = f.read(cache_size)logger.info(f"[CACHE] Extracted {len(signature)} bytes signature from {os.path.basename(model_path)}")return signatureexcept Exception as e:logger.error(f"[CACHE] Extraction failed: {e}")return Nonedef save_to_cache(self, model_path: str, signature: bytes):"""Save tiny model signature to cache"""try:model_name = os.path.basename(model_path)cache_path = os.path.join(self.cache_dir, f"{model_name}.cache")# Check total cache sizetotal_size = sum(os.path.getsize(os.path.join(self.cache_dir, f))for f in os.listdir(self.cache_dir) if f.endswith('.cache'))# If cache too big, delete oldestif total_size > (self.max_cache_size_mb * 1024 * 1024):logger.info("[CACHE] Cache full, removing oldest entry")cache_files = sorted([os.path.join(self.cache_dir, f) for f in os.listdir(self.cache_dir) if f.endswith('.cache')],key=os.path.getmtime)if cache_files:os.remove(cache_files[0])logger.info(f"[CACHE] Deleted {os.path.basename(cache_files[0])}")# Save new cachewith open(cache_path, 'wb') as f:f.write(signature)self.cache[model_path] = {"signature": signature,"cached_at": time.time(),"hits": 0}logger.info(f"[CACHE] β Cached {model_name} ({len(signature) / 1024:.1f}KB)")except Exception as e:logger.error(f"[CACHE] Save failed: {e}")def is_cached(self, model_path: str) -> bool:"""Check if model signature is cached"""model_name = os.path.basename(model_path)cache_path = os.path.join(self.cache_dir, f"{model_name}.cache")exists = os.path.exists(cache_path)if exists:logger.info(f"[CACHE] π― HIT for {model_name}")return existsdef preload_cache(self, model_path: str):"""Preload cached signature (simulates faster load)"""try:model_name = os.path.basename(model_path)cache_path = os.path.join(self.cache_dir, f"{model_name}.cache")if os.path.exists(cache_path):with open(cache_path, 'rb') as f:signature = f.read()if model_path in self.cache:self.cache[model_path]["hits"] += 1logger.info(f"[CACHE] Preloaded {len(signature) / 1024:.1f}KB signature")return Trueexcept Exception as e:logger.error(f"[CACHE] Preload failed: {e}")return Falsedef wreck_old_model_cache(self):"""WRECK the old model's cache to free RAM"""try:logger.info("[WRECKER] π£ Destroying old model caches...")# Clear Python's internal cachesgc.collect()# This is symbolic - the real wrecking happens when we del self.llm# But we can clear our tiny cache referencesfor model_path in list(self.cache.keys()):if self.cache[model_path].get("signature"):self.cache[model_path]["signature"] = Nonenuclear_ram_clear()logger.info("[WRECKER] β Old model WRECKED")return Trueexcept Exception as e:logger.error(f"[WRECKER] Failed: {e}")return False# Global cache managermodel_cache = ModelCacheManager()# --- TELEMETRY MODULE ---class TelemetryManager:def __init__(self, api: HfApi):72 unmodified linesself.auto_cleanup_thread = Noneself.start_idle_monitor()# Keyboard input pre-processingself.typing_buffer = ""self.typing_timer = Noneself.preprocessed_tokens = Nonedef detect_quantization(self, filename: str) -> dict:"""Detect quantization method from filename and return optimizations"""filename_upper = filename.upper()for quant_type, optimizations in QUANT_OPTIMIZATIONS.items():if quant_type in filename_upper:logger.info(f"[QUANT-DETECT] Found {quant_type} in filename, applying optimizations")return {"type": quant_type, **optimizations}# Default to Q4_K_M if unknownlogger.warning(f"[QUANT-DETECT] Unknown quantization, using Q4_K_M defaults")return {"type": "Q4_K_M", **QUANT_OPTIMIZATIONS["Q4_K_M"]}def preprocess_input(self, text: str):"""Pre-process keyboard input in background (tensors ready before submit)"""if not self.llm or not text or len(text) < 5:returndef _preprocess():try:logger.info(f"[PREPROCESS] Tokenizing {len(text)} chars in background...")tokens = self.llm.tokenize(text.encode("utf-8"))self.preprocessed_tokens = tokenslogger.info(f"[PREPROCESS] β Ready: {len(tokens)} tokens cached")except Exception as e:logger.error(f"[PREPROCESS] Failed: {e}")self.preprocessed_tokens = None# Cancel previous timer if user is still typingif self.typing_timer:self.typing_timer.cancel()# Start new timer - preprocess after 1 second of no typingself.typing_timer = threading.Timer(1.0, _preprocess)self.typing_timer.daemon = Trueself.typing_timer.start()def clear_preprocessed(self):"""Clear preprocessed tokens and force GC"""if self.preprocessed_tokens:self.preprocessed_tokens = Noneforce_gc()logger.info("[PREPROCESS] Cleared cached tokens")def start_idle_monitor(self):"""Start background thread to monitor idle timeout"""def monitor():7 unmodified linesdel self.llmself.llm = Noneself.active_model_info = {"repo": "", "file": ""}force_gc() # Aggressive cleanuplogger.info("[IDLE] Model unloaded successfully")except Exception as e:logger.error(f"[IDLE] Cleanup error: {e}")33 unmodified linesreturn []def boot_kernel(self, repo: str, filename: str) -> str:"""HYPER-OPTIMIZED Boot kernel with cache manager and old model wrecker"""try:if not repo or not filename:return "π΄ ERROR: Repository or filename missing"logger.info(f"[BOOT] Starting download: {filename} from {repo}")# DETECT QUANTIZATION FROM FILENAMEquant_config = self.detect_quantization(filename)# Download with timeout protectiontry:path = hf_hub_download(7 unmodified lineslogger.error(f"[BOOT] Download failed: {e}")return f"π΄ DOWNLOAD FAILED: {str(e)}"# Check if model is cached (for faster subsequent loads)is_cached = model_cache.is_cached(path)cache_status = "π― CACHED" if is_cached else "π NEW"# Validate before loadingvalid, msg = ResourceMonitor.validate_deployment(path)if not valid:logger.warning(f"[BOOT] Validation failed: {msg}")return f"π΄ VALIDATION FAILED: {msg}"logger.info(f"[BOOT] Validation passed ({cache_status}), applying {quant_config['type']} optimizations...")# Apply NUMA optimizationif NUMA_OPTIMIZE:1 unmodified line# Load model with MAXIMUM PERFORMANCE SETTINGSwith self.kernel_lock:# WRECK OLD MODEL - Nuclear optionif self.llm:logger.info("[BOOT] π£ WRECKING old model...")try:# Wreck the cache firstmodel_cache.wreck_old_model_cache()# Delete the modeldel self.llmself.llm = None# Nuclear RAM clearnuclear_ram_clear()logger.info("[BOOT] β Old model DESTROYED")except Exception as e:logger.warning(f"[BOOT] Cleanup warning: {e}")# Calculate optimal batch size based on quantization and available RAMvm = psutil.virtual_memory()available_ram_gb = vm.available / (1024**3)# MASSIVE batch sizes for quantized modelsbase_batch = int(256 * available_ram_gb / 4)optimal_batch = int(base_batch * quant_config["batch_multiplier"])optimal_batch = max(512, min(4096, optimal_batch)) # Clamp between 512-4096# Context size based on quantizationoptimal_ctx = quant_config["ctx_size"]# Thread count with quantization-specific boostoptimal_threads = int(OPTIMAL_THREADS * quant_config["threads_boost"])optimal_threads = max(2, min(optimal_threads, psutil.cpu_count(logical=False)))try:logger.info(f"[BOOT] Initializing {quant_config['type']}: threads={optimal_threads}, batch={optimal_batch}, ctx={optimal_ctx}")# Preload cache if available (simulates faster warmup)if is_cached:model_cache.preload_cache(path)# ULTRA-OPTIMIZED LLAMA.CPP INITIALIZATIONself.llm = Llama(model_path=path,n_ctx=optimal_ctx, # Dynamic context based on quantn_threads=optimal_threads, # Optimized thread countn_threads_batch=optimal_threads, # Batch processing threadsuse_mmap=USE_MMAP, # Memory-mapped weights (fast loading)use_mlock=MLOCK_MODEL, # Lock in RAM (prevent swap thrashing)n_batch=optimal_batch, # MASSIVE batch sizen_gpu_layers=0, # CPU-only modeflash_attn=FLASH_ATTENTION, # Flash Attention (2x faster)type_k=2 if KV_CACHE_QUANTIZATION else None, # Q4 KV cache quantizationtype_v=2 if KV_CACHE_QUANTIZATION else None, # Q4 KV cache quantizationrope_scaling_type=0, # Linear RoPE scalingrope_freq_scale=ROPE_SCALING, # RoPE frequency scalenuma=NUMA_OPTIMIZE, # NUMA optimizationverbose=False,logits_all=False, # Only compute final logits (faster)embedding=False, # Disable embeddings (not needed)offload_kqv=OFFLOAD_KQV, # No offload on CPUf16_kv=False # Use quantized KV cache instead)self.active_model_info = {"repo": repo, "file": filename, "quant": quant_config['type']}self.telemetry.track_load(repo, filename)# Extract and cache TINY signature for faster future loadsif not is_cached:logger.info("[BOOT] Extracting cache signature...")signature = model_cache.extract_cache_signature(path)if signature:model_cache.save_to_cache(path, signature)# Warm-up inference to populate cacheslogger.info("[BOOT] Warming up model caches...")try:self.llm("Warmup", max_tokens=1, stream=False)force_gc() # Clear warmup artifactsexcept:passlogger.info("[BOOT] π HYPER-OPTIMIZED MODEL READY!")return f"π’ {quant_config['type']} KERNEL {cache_status} | T:{optimal_threads} | B:{optimal_batch} | Ctx:{optimal_ctx}"except Exception as e:logger.error(f"[BOOT] Model loading failed: {e}")self.llm = Nonenuclear_ram_clear()return f"π΄ LOAD FAILED: {str(e)}"except Exception as e:logger.error(f"[BOOT] Unexpected error: {e}")nuclear_ram_clear()return f"π΄ BOOT FAILURE: {str(e)}"def stitch_cache(self, ghost_text: str) -> str:"""Prime KV cache with ghost context"""if not self.llm or not ghost_text or self.is_prefilling:return "Kernel Idle/Busy"3 unmodified linestokens = self.llm.tokenize(ghost_text.encode("utf-8"))self.llm.eval(tokens)logger.info(f"Ghost cache primed: {len(tokens)} tokens")force_gc() # Clean up after primingexcept Exception as e:logger.error(f"KV Cache priming failed: {e}")finally:self.is_prefilling = Falsethreading.Thread(target=_bg_eval, daemon=True).start()return "β‘ Primed"def inference_generator(self, prompt: str, history: List[Dict], ghost_context: str, repo: str, quant: str) -> Generator:# Update activity timestampself.update_activity()# Clear any preprocessed tokens from typingself.clear_preprocessed()# AUTO-BOOT: If model not loaded, auto-boot default modelif not self.llm:logger.info("[AUTO-BOOT] No model loaded, initiating auto-boot...")77 unmodified linesself.perf_stats["peak_tps"] = tps# Update history with streaming content + performance metricshistory[-1]["content"] = f"{response_text}\n\n`β‘ {tps} t/s | π― Peak: {self.perf_stats['peak_tps']:.1f} t/s | πΎ Cache: {self.perf_stats['cache_hits']}`"yield history# Update global performance stats11 unmodified linesself.telemetry.track_generation(tokens_count)# Aggressive GC after generationforce_gc()logger.info(f"β Generation complete: {tokens_count} tokens @ {tps:.1f} t/s (TTFT: {first_token_time*1000:.0f}ms)")except Exception as e:logger.error(f"Inference error: {e}")history[-1]["content"] = f"π΄ Runtime Error: {str(e)}"yield historyforce_gc()# --- CUSTOM CSS ---CUSTOM_CSS = """144 unmodified linesboot_status = gr.Markdown("Status: `STANDBY`")gr.Markdown("---")gr.Markdown("### π» Ghost Cache (Pre-Context)")ghost_buffer = gr.Textbox(label="Background Context",placeholder="Add context that will be prepended to all messages...",lines=3)with gr.Row():stitch_btn = gr.Button("PRIME CACHE", variant="secondary", size="sm", scale=1)stitch_status = gr.Markdown("Cache: `EMPTY`")log_output = gr.Code(label="Kernel Logs",57 unmodified lines[stitch_status])# Keyboard input preprocessing (tokenize while typing)user_input.change(lambda x: kernel.preprocess_input(x),[user_input],None)# Auto-boot enabled inference - passes repo and quant for auto-bootinference_args = [user_input, chat_box, ghost_buffer, repo_input, quant_dropdown]user_input.submit(kernel.inference_generator, inference_args, [chat_box])
app.py+303-32