Spaces:
Running on Zero
Running on Zero
Download app.py from Featherplayz/Cpu: direct link, hf CLI and curl.
- Browser
- Download file 44.7 kB
-
https://huggingface.co/spaces/Featherplayz/Cpu/resolve/main/app.py
- Command line
-
hf download hf://spaces/Featherplayz/Cpu/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Featherplayz/Cpu/resolve/main/app.py
44.7 kB
"""
Granite 4.0 H-Tiny β Self-hosted OpenAI-style API + Gradio UI.
- Prebuilt llama.cpp (no clone, no compile β downloads official release binary).
- One-time model download via huggingface_hub (cached).
- FastAPI custom routes with payload-secret auth (SECRET from env).
- effort (low|medium|high) + reasoning flag -> system prompt handling.
- Streaming support, /metrics, /v1/models, token counting, health routes.
Env:
SECRET (required) β API secret checked against payload["secret"]
PORT (default 7860)
LLAMA_PORT (default 8081)
MODEL_REPO (default ibm-granite/granite-4.0-h-tiny-GGUF)
MODEL_QUANT (default Q4_K_M)
MODEL_FILE (optional exact gguf filename override)
MODEL_ALIAS (default granite-4.0-h-tiny)
CTX_SIZE (default 8192) β context PER parallel slot
THREADS (default 2)
PARALLEL (default 2)
LLAMA_EXTRA_ARGS (optional comma-separated extra llama-server flags)
LLAMA_ZIP_URL (optional override for prebuilt release archive URL)
requirements.txt: fastapi, uvicorn, gradio, requests, huggingface_hub
"""
from __future__ import annotations
import atexit
import hmac
import json
import math
import os
import shutil
import stat
import subprocess
import tarfile
import threading
import time
import urllib.request
import zipfile
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Tuple
os.environ.setdefault("GRADIO_SSR_MODE", "false")
import gradio as gr
import requests
import uvicorn
from fastapi import FastAPI, Request
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import JSONResponse, Response, StreamingResponse
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ZeroGPU startup validator (kept: tiny duration, negligible GPU quota usage).
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
try:
import spaces # type: ignore
@spaces.GPU(duration=0.0000000001)
def _gpu_validation_placeholder() -> None:
return None
except Exception: # local / CPU-only environments
def _gpu_validation_placeholder() -> None:
return None
try:
_gpu_validation_placeholder()
except Exception as _exc: # never let the validator crash startup
print(f"[spaces] GPU validator call skipped: {_exc}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Configuration (all overridable via env)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SECRET = os.environ.get("SECRET", "").strip()
PORT = int(os.environ.get("PORT", "7860"))
LLAMA_PORT = int(os.environ.get("LLAMA_PORT", "8081"))
LLAMA_URL = f"http://127.0.0.1:{LLAMA_PORT}"
MODEL_REPO = os.environ.get("MODEL_REPO", "ibm-granite/granite-4.0-h-tiny-GGUF")
MODEL_QUANT = os.environ.get("MODEL_QUANT", "Q4_K_M")
MODEL_FILE = os.environ.get("MODEL_FILE", "")
MODEL_ALIAS = os.environ.get("MODEL_ALIAS", "granite-4.0-h-tiny")
CTX_SIZE = int(os.environ.get("CTX_SIZE", "8192")) # per slot
THREADS = int(os.environ.get("THREADS", "2"))
THREADS_BATCH = int(os.environ.get("THREADS_BATCH", str(THREADS)))
PARALLEL = max(1, int(os.environ.get("PARALLEL", "2")))
BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "512"))
UBATCH_SIZE = int(os.environ.get("UBATCH_SIZE", "128"))
CACHE_REUSE = int(os.environ.get("CACHE_REUSE", "256"))
MAX_TOKENS_DEFAULT = int(os.environ.get("MAX_TOKENS", "8192"))
LLAMA_DIR = Path(os.environ.get("LLAMA_DIR", "/tmp/llama"))
LLAMA_ZIP_URL = os.environ.get("LLAMA_ZIP_URL", "")
LLAMA_BIN = os.environ.get("LLAMA_SERVER_BIN", "")
LLAMA_EXTRA_ARGS = [
a.strip() for a in os.environ.get("LLAMA_EXTRA_ARGS", "").split(",") if a.strip()
]
GH_LATEST_API = "https://api.github.com/repos/ggml-org/llama.cpp/releases/latest"
STARTUP_TIMEOUT = int(os.environ.get("STARTUP_TIMEOUT", "1800"))
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Small helpers
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def to_bool(value: Any, default: bool) -> bool:
"""bool('false') is True in Python β parse JSON-ish values properly."""
if isinstance(value, bool):
return value
if value is None:
return default
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
v = value.strip().lower()
if v in {"1", "true", "yes", "on"}:
return True
if v in {"0", "false", "no", "off", ""}:
return False
return default
def secret_matches(provided: Any, expected: str) -> bool:
# compare_digest raises TypeError on non-ASCII str; compare bytes instead.
return hmac.compare_digest(str(provided or "").encode("utf-8"), expected.encode("utf-8"))
def clamp(value: Any, lo: float, hi: float, default: float) -> float:
try:
v = float(value)
except (TypeError, ValueError):
v = default
if not math.isfinite(v):
v = default
return max(lo, min(hi, v))
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Effort / reasoning handling
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
EFFORT_CHOICES = ["low", "medium", "high"]
ALLOWED_EFFORTS = set(EFFORT_CHOICES)
DEFAULT_SYSTEM_PROMPT = (
"You are Granite, an AI assistant powered by IBM Granite 4.0 H-Tiny. "
"Be helpful, accurate, natural, and concise. "
"Avoid repeating sentences. If you are unsure, say so."
)
EFFORT_SYSTEM_PROMPT = (
"Reasoning effort preference: {effort}. "
"Solve carefully, verify the result, "
"and provide a concise explanation."
)
def normalize_effort(payload: Dict[str, Any]) -> str:
effort = str(payload.get("effort") or "medium").strip().lower()
return effort if effort in ALLOWED_EFFORTS else "medium"
def build_system_prompt(payload: Dict[str, Any]) -> Tuple[str, str, bool]:
"""Returns (final_system_prompt, effort, reasoning)."""
effort = normalize_effort(payload)
reasoning = to_bool(payload.get("reasoning"), True)
system_prompt = str(payload.get("system_prompt") or "").strip()
if not system_prompt:
system_prompt = DEFAULT_SYSTEM_PROMPT
if not reasoning:
return system_prompt, effort, False
final = f"{system_prompt}\n\n{EFFORT_SYSTEM_PROMPT.format(effort=effort)}"
return final, effort, True
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Prebuilt llama.cpp (no compile, ever)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_EXCLUDED_ASSET_WORDS = (
"vulkan", "rocm", "hip", "openvino", "sycl", "cuda", "arm", "aarch",
"s390x", "riscv", "kleidiai",
)
def _http_download(url: str, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_suffix(dest.suffix + ".part")
req = urllib.request.Request(url, headers={"User-Agent": "granite-h-tiny-space"})
with urllib.request.urlopen(req, timeout=120) as resp, open(tmp, "wb") as out:
shutil.copyfileobj(resp, out)
os.replace(tmp, dest)
GH_RELEASES_API = "https://api.github.com/repos/ggml-org/llama.cpp/releases?per_page=15"
SRC_DIR = Path(os.environ.get("LLAMA_SRC_DIR", "/tmp/llama.cpp"))
def _latest_ubuntu_archive_url() -> str:
req = urllib.request.Request(
GH_RELEASES_API,
headers={"User-Agent": "granite-h-tiny-space", "Accept": "application/vnd.github+json"},
)
with urllib.request.urlopen(req, timeout=30) as resp:
releases = json.load(resp)
seen: List[str] = []
for rel in releases:
for asset in rel.get("assets", []):
name = (asset.get("name") or "").lower()
seen.append(name)
if "ubuntu" not in name or "x64" not in name:
continue
if not name.endswith((".zip", ".tar.gz", ".tgz")):
continue
if any(w in name for w in _EXCLUDED_ASSET_WORDS):
continue
return asset["browser_download_url"]
print(f"[llama] no matching asset. Seen: {seen[:20]}")
raise RuntimeError("No prebuilt ubuntu-x64 asset found in recent llama.cpp releases")
def _build_from_source() -> str:
def run(cmd: List[str]) -> None:
subprocess.run(cmd, check=True)
if not SRC_DIR.is_dir():
run(["git", "clone", "--depth", "1",
"https://github.com/ggml-org/llama.cpp.git", str(SRC_DIR)])
build = SRC_DIR / "build"
run(["cmake", "-S", str(SRC_DIR), "-B", str(build),
"-DGGML_CUDA=OFF", "-DGGML_VULKAN=OFF", "-DGGML_METAL=OFF",
"-DGGML_NATIVE=OFF", "-DLLAMA_CURL=OFF", "-DCMAKE_BUILD_TYPE=Release"])
run(["cmake", "--build", str(build), "--config", "Release",
"--parallel", "2", "--target", "llama-server"])
binary = build / "bin" / "llama-server"
if not binary.is_file():
raise RuntimeError("source build finished but llama-server was not found")
return str(binary)
def _extract_archive(archive: Path, dest: Path) -> None:
name = archive.name.lower()
if name.endswith(".zip"):
with zipfile.ZipFile(archive) as zf:
zf.extractall(dest)
else:
with tarfile.open(archive) as tf:
try:
tf.extractall(dest, filter="data") # Python 3.12+
except TypeError:
tf.extractall(dest)
def _find_server() -> Optional[Path]:
if not LLAMA_DIR.is_dir():
return None
for root, _dirs, files in os.walk(LLAMA_DIR):
if "llama-server" in files:
return Path(root) / "llama-server"
return None
def _download_prebuilt() -> Path:
LLAMA_DIR.mkdir(parents=True, exist_ok=True)
url = LLAMA_ZIP_URL or _latest_ubuntu_archive_url()
print(f"[llama] downloading prebuilt binary: {url}")
archive_name = Path(url.split("?")[0]).name or "llama-bin.zip"
archive = LLAMA_DIR / archive_name
_http_download(url, archive)
_extract_archive(archive, LLAMA_DIR)
archive.unlink(missing_ok=True)
for root, _dirs, files in os.walk(LLAMA_DIR):
for fn in files:
if fn.startswith("llama-") or fn.startswith("lib"):
p = Path(root) / fn
p.chmod(p.stat().st_mode | stat.S_IEXEC)
server = _find_server()
if server is None:
raise RuntimeError("llama-server not found inside release archive")
return server
def ensure_llama_binary() -> str:
"""Resolve llama-server: env path > cached > prebuilt release > source build."""
global LLAMA_BIN
if LLAMA_BIN and os.path.isfile(LLAMA_BIN):
return LLAMA_BIN
server = _find_server()
src_bin = SRC_DIR / "build" / "bin" / "llama-server"
if server is None and src_bin.is_file():
server = src_bin
if server is None:
try:
server = _download_prebuilt()
except Exception as exc:
print(f"[llama] prebuilt download failed ({exc}); building from source (slow)...")
server = Path(_build_from_source())
server.chmod(server.stat().st_mode | stat.S_IEXEC)
LLAMA_BIN = str(server)
return LLAMA_BIN
def ensure_model_file() -> str:
"""Download the GGUF once via huggingface_hub (cached in HF_HOME)."""
if MODEL_FILE and os.path.isfile(MODEL_FILE):
return MODEL_FILE
from huggingface_hub import hf_hub_download, list_repo_files
files = [
f for f in list_repo_files(MODEL_REPO)
if f.lower().endswith(".gguf") and "mmproj" not in f.lower()
]
if not files:
raise RuntimeError(f"No GGUF files found in {MODEL_REPO}")
target: Optional[str] = None
if MODEL_FILE:
target = next((f for f in files if f == MODEL_FILE or f.endswith(MODEL_FILE)), None)
if target is None:
target = next((f for f in files if MODEL_QUANT.lower() in f.lower()), None)
if target is None:
raise RuntimeError(f"No GGUF matching {MODEL_QUANT!r} in {MODEL_REPO}: {files}")
return str(hf_hub_download(repo_id=MODEL_REPO, filename=target))
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# llama-server lifecycle
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
server_process: Optional[subprocess.Popen] = None
_server_lock = threading.Lock()
_started_at: float = 0.0
def _stop_process(proc: Optional[subprocess.Popen]) -> None:
if proc is None or proc.poll() is not None:
return
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
def _shutdown() -> None:
_stop_process(server_process)
atexit.register(_shutdown)
def _minimal_cmd(binary: str, model_path: str) -> List[str]:
# NOTE: --ctx-size is the TOTAL context shared by all parallel slots, so
# multiply by PARALLEL to give every slot the advertised CTX_SIZE.
return [
binary,
"-m", model_path,
"--host", "127.0.0.1",
"--port", str(LLAMA_PORT),
"--threads", str(THREADS),
"--ctx-size", str(CTX_SIZE * PARALLEL),
"--parallel", str(PARALLEL),
"--alias", MODEL_ALIAS,
]
def _tuned_cmd(binary: str, model_path: str) -> List[str]:
cmd = _minimal_cmd(binary, model_path) + [
"--threads-batch", str(THREADS_BATCH),
"--batch-size", str(BATCH_SIZE),
"--ubatch-size", str(UBATCH_SIZE),
"--flash-attn", "auto",
"--cont-batching",
"--cache-reuse", str(CACHE_REUSE), # shared-prefix KV reuse β faster repeats
"--metrics", # /metrics endpoint for monitoring
]
if "--no-webui" not in LLAMA_EXTRA_ARGS:
cmd.append("--no-webui")
return cmd + LLAMA_EXTRA_ARGS
def _cmd_variants(binary: str, model_path: str) -> List[List[str]]:
# Variant 1: full tuned flags (+ user extras).
# Variant 2: truly minimal fallback if variant 1 fails on flag support.
return [_tuned_cmd(binary, model_path), _minimal_cmd(binary, model_path)]
def llama_healthy() -> bool:
try:
return requests.get(f"{LLAMA_URL}/health", timeout=2).ok
except requests.RequestException:
return False
def _wait_healthy(proc: subprocess.Popen, timeout: int) -> bool:
deadline = time.time() + timeout
while time.time() < deadline:
if proc.poll() is not None:
return False
if llama_healthy():
return True
time.sleep(1.0)
return False
def _warmup() -> None:
"""Tiny request so the first real user doesn't pay cold-start cost."""
try:
requests.post(
f"{LLAMA_URL}/v1/chat/completions",
json={"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 1},
timeout=(5, 120),
)
except requests.RequestException:
pass
def _server_ok() -> bool:
proc = server_process
return proc is not None and proc.poll() is None and llama_healthy()
def start_server(force: bool = False) -> None:
"""Idempotent llama-server boot; called at startup and re-checked per request."""
global server_process, _started_at
if not force and _server_ok(): # fast path without taking the lock
return
with _server_lock:
if not force and _server_ok():
return
# Kill any stale/unhealthy instance so the port is free.
_stop_process(server_process)
server_process = None
binary = ensure_llama_binary()
model_path = ensure_model_file()
print(f"[llama] binary: {binary}")
print(f"[llama] model: {model_path}")
last_error = "unknown"
for variant in _cmd_variants(binary, model_path):
print(f"[llama] starting: {' '.join(variant)}")
proc = subprocess.Popen(variant)
if _wait_healthy(proc, STARTUP_TIMEOUT):
server_process = proc
_started_at = time.time()
print("[llama] ready β serving requests.")
_warmup()
return
code = proc.poll()
last_error = f"exit_code={code}" if code is not None else "startup timeout"
_stop_process(proc)
raise RuntimeError(f"llama-server failed to start ({last_error}). Check Space logs.")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Auth (payload secret must match SECRET env)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def check_secret(payload: Dict[str, Any]) -> Optional[JSONResponse]:
if not SECRET:
return JSONResponse(
{"error": "Server SECRET env is not configured."},
status_code=503,
)
if not secret_matches(payload.get("secret", ""), SECRET):
return JSONResponse({"error": "Wrong Secret"}, status_code=401)
return None
async def read_payload(request: Request) -> Tuple[Optional[Dict[str, Any]], Optional[JSONResponse]]:
try:
payload = await request.json()
except Exception:
return None, JSONResponse({"error": "Invalid JSON payload."}, status_code=400)
if not isinstance(payload, dict):
return None, JSONResponse({"error": "Payload must be a JSON object."}, status_code=400)
return payload, None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Core generation helper
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def llama_chat(
messages: List[Dict[str, str]],
max_tokens: int,
temperature: float = 0.7,
top_p: float = 0.9,
stream: bool = False,
) -> requests.Response:
body: Dict[str, Any] = {
"model": MODEL_ALIAS,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": top_p,
"stream": bool(stream),
}
if stream:
body["stream_options"] = {"include_usage": True} # real token count at the end
resp = requests.post(
f"{LLAMA_URL}/v1/chat/completions",
json=body,
stream=stream,
timeout=(15, 900),
)
if stream:
# text/event-stream has no charset β requests assumes ISO-8859-1 and
# garbles every non-ASCII character. SSE is always UTF-8.
resp.encoding = "utf-8"
return resp
def _sse_lines(upstream: requests.Response) -> Iterator[str]:
for line in upstream.iter_lines(decode_unicode=True):
if isinstance(line, bytes):
line = line.decode("utf-8", errors="replace")
yield line
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Metrics: TTFT + tokens/s (shared by the API and the UI)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def count_tokens(text: str) -> Tuple[int, str]:
"""Ask llama.cpp to count tokens with the model's own tokenizer."""
try:
resp = requests.post(
f"{LLAMA_URL}/tokenize",
json={"content": text, "add_special": False, "parse_special": False},
timeout=15,
)
resp.raise_for_status()
tokens = resp.json().get("tokens")
if isinstance(tokens, list):
return len(tokens), "model-tokenizer"
except (requests.RequestException, ValueError, TypeError):
pass
return len(text.split()), "word-based estimate" # fallback only
class StreamStats:
"""Create right before sending the request; feed it every parsed SSE chunk."""
def __init__(self) -> None:
self.t_start = time.perf_counter()
self.t_first: Optional[float] = None
self.chunks = 0
self.text = ""
self.usage_tokens: Optional[int] = None
self.timing_tokens: Optional[int] = None
def feed(self, data: Dict[str, Any]) -> str:
"""Returns the new text piece (or '')."""
usage = data.get("usage")
if isinstance(usage, dict):
n = usage.get("completion_tokens")
if isinstance(n, int) and n > 0:
self.usage_tokens = n
timings = data.get("timings")
if isinstance(timings, dict):
n = timings.get("predicted_n")
if isinstance(n, int) and n > 0:
self.timing_tokens = n
choices = data.get("choices") or []
if not choices:
return ""
piece = (choices[0].get("delta") or {}).get("content") or ""
if not isinstance(piece, str) or not piece:
return ""
if self.t_first is None:
self.t_first = time.perf_counter()
self.chunks += 1
self.text += piece
return piece
def live(self) -> Optional[Dict[str, float]]:
if self.t_first is None:
return None
elapsed = max(time.perf_counter() - self.t_first, 0.001)
return {
"ttft_ms": (self.t_first - self.t_start) * 1000,
"approx_tokens_per_second": self.chunks / elapsed, # ~1 chunk per token
}
def finish(self) -> Dict[str, Any]:
t_end = time.perf_counter()
if self.usage_tokens:
tokens, method = self.usage_tokens, "llama-server usage"
elif self.timing_tokens:
tokens, method = self.timing_tokens, "llama-server timings"
elif self.text:
tokens, method = count_tokens(self.text)
else:
tokens, method = 0, "none"
first = self.t_first if self.t_first is not None else t_end
gen_seconds = t_end - first
tps = round(tokens / gen_seconds, 2) if tokens > 1 and gen_seconds > 0 else None
return {
"ttft_ms": round((first - self.t_start) * 1000, 1) if self.t_first is not None else None,
"tokens_per_second": tps,
"output_tokens": tokens,
"token_count_method": method,
"generation_seconds": round(gen_seconds, 2),
"total_seconds": round(t_end - self.t_start, 2),
}
def format_metrics_md(m: Dict[str, Any]) -> str:
ttft = f"{m['ttft_ms']:.1f} ms" if m.get("ttft_ms") is not None else "n/a"
tps = f"{m['tokens_per_second']:.2f} tokens/s" if m.get("tokens_per_second") else "n/a"
return (
"### π Generation metrics\n"
f"- **TTFT:** {ttft}\n"
f"- **Generation speed:** {tps}\n"
f"- **Output tokens:** {m.get('output_tokens', 0)} ({m.get('token_count_method', '?')})\n"
f"- **Generation time after first text:** {m.get('generation_seconds', 0)} s\n"
f"- **Total request time:** {m.get('total_seconds', 0)} s"
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FastAPI app + routes
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(title="Granite 4.0 H-Tiny Self-Hosted API", version="1.0.0")
@app.post("/v1/chat/completion")
@app.post("/v1/chat/completions")
async def chat_completion(request: Request):
payload, err = await read_payload(request)
if err:
return err
err = check_secret(payload)
if err:
return err
prompt = str(payload.get("prompt") or payload.get("message") or "").strip()
if not prompt:
return JSONResponse({"error": "Field 'prompt' is required."}, status_code=400)
try:
# no-op if healthy; auto-recovers if crashed (off the event loop: may block)
await run_in_threadpool(start_server)
except Exception as exc:
return JSONResponse({"error": f"Inference backend unavailable: {exc}"}, status_code=503)
system_content, effort, reasoning = build_system_prompt(payload)
messages: List[Dict[str, str]] = [
{"role": "system", "content": system_content},
{"role": "user", "content": prompt},
]
requested_model = str(payload.get("model") or MODEL_ALIAS)
max_tokens = int(clamp(payload.get("max_tokens", MAX_TOKENS_DEFAULT), 16, CTX_SIZE, MAX_TOKENS_DEFAULT))
temperature = clamp(payload.get("temperature", 0.7), 0.0, 2.0, 0.7)
top_p = clamp(payload.get("top_p", 0.9), 0.01, 1.0, 0.9)
stream = to_bool(payload.get("stream"), False)
if stream:
stats = StreamStats()
try:
upstream = await run_in_threadpool(
llama_chat, messages, max_tokens, temperature, top_p, True
)
except requests.RequestException as exc:
return JSONResponse({"error": f"llama-server error: {exc}"}, status_code=502)
if not upstream.ok:
detail = upstream.text[:500]
upstream.close()
return JSONResponse(
{"error": f"llama-server error: HTTP {upstream.status_code}: {detail}"},
status_code=502,
)
def metrics_event() -> bytes:
chunk = {
"id": "chatcmpl-granite-metrics",
"object": "chat.completion.chunk",
"model": requested_model,
"choices": [],
"granite_meta": {
"actual_model": MODEL_ALIAS,
"effort": effort,
"reasoning": reasoning,
**stats.finish(),
},
}
return f"data: {json.dumps(chunk)}\n\n".encode("utf-8")
def event_stream() -> Iterator[bytes]:
done = False
try:
with upstream:
for line in _sse_lines(upstream):
if not line:
continue
if line.startswith("data:"):
chunk = line[5:].strip()
if chunk == "[DONE]":
yield metrics_event() # final metrics chunk, then DONE
yield b"data: [DONE]\n\n"
done = True
break
try:
stats.feed(json.loads(chunk))
except (json.JSONDecodeError, AttributeError):
pass
yield (line + "\n\n").encode("utf-8")
else:
yield (line + "\n").encode("utf-8")
if not done:
yield metrics_event()
yield b"data: [DONE]\n\n"
except requests.RequestException as exc:
err_json = json.dumps({"error": f"upstream stream interrupted: {exc}"})
yield f"data: {err_json}\n\n".encode("utf-8")
yield b"data: [DONE]\n\n"
return StreamingResponse(event_stream(), media_type="text/event-stream")
def _generate() -> Tuple[Dict[str, Any], float]:
t0 = time.perf_counter()
upstream = llama_chat(messages, max_tokens, temperature, top_p)
elapsed = time.perf_counter() - t0
upstream.raise_for_status()
return upstream.json(), elapsed
try:
data, elapsed = await run_in_threadpool(_generate)
except (requests.RequestException, ValueError) as exc:
return JSONResponse({"error": f"llama-server error: {exc}"}, status_code=502)
choice = (data.get("choices") or [{}])[0]
text = (choice.get("message") or {}).get("content", "")
usage = data.get("usage", {})
completion_tokens = int(usage.get("completion_tokens", 0) or 0)
# Non-streaming has no real first-token event, so TTFT is approximated by
# llama-server's own prompt-processing time (prompt_ms).
timings = data.get("timings") or {}
prompt_ms = timings.get("prompt_ms")
ttft_approx = round(float(prompt_ms), 1) if isinstance(prompt_ms, (int, float)) else None
pps = timings.get("predicted_per_second")
if isinstance(pps, (int, float)) and pps > 0:
tps: Optional[float] = round(float(pps), 2)
else:
tps = round(completion_tokens / elapsed, 2) if elapsed > 0 and completion_tokens else None
return {
"id": data.get("id", "chatcmpl-granite"),
"object": "chat.completion",
"model": requested_model,
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": text},
"finish_reason": choice.get("finish_reason", "stop"),
}
],
"usage": usage,
"granite_meta": {
"actual_model": MODEL_ALIAS,
"effort": effort,
"reasoning": reasoning,
"ttft_ms_approx": ttft_approx,
"tokens_per_second": tps,
"output_tokens": completion_tokens,
"generation_seconds": round(elapsed, 2),
},
}
@app.post("/v1/completion")
async def raw_completion(request: Request):
payload, err = await read_payload(request)
if err:
return err
err = check_secret(payload)
if err:
return err
prompt = str(payload.get("prompt") or "").strip()
if not prompt:
return JSONResponse({"error": "Field 'prompt' is required."}, status_code=400)
try:
await run_in_threadpool(start_server)
except Exception as exc:
return JSONResponse({"error": f"Inference backend unavailable: {exc}"}, status_code=503)
max_tokens = int(clamp(payload.get("max_tokens", MAX_TOKENS_DEFAULT), 16, CTX_SIZE, MAX_TOKENS_DEFAULT))
temperature = clamp(payload.get("temperature", 0.7), 0.0, 2.0, 0.7)
def _call() -> Dict[str, Any]:
upstream = requests.post(
f"{LLAMA_URL}/completion",
json={"prompt": prompt, "n_predict": max_tokens, "temperature": temperature},
timeout=(15, 900),
)
upstream.raise_for_status()
return upstream.json()
try:
data = await run_in_threadpool(_call)
except (requests.RequestException, ValueError) as exc:
return JSONResponse({"error": f"llama-server error: {exc}"}, status_code=502)
return {
"object": "text_completion",
"content": data.get("content", ""),
"tokens_predicted": data.get("tokens_predicted"),
"timing": data.get("timings"),
}
@app.post("/v1/tokenize")
async def tokenize(request: Request):
payload, err = await read_payload(request)
if err:
return err
err = check_secret(payload)
if err:
return err
content = str(payload.get("content") or "")
try:
await run_in_threadpool(start_server)
except Exception as exc:
return JSONResponse({"error": f"Inference backend unavailable: {exc}"}, status_code=503)
def _call() -> List[Any]:
resp = requests.post(
f"{LLAMA_URL}/tokenize",
json={"content": content, "add_special": False},
timeout=30,
)
resp.raise_for_status()
return resp.json().get("tokens", [])
try:
tokens = await run_in_threadpool(_call)
except (requests.RequestException, ValueError) as exc:
return JSONResponse({"error": f"tokenize failed: {exc}"}, status_code=502)
return {"token_count": len(tokens), "tokens": tokens[:50]}
@app.get("/v1/models")
def list_models():
return {
"object": "list",
"data": [
{
"id": MODEL_ALIAS,
"object": "model",
"owned_by": "ibm-granite",
"license": "Apache-2.0",
"quantization": MODEL_QUANT,
"context_size": CTX_SIZE,
"parallel_slots": PARALLEL,
}
],
}
@app.get("/health")
def health():
ok = llama_healthy()
return {
"status": "ok" if ok else "degraded",
"llama_server": ok,
"model": MODEL_ALIAS,
"uptime_seconds": round(time.time() - _started_at, 1) if _started_at else 0,
"auth_configured": bool(SECRET),
}
@app.get("/llama/health")
def llama_health_proxy():
try:
resp = requests.get(f"{LLAMA_URL}/health", timeout=5)
return JSONResponse(resp.json(), status_code=resp.status_code)
except (requests.RequestException, ValueError):
return JSONResponse({"error": "llama-server unreachable"}, status_code=503)
@app.get("/metrics")
def metrics():
try:
resp = requests.get(f"{LLAMA_URL}/metrics", timeout=10)
except requests.RequestException:
return JSONResponse({"error": "metrics unavailable"}, status_code=503)
return Response(
content=resp.content,
status_code=resp.status_code,
media_type=resp.headers.get("content-type", "text/plain"),
)
@app.get("/info")
def info():
return {
"service": "Granite 4.0 H-Tiny self-hosted API",
"model": MODEL_ALIAS,
"model_repo": MODEL_REPO,
"quantization": MODEL_QUANT,
"context_size": CTX_SIZE,
"max_output_tokens": MAX_TOKENS_DEFAULT,
"threads": THREADS,
"parallel": PARALLEL,
"auth": "payload field 'secret' must match SECRET env",
"allowed_efforts": EFFORT_CHOICES,
"reasoning_flag": "payload['reasoning'] (default true) appends effort guidance to system prompt",
"metrics": "granite_meta has ttft_ms / tokens_per_second (stream: final chunk; non-stream: in response)",
"routes": [
"POST /v1/chat/completion",
"POST /v1/chat/completions",
"POST /v1/completion",
"POST /v1/tokenize",
"GET /v1/models",
"GET /health",
"GET /llama/health",
"GET /metrics",
"GET /info",
"GET / (Gradio UI)",
],
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Gradio UI (mounted at /)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
IDLE_METRICS = "Send a message to measure TTFT and generation speed."
def _content_to_text(content: Any) -> str:
"""Chatbot history content may be a str or a list of content blocks."""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, dict):
t = content.get("text")
return t if isinstance(t, str) else ""
if isinstance(content, list):
parts: List[str] = []
for p in content:
if isinstance(p, str):
parts.append(p)
elif isinstance(p, dict) and isinstance(p.get("text"), str):
parts.append(p["text"])
return "".join(parts)
return str(content)
def ui_respond(message, history, secret, effort, reasoning, system_prompt):
"""Generator yielding (chatbot_history, textbox_value, metrics_markdown)."""
prior: List[Dict[str, str]] = []
for item in history or []:
if isinstance(item, dict) and item.get("role") in ("user", "assistant"):
prior.append({"role": item["role"], "content": _content_to_text(item.get("content"))})
message = (message or "").strip()
if not message:
gr.Warning("Enter a message first.")
yield prior, "", gr.update()
return
if not SECRET:
gr.Warning("Server SECRET env is not configured.")
yield prior, message, gr.update()
return
if not secret_matches(secret, SECRET):
gr.Warning("Wrong Secret")
yield prior, message, gr.update()
return
payload = {
"prompt": message,
"effort": effort,
"reasoning": reasoning,
"system_prompt": system_prompt or "",
}
system_content, eff, rsn = build_system_prompt(payload)
messages: List[Dict[str, str]] = [{"role": "system", "content": system_content}]
messages.extend(prior[-10:])
messages.append({"role": "user", "content": message})
shown = prior + [{"role": "user", "content": message}]
yield shown, "", "β³ Waiting for the first token..."
def with_reply(text: str) -> List[Dict[str, str]]:
return shown + [{"role": "assistant", "content": text}]
try:
start_server()
except Exception as exc:
yield with_reply(f"β Inference backend unavailable: {exc}"), "", "β Backend unavailable."
return
stats = StreamStats()
try:
upstream = llama_chat(messages, MAX_TOKENS_DEFAULT, 0.7, 0.9, stream=True)
except requests.RequestException as exc:
yield with_reply(f"β llama-server error: {exc}"), "", "β Request failed."
return
try:
with upstream:
if not upstream.ok:
yield (
with_reply(f"β llama-server error: HTTP {upstream.status_code}: {upstream.text[:300]}"),
"",
"β Request failed.",
)
return
for line in _sse_lines(upstream):
if not line or not line.startswith("data:"):
continue
chunk = line[5:].strip()
if chunk == "[DONE]":
break
try:
data = json.loads(chunk)
except json.JSONDecodeError:
continue
if not isinstance(data, dict):
continue
piece = stats.feed(data)
if piece:
live = stats.live()
if stats.chunks == 1 and live:
print(f"[ui] TTFT: {live['ttft_ms']:.0f} ms Β· effort={eff} Β· reasoning={rsn}")
status = "π **Streaming**"
if live:
status += (
f" Β· TTFT: {live['ttft_ms']:.0f} ms"
f" Β· β{live['approx_tokens_per_second']:.1f} tokens/s"
)
yield with_reply(stats.text), "", status
except requests.RequestException as exc:
yield (
with_reply((stats.text + "\n\n" if stats.text else "") + f"β Stream interrupted: {exc}"),
"",
"β Stream interrupted.",
)
return
if not stats.text:
yield with_reply("(no output β check Space logs)"), "", "β οΈ No generated text received."
return
yield with_reply(stats.text), "", format_metrics_md(stats.finish())
with gr.Blocks(title="Granite 4.0 H-Tiny") as demo:
gr.Markdown("# Granite 4.0 H-Tiny β‘\nSelf-hosted Β· optimized llama.cpp Β· secret-protected API")
with gr.Accordion("π Access", open=True):
secret_box = gr.Textbox(label="Secret", type="password", placeholder="SECRET from env")
with gr.Row():
effort_dd = gr.Dropdown(choices=EFFORT_CHOICES, value="medium", label="Effort")
reasoning_cb = gr.Checkbox(value=True, label="Reasoning (appends effort guidance)")
sys_box = gr.Textbox(
label="System prompt (optional override)",
placeholder="Leave empty to use the default Granite persona.",
lines=2,
)
try:
chat = gr.Chatbot(height=440, type="messages")
except TypeError: # newer Gradio: "messages" is the only format
chat = gr.Chatbot(height=440)
metrics_md = gr.Markdown(IDLE_METRICS)
msg_box = gr.Textbox(label="Message", placeholder="Ask Granite something...", lines=2)
with gr.Row():
send_btn = gr.Button("Send", variant="primary", scale=4)
clear_btn = gr.Button("Clear", scale=1)
ui_inputs = [msg_box, chat, secret_box, effort_dd, reasoning_cb, sys_box]
ui_outputs = [chat, msg_box, metrics_md]
msg_box.submit(ui_respond, inputs=ui_inputs, outputs=ui_outputs)
send_btn.click(ui_respond, inputs=ui_inputs, outputs=ui_outputs)
clear_btn.click(lambda: ([], "", IDLE_METRICS), outputs=ui_outputs)
# Mount Gradio at "/" β API routes above take precedence (registered first).
try:
app = gr.mount_gradio_app(app, demo, path="/", show_error=True, ssr_mode=False)
except TypeError: # older Gradio has no ssr_mode argument
app = gr.mount_gradio_app(app, demo, path="/", show_error=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Boot
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def main() -> None:
if not SECRET:
print("WARNING: SECRET env is not set β all API requests will be rejected (503).")
print("[app] booting llama-server (prebuilt binary, no compile)...")
try:
start_server()
except Exception as exc: # keep the web app up; requests retry start_server()
print(f"[app] initial llama-server start failed: {exc}")
print(f"[app] serving on 0.0.0.0:{PORT}")
uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="info")
if __name__ == "__main__":
main()
"""
Granite 4.0 H-Tiny β Self-hosted OpenAI-style API + Gradio UI.
- Prebuilt llama.cpp (no clone, no compile β downloads official release binary).
- One-time model download via huggingface_hub (cached).
- FastAPI custom routes with payload-secret auth (SECRET from env).
- effort (low|medium|high) + reasoning flag -> system prompt handling.
- Streaming support, /metrics, /v1/models, token counting, health routes.
Env:
SECRET (required) β API secret checked against payload["secret"]
PORT (default 7860)
LLAMA_PORT (default 8081)
MODEL_REPO (default ibm-granite/granite-4.0-h-tiny-GGUF)
MODEL_QUANT (default Q4_K_M)
MODEL_FILE (optional exact gguf filename override)
MODEL_ALIAS (default granite-4.0-h-tiny)
CTX_SIZE (default 8192) β context PER parallel slot
THREADS (default 2)
PARALLEL (default 2)
LLAMA_EXTRA_ARGS (optional comma-separated extra llama-server flags)
LLAMA_ZIP_URL (optional override for prebuilt release archive URL)
requirements.txt: fastapi, uvicorn, gradio, requests, huggingface_hub
"""
from __future__ import annotations
import atexit
import hmac
import json
import math
import os
import shutil
import stat
import subprocess
import tarfile
import threading
import time
import urllib.request
import zipfile
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Tuple
os.environ.setdefault("GRADIO_SSR_MODE", "false")
import gradio as gr
import requests
import uvicorn
from fastapi import FastAPI, Request
from fastapi.concurrency import run_in_threadpool
from fastapi.responses import JSONResponse, Response, StreamingResponse
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ZeroGPU startup validator (kept: tiny duration, negligible GPU quota usage).
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
try:
import spaces # type: ignore
def _gpu_validation_placeholder() -> None:
return None
except Exception: # local / CPU-only environments
def _gpu_validation_placeholder() -> None:
return None
try:
_gpu_validation_placeholder()
except Exception as _exc: # never let the validator crash startup
print(f"[spaces] GPU validator call skipped: {_exc}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Configuration (all overridable via env)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SECRET = os.environ.get("SECRET", "").strip()
PORT = int(os.environ.get("PORT", "7860"))
LLAMA_PORT = int(os.environ.get("LLAMA_PORT", "8081"))
LLAMA_URL = f"http://127.0.0.1:{LLAMA_PORT}"
MODEL_REPO = os.environ.get("MODEL_REPO", "ibm-granite/granite-4.0-h-tiny-GGUF")
MODEL_QUANT = os.environ.get("MODEL_QUANT", "Q4_K_M")
MODEL_FILE = os.environ.get("MODEL_FILE", "")
MODEL_ALIAS = os.environ.get("MODEL_ALIAS", "granite-4.0-h-tiny")
CTX_SIZE = int(os.environ.get("CTX_SIZE", "8192")) # per slot
THREADS = int(os.environ.get("THREADS", "2"))
THREADS_BATCH = int(os.environ.get("THREADS_BATCH", str(THREADS)))
PARALLEL = max(1, int(os.environ.get("PARALLEL", "2")))
BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "512"))
UBATCH_SIZE = int(os.environ.get("UBATCH_SIZE", "128"))
CACHE_REUSE = int(os.environ.get("CACHE_REUSE", "256"))
MAX_TOKENS_DEFAULT = int(os.environ.get("MAX_TOKENS", "8192"))
LLAMA_DIR = Path(os.environ.get("LLAMA_DIR", "/tmp/llama"))
LLAMA_ZIP_URL = os.environ.get("LLAMA_ZIP_URL", "")
LLAMA_BIN = os.environ.get("LLAMA_SERVER_BIN", "")
LLAMA_EXTRA_ARGS = [
a.strip() for a in os.environ.get("LLAMA_EXTRA_ARGS", "").split(",") if a.strip()
]
GH_LATEST_API = "https://api.github.com/repos/ggml-org/llama.cpp/releases/latest"
STARTUP_TIMEOUT = int(os.environ.get("STARTUP_TIMEOUT", "1800"))