Spaces:
Running on Zero
Running on Zero
Upload 5 files
Browse filesFiles changed (5)
- .env.example+9-8
- .gitignore+1-1
- README.md+120-98
- app.py+416-75
- requirements.txt+5-3
12345678910# Required. Put the real value in Hugging Face Space Secrets, not in Git.LLAMA_API_KEY=replace-with-a-long-random-secret# Optional performance/model overrides:# LLAMA_N_THREADS=2# LLAMA_N_THREADS_BATCH=2# LLAMA_N_CTX=2048# LLAMA_N_BATCH=512# LLAMA_N_UBATCH=256# MODEL_ALIAS=qwen2.5-coder-0.5b-instruct1234567891011# Required in Hugging Face Space Settings > Variables and secrets > SecretsLLAMA_API_KEY=replace-with-a-long-random-secret# Optional tuning variables (set these under Space Variables)LLAMA_N_CTX=4096LLAMA_N_BATCH=1024LLAMA_N_UBATCH=512LLAMA_N_THREADS=4LLAMA_MAX_TOKENS=2048LLAMA_GPU_DURATION_MAX=60LOG_LEVEL=INFO
123456.env.venv/__pycache__/*.py[cod].cache/models/123456.env__pycache__/*.py[cod].cache/models/*.gguf
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168---title: Qwen2.5 Coder 0.5B APIemoji: ⚡colorFrom: bluecolorTo: purplesdk: gradiopython_version: "3.11"app_file: app.py---# Qwen2.5-Coder-0.5B-Instruct REST APIA Hugging Face **Gradio SDK Space** that serves the official Qwen2.5-Coder-0.5B-Instruct `Q4_K_M` GGUF model through a llama.cpp-backed, OpenAI-compatible REST API.- Model: `Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF`- Quantization: `Q4_K_M` (about 491 MB on the Hub)- Runtime: `llama-cpp-python` (Python bindings to llama.cpp)- Default hardware target: Hugging Face CPU Basic (2 vCPU / 16 GB RAM)- Authentication: one required bearer API key from the Space Secret `LLAMA_API_KEY`- Streaming: supported by `/v1/chat/completions`- Docker: **not required**## Deploy to Hugging Face Spaces1. Create a new Space and select **Gradio** as the SDK.2. Upload or push all files from this project to the Space repository.3. Open **Settings → Variables and secrets**.4. Add a **Secret** named `LLAMA_API_KEY` and set a long, random value. Do not put the key in this repository or in a normal variable.5. Select **CPU Basic** hardware if it is not already selected, then let the Space build and start.6. Once it is running, the API base URL is:`https://YOUR-SPACE-NAME.hf.space/v1`The model file is downloaded automatically from the official Qwen repository on first startup. It is not included in this ZIP.> **Hugging Face plan note (checked November 19, 2026):** Hugging Face documents CPU Basic as 2 vCPU / 16 GB RAM with no hourly compute charge, but creating a compute-backed Gradio or Docker Space on a personal account requires PRO. Free personal accounts can still run up to two Gradio Spaces on ZeroGPU; this project is a CPU-based llama.cpp service, not a ZeroGPU app. So the runtime hardware can be CPU Basic at no hourly cost, but a free personal account alone may not be able to create/run this kind of Space.## API authenticationEvery `/v1` inference/API request must include the single Space Secret as a Bearer token:```httpAuthorization: Bearer YOUR_LLAMA_API_KEY```The key is checked by the llama-cpp-python API server. The public `/health` endpoint is intentionally unauthenticated so hosting health checks can reach it. Do not expose or share the key.## Endpoints| Method | Endpoint | Authentication | Purpose ||---|---|---|---|| `GET` | `/health` | No | Health check || `GET` | `/v1/models` | Bearer key | List the served model || `POST` | `/v1/chat/completions` | Bearer key | Chat Completions; supports streaming || `POST` | `/v1/completions` | Bearer key | Text Completions || `GET` | `/docs` | No | OpenAPI documentation || `GET` | `/console` | No | Small deployment/API information page |## Quick test with curlReplace the Space URL and key:```bashcurl https://YOUR-SPACE-NAME.hf.space/health``````bashcurl https://YOUR-SPACE-NAME.hf.space/v1/chat/completions \-H "Authorization: Bearer YOUR_LLAMA_API_KEY" \-H "Content-Type: application/json" \-d '{"model": "qwen2.5-coder-0.5b-instruct","messages": [{"role": "system", "content": "You are a precise coding assistant."},{"role": "user", "content": "Write a JavaScript function that checks whether a string is a palindrome."}],"temperature": 0.2,"max_tokens": 256,"stream": false}'```Streaming response:```bashcurl -N https://YOUR-SPACE-NAME.hf.space/v1/chat/completions \-H "Authorization: Bearer YOUR_LLAMA_API_KEY" \-H "Content-Type: application/json" \-d '{"model": "qwen2.5-coder-0.5b-instruct","messages": [{"role": "user", "content": "Explain JavaScript promises in three bullet points."}],"max_tokens": 256,"stream": true}'```## Use with the OpenAI SDK```bashnpm install openai``````jsimport OpenAI from "openai";const client = new OpenAI({baseURL: "https://YOUR-SPACE-NAME.hf.space/v1",apiKey: process.env.LLAMA_API_KEY,});const response = await client.chat.completions.create({model: "qwen2.5-coder-0.5b-instruct",messages: [{ role: "user", content: "Write a TypeScript debounce function." }],max_tokens: 256,});console.log(response.choices[0].message.content);```Set `LLAMA_API_KEY` in your local shell for the client example. The server-side key belongs only in Hugging Face Space Secrets.## Performance settingsThis project is biased toward generation speed on a small CPU instance:- Builds llama-cpp-python from source with `GGML_NATIVE`, OpenMP, and OpenBLAS enabled. `GGML_NATIVE` lets the compiler use the CPU instructions available during the build.- Uses two inference threads by default to match CPU Basic's two vCPUs.- Uses memory-mapped model loading, a 512-token logical batch, and a 256-token physical micro-batch.- Starts with a 2,048-token context to reduce per-request memory and attention work. Increase it when larger prompts are more important than speed.- Uses Q4_K_M rather than a larger quantization to keep the model compact.These are performance-oriented defaults, not a guaranteed tokens-per-second figure. Actual throughput depends on the Space host CPU, prompt length, generated length, and concurrent traffic. CPU Basic is not a GPU accelerator. The service serializes access to its single model instance to avoid CPU oversubscription and model-state conflicts.### Optional Space variablesOnly `LLAMA_API_KEY` is required. The following variables are optional:| Variable | Default | Meaning ||---|---:|---|| `MODEL_REPO_ID` | `Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF` | Hugging Face model repository || `MODEL_FILENAME` | `qwen2.5-coder-0.5b-instruct-q4_k_m.gguf` | Exact GGUF file to download || `MODEL_ALIAS` | `qwen2.5-coder-0.5b-instruct` | Model name accepted in API requests || `LLAMA_N_THREADS` | `2` | Generation CPU threads || `LLAMA_N_THREADS_BATCH` | `2` | Prompt-processing CPU threads || `LLAMA_N_CTX` | `2048` | Context window size || `LLAMA_N_BATCH` | `512` | Logical prompt batch size || `LLAMA_N_UBATCH` | `256` | Physical prompt micro-batch size |Do not set `LLAMA_API_KEY` as a public variable. Store it under **Secrets**.## Local runThis project targets the Hugging Face Spaces Gradio environment. To run locally, install the Debian packages listed in `packages.txt`, install `requirements.txt`, set `LLAMA_API_KEY`, and run:```bashpython app.py```The server listens on port `7860`.## Model and API references- [Official Qwen GGUF repository](https://huggingface.co/Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF)- [llama-cpp-python](https://github.com/abetlen/llama-cpp-python)- [llama.cpp server documentation](https://github.com/ggml-org/llama.cpp/tree/master/tools/server)- [Hugging Face Spaces overview](https://huggingface.co/docs/hub/spaces-overview)The Qwen model repository is licensed under Apache-2.0. Review the model card and license before redistribution or commercial use.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190---title: Qwen2.5 Coder 0.5B Instruct APIemoji: ⚡colorFrom: bluecolorTo: indigosdk: gradiopython_version: 3.12app_file: app.pypinned: false---# Qwen2.5-Coder-0.5B-Instruct — ZeroGPU REST APIAn OpenAI-compatible REST API for the official Qwen2.5-Coder-0.5B-Instruct **Q4_K_M GGUF** model, powered by `llama.cpp` with CUDA GPU offload on Hugging Face ZeroGPU.## What changed from the CPU project- Uses `@spaces.GPU` to request ZeroGPU for inference calls.- FastAPI routes submit inference jobs through the internal Gradio queue; this is important because ZeroGPU schedules registered Gradio GPU callbacks.- Forwards Hugging Face's incoming `X-IP-Token` to the internal queue when present, so requests can be attributed to the caller instead of automatically falling into the anonymous pool.- Uses `n_gpu_layers=-1` to offload all model layers to the GPU.- Uses CUDA 13.0 prebuilt `llama-cpp-python` wheels (`0.3.36`) instead of building llama.cpp from source during Space startup.- `--only-binary=llama-cpp-python` prevents pip from silently falling back to a source build.- Uses Flash Attention and larger batches for throughput.- Keeps one API credential: the `LLAMA_API_KEY` Space Secret.- The model file is downloaded to the Space cache at startup; it is not included in this repository.> **Compatibility note:** Hugging Face documents ZeroGPU as primarily compatible with PyTorch-based Spaces and warns that some other GPU workloads may have limited compatibility. This project uses native CUDA through llama.cpp inside a ZeroGPU worker; that exact combination is not guaranteed by Hugging Face. It deliberately refuses CPU fallback. The first real inference request is the definitive compatibility test. See [ZeroGPU docs](https://huggingface.co/docs/hub/spaces-zerogpu) and [llama-cpp-python CUDA installation](https://github.com/abetlen/llama-cpp-python#cuda).## Create / update the Space1. Create a Space with **SDK: Gradio**.2. Keep the Space hardware set to **ZeroGPU**.3. Upload the contents of this folder to the Space's `main` branch (replace the old `app.py`, `README.md`, and `requirements.txt`).4. Open **Settings → Variables and secrets → New secret**.5. Add `LLAMA_API_KEY` with a long random value. The value is not stored in this repository.6. Let the Space rebuild. The Space uses Python 3.12. The dependency step should install the prebuilt CUDA 13.0 wheel; it should not print `Building wheel for llama-cpp-python`. The `gradio`, `spaces`, and CUDA-enabled `torch` packages are supplied by the Hugging Face ZeroGPU Gradio runtime and are intentionally not overridden in `requirements.txt`.Generate a key locally:```bashpython -c "import secrets; print(secrets.token_urlsafe(48))"```Do not put the API key in a regular Variable or commit it to source control. Use a **Secret**.## Model- Repository: `Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF`- File: `qwen2.5-coder-0.5b-instruct-q4_k_m.gguf`- Quantization: `Q4_K_M`- Approximate download size: 491 MBThe model is downloaded automatically on startup with `huggingface_hub`.## APIYour Space URL looks like:```texthttps://YOUR-USERNAME-qwen25-coder-api.hf.space```All `/v1` endpoints require:```httpAuthorization: Bearer YOUR_LLAMA_API_KEY```| Method | Endpoint | Auth ||---|---|---|| `GET` | `/health` | No || `GET` | `/v1/models` | Yes || `POST` | `/v1/chat/completions` | Yes || `POST` | `/v1/completions` | Yes || `GET` | `/docs` | No |### Chat completion```bashcurl https://YOUR-USERNAME-qwen25-coder-api.hf.space/v1/chat/completions \-H "Authorization: Bearer YOUR_LLAMA_API_KEY" \-H "Content-Type: application/json" \-d '{"model": "qwen2.5-coder-0.5b-instruct","messages": [{"role": "system", "content": "You are an expert programming assistant."},{"role": "user", "content": "Write a JavaScript function to debounce another function."}],"temperature": 0.2,"max_tokens": 512,"stream": false}'```### Streaming```bashcurl -N https://YOUR-USERNAME-qwen25-coder-api.hf.space/v1/chat/completions \-H "Authorization: Bearer YOUR_LLAMA_API_KEY" \-H "Content-Type: application/json" \-d '{"model": "qwen2.5-coder-0.5b-instruct","messages": [{"role": "user", "content": "Explain JavaScript promises with a short example."}],"temperature": 0.2,"max_tokens": 512,"stream": true}'```### Python OpenAI SDK```bashpip install openai``````pythonimport osfrom openai import OpenAIclient = OpenAI(base_url="https://YOUR-USERNAME-qwen25-coder-api.hf.space/v1",api_key=os.environ["LLAMA_API_KEY"],)result = client.chat.completions.create(model="qwen2.5-coder-0.5b-instruct",messages=[{"role": "user", "content": "Write a Python binary search."}],temperature=0.2,max_tokens=512,)print(result.choices[0].message.content)```## Performance settingsThe defaults are tuned for the small 0.5B model and ZeroGPU's RTX PRO 6000 Blackwell allocation:- Full layer offload (`n_gpu_layers=-1`)- Flash Attention enabled- `n_ctx=4096`- `n_batch=1024`, `n_ubatch=512`- Memory mapping enabled- Generation defaults to 512 tokens; maximum accepted output is 2048 tokensOptional Space **Variables** (not Secrets):| Variable | Default | Meaning ||---|---:|---|| `LLAMA_N_CTX` | `4096` | Context window || `LLAMA_N_BATCH` | `1024` | Prompt batch size || `LLAMA_N_UBATCH` | `512` | Physical micro-batch size || `LLAMA_N_THREADS` | `4` | CPU threads for sampling / host work || `LLAMA_MAX_TOKENS` | `2048` | API maximum output limit || `LLAMA_GPU_DURATION_MAX` | `60` | Maximum reserved ZeroGPU seconds per inference || `LOG_LEVEL` | `INFO` | Logging verbosity |Don't set `n_gpu_layers` to zero. This build is intended to use the GPU only.## ZeroGPU behavior and limits- ZeroGPU is dynamically allocated. The model is loaded in the GPU worker on its first request and may remain cached while that worker stays warm. A cold worker needs to load it again.- GPU quota and queue priority depend on the caller's Hugging Face account tier and authentication context. A custom `LLAMA_API_KEY` authenticates this API, but it is **not** a Hugging Face login token and does not itself grant the caller a personal ZeroGPU quota.- FastAPI does not call the decorated GPU functions directly. It submits each request to the registered Gradio event queue, where ZeroGPU can allocate the GPU.- `@spaces.GPU` reserves GPU time for inference. Requests are capped to keep reservations bounded.- If Hugging Face provides an `X-IP-Token` header on the incoming request, the API forwards it to the internal Gradio event call. A caller that does not receive this header may be treated as unauthenticated by ZeroGPU.- A successful package install does not prove CUDA works. Check the logs from the first inference call for a positive GPU offload message (for example, `offloaded ... layers to GPU`).- If the CUDA wheel cannot load, the CUDA runtime is missing, the GPU worker cannot access native CUDA, or the Blackwell kernel is unsupported, inference returns an error. It will not continue on CPU.## Troubleshooting### The build still says `Building wheel for llama-cpp-python`This project pins a binary-only CUDA wheel. Make sure the old `requirements.txt` was replaced and the new requirements were committed. The binary-only flag should make pip fail with `No matching distribution found` rather than compile from source if the wheel is unavailable for that Python/platform combination.### `llama_supports_gpu_offload()` is falseThe installed wheel is not exposing a usable GPU backend. Check that the `cu130` index was used and that the CUDA libraries are present in the ZeroGPU runtime. Do not remove the GPU check or set `n_gpu_layers=0` to hide the issue.### `libcudart.so` / `libcublas.so` cannot be foundThe CUDA runtime libraries needed by the prebuilt wheel are missing or not visible to the dynamic linker. Check the ZeroGPU base runtime and the installed PyTorch CUDA runtime. The project does not compile a local replacement.### `no kernel image is available`The wheel's CUDA kernels do not match the allocated GPU architecture. Do not fall back to CPU and claim GPU acceleration. A wheel built for the active GPU architecture is required.## Local developmentThe app is designed for Hugging Face ZeroGPU. A local CPU environment is intentionally not treated as a valid production test because this build requires a working CUDA backend and refuses CPU inference.
123456789101112131415161718192021221 unmodified line24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136from __future__ import annotationsimport loggingimport osfrom pathlib import Pathimport gradio as grimport uvicornfrom huggingface_hub import hf_hub_downloadfrom llama_cpp.server.app import create_appfrom llama_cpp.server.settings import Settingslogging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO").upper(),format="%(asctime)s %(levelname)s %(name)s: %(message)s",)logger = logging.getLogger("qwen-space")SPACE_PORT = int(os.getenv("PORT", "7860"))MODEL_REPO_ID = os.getenv("MODEL_REPO_ID", "Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF")1 unmodified line"MODEL_FILENAME", "qwen2.5-coder-0.5b-instruct-q4_k_m.gguf")MODEL_ALIAS = os.getenv("MODEL_ALIAS", "qwen2.5-coder-0.5b-instruct")def _read_positive_int(name: str, default: int) -> int:raw = os.getenv(name, str(default))try:value = int(raw)except ValueError as exc:raise RuntimeError(f"{name} must be an integer; received {raw!r}") from excif value < 1:raise RuntimeError(f"{name} must be >= 1; received {value}")return valuedef download_model() -> str:"""Fetch exactly the selected GGUF file into the Hugging Face cache."""logger.info("Downloading model %s / %s", MODEL_REPO_ID, MODEL_FILENAME)model_path = hf_hub_download(repo_id=MODEL_REPO_ID,filename=MODEL_FILENAME,cache_dir=os.getenv("HF_HUB_CACHE") or None,token=os.getenv("HF_TOKEN") or None,)size_mb = Path(model_path).stat().st_size / (1024 * 1024)logger.info("Model ready at %s (%.1f MiB)", model_path, size_mb)return model_pathdef build_api_app():api_key = os.getenv("LLAMA_API_KEY", "").strip()if not api_key:raise RuntimeError("Missing required Space Secret LLAMA_API_KEY. Add it under ""Settings > Variables and secrets > New secret.")model_path = download_model()threads = _read_positive_int("LLAMA_N_THREADS", 2)batch_threads = _read_positive_int("LLAMA_N_THREADS_BATCH", 2)# llama-cpp-python is the llama.cpp C/C++ inference runtime with its# OpenAI-compatible FastAPI server and built-in Bearer-key authentication.settings = Settings(model=model_path,model_alias=MODEL_ALIAS,host="0.0.0.0",port=SPACE_PORT,api_key=api_key,chat_format="chatml",n_ctx=_read_positive_int("LLAMA_N_CTX", 2048),n_threads=threads,n_threads_batch=batch_threads,n_batch=_read_positive_int("LLAMA_N_BATCH", 512),n_ubatch=_read_positive_int("LLAMA_N_UBATCH", 256),n_gpu_layers=0,use_mmap=True,use_mlock=False,flash_attn=False,verbose=False,)api_app = create_app(settings=settings)# A lightweight public health route for Space monitoring. Inference routes# remain protected by the server's built-in Bearer-key dependency.@api_app.get("/health", include_in_schema=False)async def health():return {"status": "ok", "model": MODEL_ALIAS}return api_appdef build_console() -> gr.Blocks:with gr.Blocks(title="Qwen2.5 Coder API", analytics_enabled=False) as demo:gr.Markdown("""# ⚡ Qwen2.5-Coder-0.5B-Instruct APIThe model is running through llama.cpp. This Space exposes anOpenAI-compatible REST API; inference endpoints require yourconfigured Bearer API key.**API base URL**```text/v1```**Main endpoints**- `GET /health` — public service health check- `GET /v1/models` — model list (Bearer key required)- `POST /v1/chat/completions` — chat and streaming completions- `POST /v1/completions` — text completions- `GET /docs` — OpenAPI schemaSend `Authorization: Bearer YOUR_LLAMA_API_KEY` with `/v1` requests.The API key is never displayed on this page.""")return demodef main() -> None:api_app = build_api_app()app = gr.mount_gradio_app(api_app, build_console(), path="/console")logger.info("Starting API on 0.0.0.0:%s", SPACE_PORT)uvicorn.run(app, host="0.0.0.0", port=SPACE_PORT, log_level="info")if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839401 unmodified line42434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477from __future__ import annotations# ZeroGPU must be imported before torch or any module that can touch CUDA.import spacesimport jsonimport loggingimport osimport secretsimport threadingimport timefrom functools import lru_cachefrom pathlib import Pathfrom typing import Any, Iterator, Optional, Unionimport gradio as grimport torch # ZeroGPU's Gradio image provides its matching CUDA-enabled PyTorch.import uvicornfrom fastapi import Depends, FastAPI, Header, HTTPException, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import RedirectResponse, StreamingResponsefrom gradio_client import Clientfrom huggingface_hub import hf_hub_downloadfrom pydantic import BaseModel, ConfigDict, Field# Import llama.cpp after the ZeroGPU bootstrap and the platform CUDA runtime.import llama_cppfrom llama_cpp import Llama, llama_supports_gpu_offloadlogging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO").upper(),format="%(asctime)s %(levelname)s %(process)d %(name)s: %(message)s",)logger = logging.getLogger("qwen-zerogpu-api")PORT = int(os.getenv("PORT", "7860"))MODEL_REPO_ID = os.getenv("MODEL_REPO_ID", "Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF")1 unmodified line"MODEL_FILENAME", "qwen2.5-coder-0.5b-instruct-q4_k_m.gguf")MODEL_ALIAS = os.getenv("MODEL_ALIAS", "qwen2.5-coder-0.5b-instruct")API_KEY = os.getenv("LLAMA_API_KEY", "").strip()def positive_int(name: str, default: int, maximum: Optional[int] = None) -> int:raw = os.getenv(name, str(default))try:value = int(raw)except ValueError as exc:raise RuntimeError(f"{name} must be an integer, got {raw!r}") from excif value < 1:raise RuntimeError(f"{name} must be >= 1")if maximum is not None and value > maximum:raise RuntimeError(f"{name} must be <= {maximum}")return valueN_CTX = positive_int("LLAMA_N_CTX", 4096, 32768)N_BATCH = positive_int("LLAMA_N_BATCH", 1024, 4096)N_UBATCH = positive_int("LLAMA_N_UBATCH", 512, N_BATCH)N_THREADS = positive_int("LLAMA_N_THREADS", 4, 64)MAX_TOKENS = positive_int("LLAMA_MAX_TOKENS", 2048, 8192)GPU_DURATION_MAX = positive_int("LLAMA_GPU_DURATION_MAX", 60, 120)# This cache is created only inside a ZeroGPU worker. It is not initialized in# the main web process, which has no physical GPU allocation._MODEL: Optional[Llama] = None_MODEL_PID: Optional[int] = Nonedef download_model() -> str:logger.info("Downloading/checking model: %s / %s", MODEL_REPO_ID, MODEL_FILENAME)path = hf_hub_download(repo_id=MODEL_REPO_ID,filename=MODEL_FILENAME,token=os.getenv("HF_TOKEN") or None,)size_mb = Path(path).stat().st_size / (1024 * 1024)logger.info("Model file available: %s (%.1f MiB)", path, size_mb)return path# Download the model once into the Hub cache. This step does not request a GPU.MODEL_PATH = download_model()def get_model() -> Llama:"""Load/cache llama.cpp in the active ZeroGPU worker process."""global _MODEL, _MODEL_PIDpid = os.getpid()if _MODEL is not None and _MODEL_PID == pid:return _MODELif not llama_supports_gpu_offload():raise RuntimeError("The installed llama.cpp wheel has no usable CUDA backend in this ""ZeroGPU worker. CPU fallback is disabled. Check the CUDA wheel, ""runtime libraries, and ZeroGPU compatibility.")logger.info("Initializing llama.cpp with full CUDA layer offload (n_gpu_layers=-1), pid=%s",pid,)started = time.perf_counter()model = Llama(model_path=MODEL_PATH,n_gpu_layers=-1,main_gpu=0,n_ctx=N_CTX,n_batch=N_BATCH,n_ubatch=N_UBATCH,n_threads=N_THREADS,n_threads_batch=N_THREADS,offload_kqv=True,flash_attn=True,use_mmap=True,use_mlock=False,verbose=os.getenv("LLAMA_VERBOSE", "1") == "1",)_MODEL = model_MODEL_PID = pidlogger.info("CUDA model initialized in %.2fs (worker pid=%s)",time.perf_counter() - started,pid,)return modeldef gpu_duration(payload: dict[str, Any], api_key: str) -> int:"""Bound each ZeroGPU reservation and keep the default request short."""try:requested = int(payload.get("max_tokens") or 512)except (TypeError, ValueError):requested = 512requested = max(1, min(requested, MAX_TOKENS))# Includes a cold worker/model-load allowance plus output-generation time.return min(GPU_DURATION_MAX, max(20, 15 + int(requested * 0.04)))def verify_worker_key(api_key: str) -> None:if not api_key or not secrets.compare_digest(str(api_key), API_KEY):raise PermissionError("Invalid API key")def chat_kwargs(payload: dict[str, Any]) -> dict[str, Any]:max_tokens = int(payload.get("max_tokens") or 512)if max_tokens < 1 or max_tokens > MAX_TOKENS:raise ValueError(f"max_tokens must be between 1 and {MAX_TOKENS}")kwargs: dict[str, Any] = {"temperature": float(payload.get("temperature", 0.2)),"top_p": float(payload.get("top_p", 0.95)),"max_tokens": max_tokens,"repeat_penalty": float(payload.get("repeat_penalty", 1.05)),"presence_penalty": float(payload.get("presence_penalty", 0.0)),"frequency_penalty": float(payload.get("frequency_penalty", 0.0)),"stream": bool(payload.get("stream", False)),"model": MODEL_ALIAS,}if payload.get("stop") is not None:kwargs["stop"] = payload["stop"]if payload.get("seed") is not None:kwargs["seed"] = int(payload["seed"])return kwargs# These functions are intentionally the functions bound to Gradio events.# ZeroGPU discovers the decorated callbacks through Gradio's event registry.@spaces.GPU(duration=gpu_duration)def gpu_chat_completion(payload: dict[str, Any], api_key: str) -> dict[str, Any]:verify_worker_key(api_key)model = get_model()started = time.perf_counter()result = model.create_chat_completion(messages=payload["messages"],**chat_kwargs(payload),)elapsed = max(time.perf_counter() - started, 1e-6)usage = result.get("usage", {})completion_tokens = int(usage.get("completion_tokens", 0))logger.info("Chat request finished: %s output tokens in %.3fs (%.1f tok/s)",completion_tokens,elapsed,completion_tokens / elapsed,)return result@spaces.GPU(duration=gpu_duration)def gpu_chat_stream(payload: dict[str, Any], api_key: str) -> Iterator[str]:verify_worker_key(api_key)try:model = get_model()kwargs = chat_kwargs(payload)kwargs["stream"] = Truefor chunk in model.create_chat_completion(messages=payload["messages"],**kwargs,):yield "data: " + json.dumps(chunk, ensure_ascii=False) + "\n\n"yield "data: [DONE]\n\n"except Exception as exc:logger.exception("Streaming inference failed")error = {"error": {"message": str(exc), "type": "server_error"}}yield "data: " + json.dumps(error, ensure_ascii=False) + "\n\n"yield "data: [DONE]\n\n"@spaces.GPU(duration=gpu_duration)def gpu_text_completion(payload: dict[str, Any], api_key: str) -> dict[str, Any]:verify_worker_key(api_key)model = get_model()max_tokens = int(payload.get("max_tokens") or 512)if max_tokens < 1 or max_tokens > MAX_TOKENS:raise ValueError(f"max_tokens must be between 1 and {MAX_TOKENS}")kwargs: dict[str, Any] = {"prompt": payload["prompt"],"temperature": float(payload.get("temperature", 0.2)),"top_p": float(payload.get("top_p", 0.95)),"max_tokens": max_tokens,"repeat_penalty": float(payload.get("repeat_penalty", 1.05)),"stream": False,"model": MODEL_ALIAS,}if payload.get("stop") is not None:kwargs["stop"] = payload["stop"]if payload.get("seed") is not None:kwargs["seed"] = int(payload["seed"])return model.create_completion(**kwargs)class ChatRequest(BaseModel):model: str = MODEL_ALIASmessages: list[dict[str, Any]]temperature: float = Field(default=0.2, ge=0, le=2)top_p: float = Field(default=0.95, gt=0, le=1)max_tokens: int = Field(default=512, ge=1, le=MAX_TOKENS)stream: bool = Falsestop: Optional[Union[str, list[str]]] = Nonepresence_penalty: float = Field(default=0.0, ge=-2, le=2)frequency_penalty: float = Field(default=0.0, ge=-2, le=2)repeat_penalty: float = Field(default=1.05, ge=0.5, le=2)seed: Optional[int] = Nonemodel_config = ConfigDict(extra="ignore")class CompletionRequest(BaseModel):model: str = MODEL_ALIASprompt: strtemperature: float = Field(default=0.2, ge=0, le=2)top_p: float = Field(default=0.95, gt=0, le=1)max_tokens: int = Field(default=512, ge=1, le=MAX_TOKENS)stream: bool = Falsestop: Optional[Union[str, list[str]]] = Nonerepeat_penalty: float = Field(default=1.05, ge=0.5, le=2)seed: Optional[int] = Nonemodel_config = ConfigDict(extra="ignore")if not API_KEY:raise RuntimeError("Missing required Space Secret LLAMA_API_KEY. Add it under ""Settings → Variables and secrets → Secrets.")api = FastAPI(title="Qwen2.5 Coder ZeroGPU API",version="2.1.0",description=("OpenAI-compatible REST API backed by Qwen2.5-Coder-0.5B-Instruct ""Q4_K_M through llama.cpp CUDA on Hugging Face ZeroGPU."),)api.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=False,allow_methods=["GET", "POST", "OPTIONS"],allow_headers=["Authorization", "Content-Type", "X-IP-Token"],)def require_api_key(authorization: Optional[str] = Header(default=None)) -> None:if not authorization or not authorization.startswith("Bearer "):raise HTTPException(status_code=401, detail="Missing Bearer API key")supplied = authorization[7:].strip()if not secrets.compare_digest(supplied, API_KEY):raise HTTPException(status_code=401, detail="Invalid API key")@lru_cache(maxsize=1)def get_internal_gradio_client() -> Client:"""Connect to this Space's Gradio queue so ZeroGPU schedules the callback."""url = f"http://127.0.0.1:{PORT}/console"logger.info("Connecting internal Gradio client to %s", url)return Client(url,verbose=False,analytics_enabled=False,max_workers=8,)def submit_gpu_job(api_name: str,payload: dict[str, Any],request: Request,):# Hugging Face adds this caller-specific token at the Space ingress. Forward# it through the internal Gradio request so ZeroGPU can attribute quota to# the real caller instead of treating every proxied request as anonymous.incoming_token = request.headers.get("x-ip-token")headers = {"X-IP-Token": incoming_token} if incoming_token else Noneclient = get_internal_gradio_client()return client.submit(payload, API_KEY, api_name=api_name, headers=headers)@api.get("/health")def health() -> dict[str, Any]:return {"status": "ok","model": MODEL_ALIAS,"quantization": "Q4_K_M","runtime": "llama.cpp","gpu": "ZeroGPU on-demand CUDA","cuda_backend_probe": "deferred until a GPU worker is allocated","model_downloaded": Path(MODEL_PATH).is_file(),"model_loaded": "inside a ZeroGPU worker on first inference","gpu_offload_required": True,}@api.get("/v1/models", dependencies=[Depends(require_api_key)])def list_models() -> dict[str, Any]:return {"object": "list","data": [{"id": MODEL_ALIAS,"object": "model","created": 0,"owned_by": "qwen",}],}@api.post("/v1/chat/completions", dependencies=[Depends(require_api_key)])def chat_completions(body: ChatRequest, request: Request):if not body.messages:raise HTTPException(status_code=422, detail="messages must contain at least one item")payload = body.model_dump()try:if body.stream:job = submit_gpu_job("/gpu_chat_stream", payload, request)def stream_job() -> Iterator[str]:try:for update in job:if isinstance(update, str):yield updateexcept Exception as exc:logger.exception("ZeroGPU streaming job failed")error = {"error": {"message": str(exc), "type": "server_error"}}yield "data: " + json.dumps(error, ensure_ascii=False) + "\n\n"yield "data: [DONE]\n\n"return StreamingResponse(stream_job(),media_type="text/event-stream",headers={"Cache-Control": "no-cache","Connection": "keep-alive","X-Accel-Buffering": "no",},)job = submit_gpu_job("/gpu_chat_completion", payload, request)return job.result()except HTTPException:raiseexcept Exception as exc:logger.exception("Chat completion failed")raise HTTPException(status_code=503, detail=f"Inference unavailable: {exc}") from exc@api.post("/v1/completions", dependencies=[Depends(require_api_key)])def completions(body: CompletionRequest, request: Request):if body.stream:raise HTTPException(status_code=400,detail="Streaming /v1/completions is not enabled; use /v1/chat/completions",)try:job = submit_gpu_job("/gpu_text_completion", body.model_dump(), request)return job.result()except Exception as exc:logger.exception("Text completion failed")raise HTTPException(status_code=503, detail=f"Inference unavailable: {exc}") from exc# Register each decorated GPU function as a Gradio event. The named Gradio API# is also protected by the same key inside the worker, so it cannot be used to# bypass authentication. FastAPI routes above proxy into this queue.with gr.Blocks(title="Qwen2.5 Coder API", analytics_enabled=False) as demo:gr.Markdown("""# ⚡ Qwen2.5-Coder-0.5B-Instruct REST API**Runtime:** llama.cpp · CUDA · Hugging Face ZeroGPU**Quantization:** Q4_K_M**REST base:** `/v1`All inference routes require the `LLAMA_API_KEY` Space Secret as aBearer token. Use `/docs` for the OpenAPI schema.""")with gr.Row(visible=False):chat_payload = gr.JSON(value={"messages": [{"role": "user", "content": "ping"}]})chat_key = gr.Textbox(value="", type="password")chat_result = gr.JSON()chat_trigger = gr.Button("Register chat worker")chat_trigger.click(fn=gpu_chat_completion,inputs=[chat_payload, chat_key],outputs=chat_result,api_name="gpu_chat_completion",)with gr.Row(visible=False):stream_payload = gr.JSON(value={"messages": [{"role": "user", "content": "ping"}]})stream_key = gr.Textbox(value="", type="password")stream_result = gr.Textbox()stream_trigger = gr.Button("Register streaming worker")stream_trigger.click(fn=gpu_chat_stream,inputs=[stream_payload, stream_key],outputs=stream_result,api_name="gpu_chat_stream",)with gr.Row(visible=False):completion_payload = gr.JSON(value={"prompt": "ping"})completion_key = gr.Textbox(value="", type="password")completion_result = gr.JSON()completion_trigger = gr.Button("Register completion worker")completion_trigger.click(fn=gpu_text_completion,inputs=[completion_payload, completion_key],outputs=completion_result,api_name="gpu_text_completion",)# Use the Gradio queue for serialized requests; the ZeroGPU scheduler allocates# a GPU for the decorated event callbacks.demo.queue(default_concurrency_limit=1, max_size=32)@api.get("/", include_in_schema=False)def root():return RedirectResponse(url="/console")app = gr.mount_gradio_app(api, demo, path="/console")if __name__ == "__main__":logger.info("llama-cpp-python version: %s", getattr(llama_cpp, "__version__", "unknown"))logger.info("CUDA initialization and model load are deferred to ZeroGPU workers.")uvicorn.run(app, host="0.0.0.0", port=PORT, log_level=os.getenv("LOG_LEVEL", "info").lower())
123--no-binary=llama-cpp-pythonllama-cpp-python[server]>=0.3.16,<0.4 --config-settings=cmake.args="-DGGML_NATIVE=ON;-DGGML_OPENMP=ON;-DGGML_BLAS=ON;-DGGML_BLAS_VENDOR=OpenBLAS"huggingface_hub>=0.27.012345# Install only the prebuilt CUDA wheel. If no compatible wheel is available,# pip must fail rather than spending Space build time compiling llama.cpp.--only-binary=llama-cpp-python--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu130llama-cpp-python==0.3.36
.env.example+9-8
.gitignore+1-1
README.md+120-98
app.py+416-75
requirements.txt+5-3