"""Shared full-precision ZeroGPU demo for the four BYOD models.""" from __future__ import annotations import json import os import secrets import sys import time from pathlib import Path import gradio as gr import spaces sys.path.insert(0, str(Path(__file__).parent / "src")) from diffusion_lm.inference import denoise_stream, load_hub_adapter_session SPACE = json.loads((Path(__file__).parent / "space_model.json").read_text()) MODEL_REPO_ID = os.getenv("MODEL_REPO_ID", SPACE["model_repo_id"]) DISPLAY_NAME = SPACE["display_name"] # ZeroGPU recommends constructing and placing the root module on CUDA at module # scope. No quantization is used: all four demos run with the saved BF16 setup. print(f"Loading {MODEL_REPO_ID} in full precision...") SESSION = load_hub_adapter_session( MODEL_REPO_ID, device_name="cuda", quantization="none", # A forward pass is only valid after @spaces.GPU has allocated hardware. preflight=False, ) print(f"Loaded {DISPLAY_NAME} ({SESSION.compute_dtype}, unquantized).") def _duration(*args) -> int: """Reserve enough GPU time for the requested number of denoising steps.""" try: steps = int(args[3]) pause_per_step = float(args[7]) except (IndexError, TypeError, ValueError): steps = 64 pause_per_step = 0.0 return min(300, max(30, round(steps * (2.0 + pause_per_step)))) @spaces.GPU(size="large", duration=_duration) def generate( question: str, system_prompt: str, max_new_tokens: int, num_steps: int, block_length: int, temperature: float, top_k: int, pause_per_step: float, trajectory_color_mode: str, remasking_strategy: str, delay_eos_eot: bool, early_stopping: bool, ): """Stream iterative masked-diffusion generation from the fixed model.""" question = question.strip() or "What do you know about Amsterdam?" block_length = min(int(block_length), int(max_new_tokens)) seed = secrets.randbelow(2**63 - 1) first_step = True for text, status, trajectory_html in denoise_stream( SESSION, question=question, system_prompt=system_prompt, max_new_tokens=int(max_new_tokens), num_steps=int(num_steps), noise_level=1.0, temperature=float(temperature), top_k=int(top_k), seed=int(seed), permanent_unmask=True, confidence_guided=remasking_strategy == "Confidence-guided", proportional_unmask=False, early_stopping=bool(early_stopping), # This delays retention of predicted endings; it does not alter their # sampling probability. Keep it optional so answers can end naturally. confidence_eos_eot_inf=bool(delay_eos_eot), freeze_retained_tokens=True, repetition_penalty=1.0, eos_eot_prediction_penalty=1.0, include_pre_remask_prediction=False, block_length=block_length, trajectory_color_mode=trajectory_color_mode, ): if not first_step and float(pause_per_step) > 0: # The sleep occurs inside this one decorated generator invocation, # so ZeroGPU remains allocated for the entire denoising run. time.sleep(float(pause_per_step)) first_step = False yield status, trajectory_html def show_loading(): """Immediately acknowledge a request while ZeroGPU prepares generation.""" return ( "⏳ Requesting a GPU and loading the model…", "