mhd-radin commited on
Commit
856bb3a
·
verified ·
1 Parent(s): 31f00bc

Upload 5 files

Browse files
Files changed (2) hide show
  1. README.md +2 -3
  2. app.py +38 -28
README.md CHANGED
@@ -17,8 +17,7 @@ An OpenAI-compatible REST API for the official Qwen2.5-Coder-0.5B-Instruct **Q4_
17
 
18
  - Uses `@spaces.GPU` to request ZeroGPU for inference calls.
19
  - FastAPI routes submit inference jobs through the internal Gradio queue; this is important because ZeroGPU schedules registered Gradio GPU callbacks.
20
- - Forwards Hugging Face's incoming `X-IP-Token` to the internal queue when present.
21
- - Requires the Space owner's `HF_TOKEN` and passes it to `gradio_client.Client(..., token=HF_TOKEN)`. The Gradio client then attaches Hugging Face authentication consistently to its internal queue handshake; this makes API calls use the owner's authenticated ZeroGPU quota instead of silently falling back to the anonymous pool. The token stays in Space Secrets and is never returned to API callers.
22
  - Uses smaller dynamic GPU duration reservations: 256 output tokens -> 15s, 512 -> 20s, 1024 -> 30s, 2048 -> 50s. Actual output length does not determine the reservation; the requested `max_tokens` does.
23
  - Uses `n_gpu_layers=-1` to offload all model layers to the GPU.
24
  - Uses CUDA 13.0 prebuilt `llama-cpp-python` wheels (`0.3.36`) instead of building llama.cpp from source during Space startup.
@@ -179,7 +178,7 @@ Don't set `n_gpu_layers` to zero. This build is intended to use the GPU only.
179
 
180
  ### `You have exceeded your ZeroGPU runs limit` / `Authenticate with a Hugging Face token for more quota`
181
 
182
- This indicates the internal Gradio queue call was not authenticated as a Hugging Face account. This release fixes the client construction by passing `token=HF_TOKEN` directly to `gradio_client.Client`; it does not merely attach `x-hf-authorization` to one submission. Add a valid Hugging Face **read** token as the Space Secret `HF_TOKEN`, then commit/restart the Space. Check `/health` for `"hf_token_configured": true` and `"quota_authentication": "Space owner HF_TOKEN via gradio_client.Client(token=...)"`.
183
 
184
  Authentication does not create unlimited free GPU usage or reset an already-exhausted quota. Free-account daily quota still applies; the authenticated requests consume the Space owner's account quota. Check the remaining balance with `hf spaces zero-gpu quota` while logged in as the token owner.
185
 
 
17
 
18
  - Uses `@spaces.GPU` to request ZeroGPU for inference calls.
19
  - FastAPI routes submit inference jobs through the internal Gradio queue; this is important because ZeroGPU schedules registered Gradio GPU callbacks.
20
+ - Requires the Space owner's `HF_TOKEN` and passes it to `gradio_client.Client(..., token=HF_TOKEN)`. Crucially, the internal client connects to `https://$SPACE_HOST/console` through Hugging Face's public Space gateway, not `127.0.0.1`; the gateway can then authenticate the request for ZeroGPU scheduling. The token stays in Space Secrets and is never returned to API callers.
 
21
  - Uses smaller dynamic GPU duration reservations: 256 output tokens -> 15s, 512 -> 20s, 1024 -> 30s, 2048 -> 50s. Actual output length does not determine the reservation; the requested `max_tokens` does.
22
  - Uses `n_gpu_layers=-1` to offload all model layers to the GPU.
23
  - Uses CUDA 13.0 prebuilt `llama-cpp-python` wheels (`0.3.36`) instead of building llama.cpp from source during Space startup.
 
178
 
179
  ### `You have exceeded your ZeroGPU runs limit` / `Authenticate with a Hugging Face token for more quota`
180
 
181
+ This indicates the ZeroGPU scheduler did not receive a valid authenticated identity. This release fixes the routing detail: the internal `gradio_client.Client` connects to `https://$SPACE_HOST/console` with `token=HF_TOKEN`, passing through Hugging Face's public Space gateway. The previous version used `http://127.0.0.1:7860/console`, which bypassed the gateway and can produce `user:null`, `uuid:null`, and `InvalidAccessToken` at `device-api.zero`. The app now validates `HF_TOKEN` with `HfApi.whoami()` during startup. Check `/health` for `"hf_token_valid": true` and `"quota_authentication": "HF_TOKEN via public SPACE_HOST gateway"`.
182
 
183
  Authentication does not create unlimited free GPU usage or reset an already-exhausted quota. Free-account daily quota still applies; the authenticated requests consume the Space owner's account quota. Check the remaining balance with `hf spaces zero-gpu quota` while logged in as the token owner.
184
 
app.py CHANGED
@@ -27,7 +27,7 @@ from fastapi import Depends, FastAPI, Header, HTTPException, Request
27
  from fastapi.middleware.cors import CORSMiddleware
28
  from fastapi.responses import RedirectResponse, StreamingResponse
29
  from gradio_client import Client
30
- from huggingface_hub import hf_hub_download
31
  from pydantic import BaseModel, ConfigDict, Field
32
 
33
  # Import llama.cpp after the ZeroGPU bootstrap and the platform CUDA runtime.
@@ -51,6 +51,7 @@ MODEL_FILENAME = os.getenv(
51
  MODEL_ALIAS = os.getenv("MODEL_ALIAS", "qwen2.5-coder-0.5b-instruct")
52
  API_KEY = os.getenv("LLAMA_API_KEY", "").strip()
53
  HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
 
54
 
55
 
56
  def positive_int(name: str, default: int, maximum: Optional[int] = None) -> int:
@@ -281,12 +282,27 @@ if not API_KEY:
281
 
282
  if not HF_TOKEN:
283
  raise RuntimeError(
284
- "Missing required Space Secret HF_TOKEN. Create a Hugging Face access token "
285
- "with read access and add it under Settings → Variables and secrets → Secrets. "
286
- "Without it, internal ZeroGPU queue calls are unauthenticated and may hit "
287
- "the anonymous run limit."
288
  )
289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  api = FastAPI(
291
  title="Qwen2.5 Coder ZeroGPU API",
292
  version="2.2.0",
@@ -314,9 +330,15 @@ def require_api_key(authorization: Optional[str] = Header(default=None)) -> None
314
 
315
  @lru_cache(maxsize=1)
316
  def get_internal_gradio_client() -> Client:
317
- """Connect to this Space's Gradio queue so ZeroGPU schedules the callback."""
318
- url = f"http://127.0.0.1:{PORT}/console"
319
- logger.info("Connecting internal Gradio client to %s", url)
 
 
 
 
 
 
320
  return Client(
321
  url,
322
  token=HF_TOKEN,
@@ -331,26 +353,12 @@ def submit_gpu_job(
331
  payload: dict[str, Any],
332
  request: Request,
333
  ):
334
- # HF_TOKEN is configured on the Gradio Client itself (Client(...,
335
- # token=HF_TOKEN)). Gradio Client converts it to the x-hf-authorization
336
- # header and uses it consistently for its queue handshake. Passing that
337
- # header only to submit() is insufficient because it does not configure
338
- # the client's authentication context for every internal request.
339
- #
340
- # Preserve the ingress X-IP-Token when present, but the authenticated Space
341
- # owner token is the identity used for ZeroGPU quota accounting here.
342
- incoming_token = request.headers.get("x-ip-token")
343
- headers: dict[str, str] = {}
344
- if incoming_token:
345
- headers["X-IP-Token"] = incoming_token
346
-
347
  client = get_internal_gradio_client()
348
- return client.submit(
349
- payload,
350
- API_KEY,
351
- api_name=api_name,
352
- headers=headers or None,
353
- )
354
 
355
 
356
  @api.get("/health")
@@ -362,8 +370,10 @@ def health() -> dict[str, Any]:
362
  "runtime": "llama.cpp",
363
  "gpu": "ZeroGPU on-demand CUDA",
364
  "cuda_backend_probe": "deferred until a GPU worker is allocated",
365
- "quota_authentication": "Space owner HF_TOKEN via gradio_client.Client(token=...)",
366
  "hf_token_configured": bool(HF_TOKEN),
 
 
367
  "model_downloaded": Path(MODEL_PATH).is_file(),
368
  "model_loaded": "inside a ZeroGPU worker on first inference",
369
  "gpu_offload_required": True,
 
27
  from fastapi.middleware.cors import CORSMiddleware
28
  from fastapi.responses import RedirectResponse, StreamingResponse
29
  from gradio_client import Client
30
+ from huggingface_hub import HfApi, hf_hub_download
31
  from pydantic import BaseModel, ConfigDict, Field
32
 
33
  # Import llama.cpp after the ZeroGPU bootstrap and the platform CUDA runtime.
 
51
  MODEL_ALIAS = os.getenv("MODEL_ALIAS", "qwen2.5-coder-0.5b-instruct")
52
  API_KEY = os.getenv("LLAMA_API_KEY", "").strip()
53
  HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
54
+ SPACE_HOST = os.getenv("SPACE_HOST", "").strip()
55
 
56
 
57
  def positive_int(name: str, default: int, maximum: Optional[int] = None) -> int:
 
282
 
283
  if not HF_TOKEN:
284
  raise RuntimeError(
285
+ "Missing required Space Secret HF_TOKEN. Create a Hugging Face user access "
286
+ "token with read access and add it under Settings → Variables and secrets → Secrets."
 
 
287
  )
288
 
289
+ if not SPACE_HOST:
290
+ raise RuntimeError(
291
+ "Missing Hugging Face SPACE_HOST environment variable. This app must run "
292
+ "inside a Hugging Face Space so its authenticated public gateway can be used."
293
+ )
294
+
295
+ # Validate the configured user token before accepting API traffic. Never log the token.
296
+ try:
297
+ HfApi(token=HF_TOKEN).whoami()
298
+ HF_TOKEN_VALID = True
299
+ except Exception as exc:
300
+ raise RuntimeError(
301
+ "HF_TOKEN is not a valid Hugging Face user access token. Create a token "
302
+ "with read access at https://huggingface.co/settings/tokens and replace "
303
+ "the Space Secret."
304
+ ) from exc
305
+
306
  api = FastAPI(
307
  title="Qwen2.5 Coder ZeroGPU API",
308
  version="2.2.0",
 
330
 
331
  @lru_cache(maxsize=1)
332
  def get_internal_gradio_client() -> Client:
333
+ """Connect through the public HF Space gateway, not the loopback socket.
334
+
335
+ Client(token=...) authenticates the request with x-hf-authorization. The
336
+ public HF gateway must see that request so it can establish the ZeroGPU
337
+ scheduling identity. Calling http://127.0.0.1 bypasses the gateway and can
338
+ produce an anonymous/InvalidAccessToken identity at device-api.zero.
339
+ """
340
+ url = f"https://{SPACE_HOST}/console"
341
+ logger.info("Connecting internal Gradio client through HF gateway: %s", url)
342
  return Client(
343
  url,
344
  token=HF_TOKEN,
 
353
  payload: dict[str, Any],
354
  request: Request,
355
  ):
356
+ # All REST callers authenticate using LLAMA_API_KEY. The Space owner's
357
+ # HF_TOKEN authenticates the internal Gradio client. Do not forward an
358
+ # arbitrary X-IP-Token supplied to this API: the public HF gateway should
359
+ # establish identity from the configured HF_TOKEN instead.
 
 
 
 
 
 
 
 
 
360
  client = get_internal_gradio_client()
361
+ return client.submit(payload, API_KEY, api_name=api_name)
 
 
 
 
 
362
 
363
 
364
  @api.get("/health")
 
370
  "runtime": "llama.cpp",
371
  "gpu": "ZeroGPU on-demand CUDA",
372
  "cuda_backend_probe": "deferred until a GPU worker is allocated",
373
+ "quota_authentication": "HF_TOKEN via public SPACE_HOST gateway",
374
  "hf_token_configured": bool(HF_TOKEN),
375
+ "hf_token_valid": HF_TOKEN_VALID,
376
+ "internal_gradio_target": f"https://{SPACE_HOST}/console",
377
  "model_downloaded": Path(MODEL_PATH).is_file(),
378
  "model_loaded": "inside a ZeroGPU worker on first inference",
379
  "gpu_offload_required": True,