Spaces:
Running on Zero
Running on Zero
Bill the conditioner call to the requesting user's own ZeroGPU token, never an org token
Browse files182 unmodified lines183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213182 unmodified lines## Whose GPU quota paysTwo cards are booked per request: this Space's denoise loop and the conditioner's forward. ZeroGPU attributes abooking to the identity of the request that triggered it, so the conditioner call tries three in order:1. **the caller's own `X-IP-Token`**, forwarded off the `gr.Request` gradio injects (the UI path and the `/generate`API path alike). The request then bills as one request across both halves and costs this org nothing. Best effort:ZeroGPU answers `401` for a proxy token it will not honour — which is what a token minted for *this* Space lookslike arriving at another one — and `spaces` surfaces that as `Expired ZeroGPU proxy token`.2. **this Space's `HF_TOKEN`**, which charges the account that owns the Space and has a real quota. This is whatcarries the Space in practice.3. **no token**, an IP-based free quota shared by everything calling out of this Space's egress IP. A last resort.Any of ZeroGPU's "this identity cannot pay" answers — a refused proxy token, a duration past what the identity maybook, an exhausted quota — moves on to the next identity instead of failing the request, and the log line`conditioner call paid for by ...` records which one paid.The conditioner is sized so that even (3) is legal: an unattributed caller may book at most 120 credits at a time andan `xlarge` booking costs **twice** its seconds, so the conditioner books the encode (45 s) and a prompt upsample(60 s) as **two separate calls**, where one combined booking would be refused outright.## Secrets`HF_TOKEN` — used for exactly one thing: paying for the conditioner call when the caller's own ZeroGPU token cannot(see above). Everything this Space downloads is public: the [`MiniMaxAI/MiniMax-H3`](https://huggingface.co/MiniMaxAI/MiniMax-H3)checkpoint and the [`multimodalart/minimax-h3-aoti`](https://huggingface.co/multimodalart/minimax-h3-aoti) packages.Without it, a call the caller cannot pay for falls back to a shared IP quota worth a couple of requests a day.## Where diffusers comes from182 unmodified lines183184185186187188189190191192193194195196197198199200201202203204205206207208209210211182 unmodified lines## Whose GPU quota paysTwo cards are booked per request: this Space's denoise loop and the conditioner's forward, and **both are meant to bebilled to the requesting user**. ZeroGPU attributes a booking to the `X-IP-Token` of the request that triggered it —its `/schedule` hands that token to the Spaces API together with the duration and the calling pod's IP, and nothingelse, so there is no Space identity in the decision and a valid token minted anywhere is honoured. This Spacetherefore forwards the caller's header to the conditioner(`gradio_client.Client(..., headers={"X-IP-Token": ...})`, off the `gr.Request` gradio injects onthe UI path and the `/generate` API path alike) rather than spending a token of its own.A token ZeroGPU refuses — it answers `401`, which `spaces` surfaces as `Expired ZeroGPU proxy token` — falls back tocalling the conditioner with no token at all, billed to this Space's pod IP off a small shared quota. That is a safetynet rather than the intended path, and the log line `conditioner call paid for by ...` records which identity actuallypaid, next to a decoded dump of what the incoming token claimed.The conditioner is sized so that even the fallback is legal: an unattributed caller may book at most 120 credits at atime and an `xlarge` booking costs **twice** its seconds (`_gpu_size_units`), so the conditioner books the encode(45 s) and a prompt upsample (60 s) as **two separate calls**, where one combined booking would be refused outright.## SecretsNone are required. Everything this Space downloads is public — the[`MiniMaxAI/MiniMax-H3`](https://huggingface.co/MiniMaxAI/MiniMax-H3) checkpoint and the[`multimodalart/minimax-h3-aoti`](https://huggingface.co/multimodalart/minimax-h3-aoti) packages — and the conditioneris a public Space called on the requesting user's own ZeroGPU token, never on an org token.## Where diffusers comes from
318 unmodified lines3193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643 unmodified lines368369370371372373374375376377378379380381382383384385386387388389390318 unmodified lineskey = (ip_token, hf_token)if key in CLIENTS:return CLIENTS[key]client = Client(CONDITIONER_SPACE,token=hf_token,headers={"X-IP-Token": ip_token} if ip_token else None,)if len(CLIENTS) >= 32:CLIENTS.pop(next(iter(CLIENTS)))CLIENTS[key] = clientreturn client# What ZeroGPU says when an identity cannot pay for the booking, in any of its forms: a proxy token it will not# honour (`401`, surfaced as "Expired ZeroGPU proxy token"), a duration past what that identity may book, and an# exhausted quota. All three mean "try the next identity" rather than "fail the request"._UNPAYABLE = ("proxy token", "ZeroGPU quota", "larger than the maximum allowed", "GPU limit")def call_conditioner(ip_token, **arguments):"""One conditioner call, against the first ZeroGPU identity that can pay for it.In order of preference:1. **the caller's own forwarded `X-IP-Token`** — the request bills as one request across both halves and coststhis org nothing. Best effort: a proxy token minted for this Space is not necessarily honoured when itarrives at another one, and ZeroGPU answers `401` when it is not.2. **this Space's `HF_TOKEN`** — the booking is charged to the account that owns the Space, which has a realquota. This is what carries the Space in practice.3. **no token at all** — an IP-based free quota, shared by everything calling out of this Space's egress IP andworth a couple of requests a day. A last resort, not a design.The conditioner's own bookings are sized to fit even (3): it books an encode and a prompt upsample as two callsof 45 s and 60 s, because an unattributed caller may book at most 60 s of `xlarge` at a time."""api_name = arguments.pop("api_name")attempts = []if ip_token:attempts.append(("the caller's forwarded ZeroGPU token", {"ip_token": ip_token}))if HF_TOKEN:attempts.append(("this Space's HF_TOKEN", {"hf_token": HF_TOKEN}))attempts.append(("no token, on an IP quota", {}))for index, (label, identity) in enumerate(attempts):try:3 unmodified linesexcept Exception as error:if index == len(attempts) - 1 or not any(reason in str(error) for reason in _UNPAYABLE):raiseprint(f"[{LOG_TAG}] {label}: {error}; trying the next identity", flush=True)CLIENTS.pop((identity.get("ip_token"), identity.get("hf_token")), None)def ip_token_of(request) -> str | None:"""The caller's ZeroGPU identity, as the Spaces router put it on this request.Present on a browser request and on an API request the router could attribute; absent for a truly anonymouscaller, which then falls back to the conditioner's IP-based quota. Both the UI path and the `/generate` API pathreach this through the same `gr.Request` gradio injects for a parameter annotated with it."""headers = getattr(request, "headers", None)token = None if headers is None else headers.get("x-ip-token")print(f"[ref2va] conditioner call {'forwards the caller ZeroGPU token' if token else 'is anonymous (IP quota)'}", flush=True)return tokendef probe(path: str) -> tuple[float | None, float | None]:"""`(video seconds, audio seconds)` of a media file, either being `None` when the stream is absent."""import av318 unmodified lines3193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553 unmodified lines359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397318 unmodified lineskey = (ip_token, hf_token)if key in CLIENTS:return CLIENTS[key]# No token of this Space's own: the booking is meant to be the caller's, and an unattributed call is the# fallback rather than a second identity to spend.client = Client(CONDITIONER_SPACE, headers={"X-IP-Token": ip_token} if ip_token else None)if len(CLIENTS) >= 32:CLIENTS.pop(next(iter(CLIENTS)))CLIENTS[key] = clientreturn client# What ZeroGPU says when an identity cannot pay for a booking: a proxy token its `/usage-approval` refused (`401`,# surfaced as "Expired ZeroGPU proxy token"), a duration past what that identity may book, and an exhausted quota._UNPAYABLE = ("proxy token", "ZeroGPU quota", "larger than the maximum allowed", "GPU limit")def call_conditioner(ip_token, **arguments):"""One conditioner call, billed to **the requesting user**.ZeroGPU attributes a booking to the `X-IP-Token` of the request that triggered it: `/schedule` hands that token tothe Spaces API's `/usage-approval` together with the duration and the calling pod's IP, and nothing else — there isno Space identity in that call, so a *valid* token minted anywhere is honoured and the user's own quota pays forboth halves of their request. That is the whole reason this Space forwards the header instead of spending a tokenof its own.A token the Spaces API refuses (`401`) falls back to calling the conditioner with no token, which is billed to thisSpace's pod IP off a small shared quota. That is a safety net, not the intended path: the log line`conditioner call paid for by ...` records which one actually paid, so a Space that keeps falling back is visible."""api_name = arguments.pop("api_name")attempts = [("no token, on this Space's shared IP quota", {})]if ip_token:attempts.insert(0, ("the requesting user's own ZeroGPU token", {"ip_token": ip_token}))for index, (label, identity) in enumerate(attempts):try:3 unmodified linesexcept Exception as error:if index == len(attempts) - 1 or not any(reason in str(error) for reason in _UNPAYABLE):raiseprint(f"[{LOG_TAG}] {label} was refused: {error}; falling back", flush=True)CLIENTS.pop((identity.get("ip_token"), identity.get("hf_token")), None)def ip_token_of(request) -> str | None:"""The requesting user's ZeroGPU identity, as the Spaces router put it on this request.Logged, decoded, on every request — never the token itself, only what it claims. ZeroGPU refuses a token its`/usage-approval` considers expired, and that refusal is indistinguishable from a missing one in the outcome, sothe claims are what tell the two apart when a request ends up on the fallback quota. Both the UI path and the`/generate` API path reach this through the same `gr.Request` gradio injects for a parameter annotated with it."""headers = getattr(request, "headers", None)token = None if headers is None else headers.get("x-ip-token")if token is None:print(f"[{LOG_TAG}] no X-IP-Token on this request; the conditioner call cannot be billed to the caller", flush=True)return Nonetry:import base64import jsonimport timepayload = json.loads(base64.urlsafe_b64decode(f"{token.split('.')[1]}=="))left = payload.get("exp", 0) - time.time()print(f"[{LOG_TAG}] X-IP-Token present: {left:.0f}s to expiry, claims "f"{ {k: v for k, v in payload.items() if k in ('exp', 'iat', 'sub', 'aud', 'error', 'user')} }",flush=True,)except Exception as error: # a token that cannot be read is still worth forwarding; ZeroGPU is the judgeprint(f"[{LOG_TAG}] X-IP-Token present but unreadable ({type(error).__name__}: {error})", flush=True)return tokendef probe(path: str) -> tuple[float | None, float | None]:"""`(video seconds, audio seconds)` of a media file, either being `None` when the stream is absent."""import av
README.md+20-22
app.py+39-32