""" Universal GGUF LLM runner — ZeroGPU Space. Load any GGUF model from the Hugging Face Hub (with a few abliterated-Qwen presets) through a single Gradio chat UI, served on ZeroGPU via llama.cpp. How it differs from serverless inference: nothing here is "pre-deployed". You point it at a repo + GGUF file (or a preset) and it downloads and runs it yourself on your Pro plan's free ZeroGPU allowance. Limits to know: * Hardware is a shared A10G (ZeroGPU) slice (~24 GB VRAM). Aim for <= 14B quantized; 4B-9B Q4_K_M is the sweet spot. A 27B model will not fit. * First use of a model downloads its GGUF (cached afterwards until the Space sleeps/rebuilds). * Architecture support matches the pinned llama-cpp-python driver. Plain Qwen3 GGUFs are the safest; brand-new experimental archs may report an "unsupported" error — just pick another model. """ from __future__ import annotations import os os.environ.setdefault("GRADIO_SSR_MODE", "false") os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1") # Import ZeroGPU integration BEFORE any CUDA-aware library. import spaces # noqa: F401 import gc import threading import time from typing import Any, Dict, List, Optional, Tuple import gradio as gr from huggingface_hub import hf_hub_download, list_repo_files from llama_cpp import Llama, llama_supports_gpu_offload HF_TOKEN = os.getenv("HF_TOKEN", "").strip() or None N_CTX = int(os.getenv("LLM_N_CTX", "8192")) # --------------------------------------------------------------------------- # # Presets (verified filenames; all Apache-2.0 abliterated Qwen GGUF builds) # --------------------------------------------------------------------------- # PRESETS: Dict[str, Dict[str, str]] = { "Qwen3-4B abliterated · Q4_K_M (2.5 GB)": { "repo_id": "mradermacher/Huihui-Qwen3-4B-abliterated-v2-i1-GGUF", "filename": "Huihui-Qwen3-4B-abliterated-v2.i1-Q4_K_M.gguf", }, "Qwen3.5-4B abliterated · Q4_K_M (2.7 GB)": { "repo_id": "mradermacher/Huihui-Qwen3.5-4B-abliterated-GGUF", "filename": "Huihui-Qwen3.5-4B-abliterated.Q4_K_M.gguf", }, "Qwen3.5-9B abliterated · Q4_K_M (5.6 GB)": { "repo_id": "mradermacher/Huihui-Qwen3.5-9B-abliterated-GGUF", "filename": "Huihui-Qwen3.5-9B-abliterated.Q4_K_M.gguf", }, "Tiny instant default · Qwen2.5-Coder-0.5B (491 MB)": { "repo_id": "Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF", "filename": "qwen2.5-coder-0.5b-instruct-q4_k_m.gguf", }, } PRESET_CHOICES = list(PRESETS.keys()) DEFAULT_PRESET = PRESET_CHOICES[0] # --------------------------------------------------------------------------- # # Worker-local model cache (same pattern as mhd-radin/qwen25-coder-api). # ZeroGPU runs @spaces.GPU calls in isolated worker processes, so a model is # cached per-worker and re-loaded (from the already-downloaded file) on cold # workers. Downloads happen in the main process, outside the GPU window. # --------------------------------------------------------------------------- # _LOCK = threading.Lock() _LLM: Optional[Llama] = None _LOADED_KEY: Optional[str] = None _LOADED_PID: Optional[int] = None def _unload() -> None: global _LLM, _LOADED_KEY, _LOADED_PID old = _LLM _LLM = None _LOADED_KEY = None _LOADED_PID = None if old is not None: try: old.close() except Exception: pass del old gc.collect() def ensure_llm(path: str, key: str) -> Llama: """Load (and cache) the llama.cpp model inside the current worker.""" global _LLM, _LOADED_KEY, _LOADED_PID with _LOCK: pid = os.getpid() if _LLM is not None and _LOADED_PID == pid and _LOADED_KEY == key: return _LLM if not llama_supports_gpu_offload(): raise RuntimeError( "No CUDA backend in this worker (llama.cpp GPU offload is unavailable)." ) _unload() t0 = time.time() llm = Llama( model_path=path, n_gpu_layers=-1, # offload every layer to the GPU main_gpu=0, n_ctx=N_CTX, n_batch=512, n_ubatch=512, offload_kqv=True, flash_attn=True, use_mmap=True, use_mlock=False, verbose=False, ) _LLM = llm _LOADED_KEY = key _LOADED_PID = pid print(f"[model] loaded {key} in {time.time() - t0:.1f}s (pid={pid})") return llm # --------------------------------------------------------------------------- # # Download + filename resolution (runs in the main process, no GPU needed) # --------------------------------------------------------------------------- # _QUANT_PREFERENCE = [ "q4_k_m", "q4_k_s", "q5_k_m", "q4_0", "q3_k_m", "iq4_xs", "q2_k", "q6_k", "q5_k_s", ] def pick_gguf(files: List[str]) -> str: ggufs = [f for f in files if f.lower().endswith(".gguf") and "mmproj" not in f.lower()] if not ggufs: raise ValueError("No .gguf files found in this repo.") for tag in _QUANT_PREFERENCE: for f in ggufs: if tag in f.lower(): return f # Fall back: smallest sensible file, avoiding huge fp16/bf16/Q8 builds. pool = [f for f in ggufs if not any(t in f.lower() for t in ("f16", "bf16", "q8_0", "q8_k"))] return sorted(pool or ggufs)[0] def resolve(repo_id: str, filename: str) -> Tuple[str, str]: repo_id = (repo_id or "").strip() if not repo_id: raise ValueError("Enter a model repo first (owner/name).") filename = (filename or "").strip() if not filename: files = list_repo_files(repo_id, token=HF_TOKEN) filename = pick_gguf(files) path = hf_hub_download(repo_id=repo_id, filename=filename, token=HF_TOKEN) key = f"{repo_id}::{filename}" return path, key # --------------------------------------------------------------------------- # # Chat helpers # --------------------------------------------------------------------------- # def build_prompt(history: List[List[str]], system: str) -> str: parts: List[str] = [] if system and system.strip(): parts.append(f"<|im_start|>system\n{system.strip()}<|im_end|>") for user, assistant in history: if user: parts.append(f"<|im_start|>user\n{user}<|im_end|>") if assistant: parts.append(f"<|im_start|>assistant\n{assistant}<|im_end|>") parts.append("<|im_start|>assistant\n") return "\n".join(parts) # --------------------------------------------------------------------------- # # Gradio handlers # --------------------------------------------------------------------------- # def load_model(preset, repo_id, filename) -> Tuple[str, Dict[str, Any]]: """Resolve + download (main process). Returns a status line and the model reference that the GPU handler will use.""" try: if preset in PRESETS: repo_id = PRESETS[preset]["repo_id"] filename = PRESETS[preset]["filename"] if not (repo_id or "").strip(): raise ValueError("No model selected.") path, key = resolve(repo_id, filename) return ( f"✅ Ready: `{repo_id}` → `{os.path.basename(path)}`\n\n" f"File is on disk. It will be loaded onto the GPU on your first message.", {"key": key, "path": path}, ) except Exception as exc: # noqa: BLE001 return f"❌ Load failed: {type(exc).__name__}: {exc}", {} @spaces.GPU(duration=90) def respond( message: str, history: List[List[str]], system: str, max_tokens: float, temperature: float, top_p: float, resolved: Optional[Dict[str, Any]], ) -> Tuple[List[List[str]], List[List[str]], str]: """GPU inference. Returns (chatbot, history, cleared_message_box).""" message = (message or "").strip() if not message: return history, history, "" if not resolved or not resolved.get("path"): err = [[message, "⚠️ Load a model first — pick a preset (or type a repo) and click **Load / refresh model**."]] return err, err, "" try: llm = ensure_llm(resolved["path"], resolved["key"]) prompt = build_prompt(history + [[message, ""]], system) out = llm( prompt, max_tokens=int(max_tokens), temperature=float(temperature), top_p=float(top_p), echo=False, ) text = (out.get("choices") or [{}])[0].get("text", "").strip() if not text: text = "(empty response)" except Exception as exc: # noqa: BLE001 text = f"❌ {type(exc).__name__}: {exc}" new_history = history + [[message, text]] return new_history, new_history, "" def clear_chat() -> Tuple[List[List[str]], List[List[str]]]: return [], [] def on_preset_change(preset: str) -> Tuple[str, str]: cfg = PRESETS.get(preset, {}) return cfg.get("repo_id", ""), cfg.get("filename", "") # --------------------------------------------------------------------------- # # UI # --------------------------------------------------------------------------- # with gr.Blocks(title="Universal GGUF LLM runner") as demo: gr.Markdown( "# 🚀 Universal GGUF LLM runner\n" "Point this at **any GGUF repo** on the Hub — or pick an **abliterated-Qwen preset** — " "and chat. Runs on your Pro plan's free **ZeroGPU** quota; no per-token inference cost." ) gr.Markdown( "> Fit guide: ≤ ~14B quantized (4B–9B Q4 is ideal) for the ~24 GB slice. " "First load downloads the file; later loads are cached until the Space sleeps." ) with gr.Row(): preset = gr.Dropdown(choices=PRESET_CHOICES, value=DEFAULT_PRESET, label="Preset") repo_id = gr.Textbox( value=PRESETS[DEFAULT_PRESET]["repo_id"], label="Model repo (owner/name)", placeholder="e.g. mradermacher/Huihui-Qwen3-4B-abliterated-v2-i1-GGUF", ) filename = gr.Textbox( value=PRESETS[DEFAULT_PRESET]["filename"], label="GGUF filename (leave blank to auto-pick)", placeholder="e.g. model.Q4_K_M.gguf", ) load_btn = gr.Button("Load / refresh model", variant="primary") status = gr.Markdown("👆 Pick a preset (or type a repo) and click **Load / refresh model**.") resolved = gr.State({}) preset.change(on_preset_change, inputs=preset, outputs=[repo_id, filename]) load_btn.click(load_model, inputs=[preset, repo_id, filename], outputs=[status, resolved]) with gr.Row(): with gr.Column(scale=3): chatbot = gr.Chatbot(label="Chat", height=460) msg = gr.Textbox(label="Message", placeholder="Type a message and press Enter…") with gr.Row(): send = gr.Button("Send", variant="primary") clear = gr.Button("Clear chat") with gr.Column(scale=1): system = gr.Textbox(label="System prompt", value="You are a helpful assistant.", lines=4) max_tokens = gr.Slider(16, 1024, value=512, step=16, label="Max new tokens") temperature = gr.Slider(0.0, 2.0, value=0.7, step=0.05, label="Temperature") top_p = gr.Slider(0.0, 1.0, value=0.9, step=0.05, label="Top-p") history = gr.State([]) inputs = [msg, history, system, max_tokens, temperature, top_p, resolved] outputs = [chatbot, history, msg] msg.submit(respond, inputs=inputs, outputs=outputs) send.click(respond, inputs=inputs, outputs=outputs) clear.click(clear_chat, outputs=[chatbot, history]) demo.queue(default_concurrency_limit=1).launch()