Spaces:
Running on Zero
Running on Zero
Forward the caller's ZeroGPU token to the conditioner so one request bills as one request
Browse files180 unmodified lines181182183184185186180 unmodified lines| `H3_PLACEMENT_ALLOWANCE` | `90` | Seconds of the reservation set aside for a cold worker's placement. || `H3_GPU_SIZE` | `xlarge` | ZeroGPU allocation size. `large` does not fit. |## SecretsNothing this Space loads is private any more: the weights are the public180 unmodified lines181182183184185186187188189190191192193194195196197198199180 unmodified lines| `H3_PLACEMENT_ALLOWANCE` | `90` | Seconds of the reservation set aside for a cold worker's placement. || `H3_GPU_SIZE` | `xlarge` | ZeroGPU allocation size. `large` does not fit. |## Whose GPU quota paysTwo cards are booked per request: this Space's denoise loop and the conditioner's forward. ZeroGPU attributes abooking to the `X-IP-Token` header of the request that triggered it, so this Space forwards the caller's token to theconditioner (`gradio_client.Client(..., headers={"X-IP-Token": ...})`, from the `gr.Request` gradio injects — the UIpath and the `/generate` API path alike). One user's request then bills as one request across both halves, the way itwould if this were a single Space, and no org token is ever spent on it.A caller the router cannot attribute — an unauthenticated API call — falls back to the conditioner's IP-based quota,whose ceiling is 120 credits. An `xlarge` booking costs **twice** its seconds there, so the conditioner keeps itsreservation at 60 s (120 credits) for an encode; asking it to upsample a prompt books 120 s (240 credits) and needs aforwarded token.## SecretsNothing this Space loads is private any more: the weights are the public
199 unmodified lines20020120220320420520699 unmodified lines30630730830931031131231331431531631731831992 unmodified lines4124134144154164174188 unmodified lines42742842943043143243360 unmodified lines49449549649749849916 unmodified lines516517518519520521522199 unmodified linesPIPE = NoneMANAGER = NoneLOAD_ERROR: str | None = NoneCLIENT = Nonedef load_models() -> str | None:99 unmodified linessetattr(module, method, armed)def conditioner():"""The other half, over the gradio API. Cached — building a `Client` costs a round trip to the Space config."""global CLIENTif CLIENT is None:from gradio_client import ClientCLIENT = Client(CONDITIONER_SPACE) # public Space, no org token: the request runs on the caller side quotareturn CLIENTdef probe(path: str) -> tuple[float | None, float | None]:92 unmodified lines)def encode_remote(prompt, references, canvas, num_frames, rewrite_prompt=False):"""Ask the conditioner Space for `prompt_embeds` + `text_token_tags`. Off this Space's GPU time entirely.The references go over with the request: `ref2va`'s presentation puts a vision block in front of the prompt for8 unmodified linesfrom gradio_client import handle_filefrom safetensors import safe_openpath, plan = conditioner().predict(prompt=prompt,media=[handle_file(path) for _, path in references],kinds=",".join(kind for kind, _ in references),60 unmodified linesseed=42,upsample=False,progress=gr.Progress(track_tqdm=True),):"""One request. `upsample` is appended last and defaults off, so an existing API client is untouched by it."""if LOAD_ERROR:16 unmodified linesconditioned = time.time()try:prompt_embeds, text_token_tags, metadata, plan = encode_remote(prompt, references, canvas, requested, rewrite_prompt=upsample)except gr.Error:raise199 unmodified lines20020120220320420520699 unmodified lines30630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834992 unmodified lines4424434444454464474488 unmodified lines45745845946046146246360 unmodified lines52452552652752852953016 unmodified lines547548549550551552553199 unmodified linesPIPE = NoneMANAGER = NoneLOAD_ERROR: str | None = NoneCLIENTS: dict[str | None, object] = {}def load_models() -> str | None:99 unmodified linessetattr(module, method, armed)def conditioner(ip_token: str | None = None):"""The other half, over the gradio API — booked against *the caller's* ZeroGPU quota, not this org's.ZeroGPU attributes a booking to the `X-IP-Token` header of the request that triggered it(`spaces/zero/client.py`), which the Spaces router puts on every browser request. That header is what pays forthis Space's own `@spaces.GPU` call, and forwarding it to the conditioner makes the same identity pay for theconditioner's — the two halves of one user's request then bill as one request, the way they would if this were asingle Space.Without it the conditioner falls back to an IP-based quota, whose ceiling is low enough that an `xlarge` bookingis refused outright ("The requested GPU duration (Ns) is larger than the maximum allowed"), so a call that doesnot forward a token only works because the conditioner keeps its own reservation small.Cached per token: building a `Client` costs a round trip to the Space config, and a token is per user session."""from gradio_client import Clientif ip_token in CLIENTS:return CLIENTS[ip_token]# No org token: the request runs on the caller side quota, which is the point of forwarding theirs.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[ip_token] = clientreturn clientdef 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]:92 unmodified lines)def encode_remote(prompt, references, canvas, num_frames, rewrite_prompt=False, ip_token=None):"""Ask the conditioner Space for `prompt_embeds` + `text_token_tags`. Off this Space's GPU time entirely.The references go over with the request: `ref2va`'s presentation puts a vision block in front of the prompt for8 unmodified linesfrom gradio_client import handle_filefrom safetensors import safe_openpath, plan = conditioner(ip_token).predict(prompt=prompt,media=[handle_file(path) for _, path in references],kinds=",".join(kind for kind, _ in references),60 unmodified linesseed=42,upsample=False,progress=gr.Progress(track_tqdm=True),request: gr.Request | None = None,):"""One request. `upsample` is appended last and defaults off, so an existing API client is untouched by it."""if LOAD_ERROR:16 unmodified linesconditioned = time.time()try:prompt_embeds, text_token_tags, metadata, plan = encode_remote(prompt, references, canvas, requested, rewrite_prompt=upsample, ip_token=ip_token_of(request))except gr.Error:raise
README.md+13
app.py+42-11