""" Utilities for integrating Hugging Face Spaces ZeroGPU without breaking local or non-ZeroGPU environments. """ import contextlib import inspect import re import threading from collections.abc import Callable from functools import wraps from typing import TypeVar T = TypeVar("T", bound=Callable) # Default values in case the spaces package is unavailable (e.g., local runs). ZERO_GPU_AVAILABLE = False class QuotaExhaustedError(Exception): """Raised when ZeroGPU quota is exhausted. Caller should retry with device='CPU'.""" def __init__(self, message, reset_time=None, detail=None): super().__init__(message) self.reset_time = reset_time #: ZeroGPU's own text, which carries the arithmetic its plain-text #: fallback drops ("s requested vs. s left"). Log-only — never #: shown to a caller, who gets the wording in ``message``. self.detail = detail class GpuBypassError(Exception): """The GPU cannot take this run, so the caller runs it on the CPU instead. ``notice`` is the sentence a person is shown; the exception text is log-only. """ def __init__(self, message, *, notice): super().__init__(message) self.notice = notice LONG_AUDIO_NOTICE = "This recording is longer than the GPU accepts, so it ran on the CPU instead." GPU_FAILED_NOTICE = "The GPU could not run this request, so it ran on the CPU instead." class GpuQueueTimeoutError(Exception): """ZeroGPU could not grant a Space concurrency slot within its 60s limit.""" class GpuTokenExpiredError(Exception): """The caller's ZeroGPU proxy token (taken when the request started) expired before this lease — a long request outlived it. Caller retries without it (:func:`without_caller_token`), then on the CPU.""" @contextlib.contextmanager def without_caller_token(): """Leases scheduled inside take ZeroGPU's IP-based quota (the Space's shared pool): ``spaces`` reads the caller's X-IP-Token from Gradio's request contextvar.""" from gradio.context import LocalContext reset = LocalContext.request.set(None) try: yield finally: LocalContext.request.reset(reset) # Per-thread (per-request) GPU state so concurrent requests don't interfere _request_state = threading.local() # --------------------------------------------------------------------------- # Shared RLock for model device transitions AND inference, held for the # ENTIRE GPU lease (inference + cleanup) to prevent concurrent threads from # moving models mid-inference. # --------------------------------------------------------------------------- model_device_lock = threading.RLock() # --------------------------------------------------------------------------- # CPU subprocess concurrency gate — limits how many local subprocesses may be # running at once. Lazily initialized from config when first used to avoid # importing config at module load. # --------------------------------------------------------------------------- _subprocess_semaphore = None _subprocess_semaphore_lock = threading.Lock() def _get_subprocess_semaphore(): global _subprocess_semaphore if _subprocess_semaphore is None: with _subprocess_semaphore_lock: if _subprocess_semaphore is None: from config import CPU_SUBPROCESS_CONCURRENCY from .cpu_sem import CountedBoundedSemaphore _subprocess_semaphore = CountedBoundedSemaphore( max(1, CPU_SUBPROCESS_CONCURRENCY) ) return _subprocess_semaphore # --------------------------------------------------------------------------- # GPU lease tracking — lets code know if ANY thread currently holds a lease. # --------------------------------------------------------------------------- _lease_lock = threading.Lock() _active_gpu_leases = 0 _models_stale = False # Set True at lease end; drained at next lease start try: import spaces # type: ignore gpu_decorator = spaces.GPU # pragma: no cover ZERO_GPU_AVAILABLE = True except Exception: def gpu_decorator(*decorator_args, **decorator_kwargs): """ No-op replacement for spaces.GPU so code can run without the package or outside of a ZeroGPU Space. """ def wrapper(func: T) -> T: return func # Support both bare @gpu_decorator and @gpu_decorator(...) if decorator_args and callable(decorator_args[0]) and not decorator_kwargs: return decorator_args[0] return wrapper # ========================================================================= # GPU lease tracking # ========================================================================= def _enter_gpu_lease(): """Mark that a GPU lease is now active in this process.""" global _active_gpu_leases with _lease_lock: _active_gpu_leases += 1 def _exit_gpu_lease(): """Mark that a GPU lease has ended in this process.""" global _active_gpu_leases with _lease_lock: _active_gpu_leases = max(0, _active_gpu_leases - 1) # ========================================================================= # Per-thread state helpers # ========================================================================= def is_quota_exhausted() -> bool: """Check if GPU quota has been exhausted for this request's thread.""" return getattr(_request_state, 'gpu_quota_exhausted', False) def is_user_forced_cpu() -> bool: """Check if the user manually selected CPU mode for this request.""" return getattr(_request_state, 'user_forced_cpu', False) def get_quota_reset_time() -> str | None: """Return the quota reset time string (e.g. '13:53:59'), or None.""" return getattr(_request_state, 'quota_reset_time', None) def reset_quota_flag(): """Reset the quota exhausted flag for this request's thread.""" _request_state.gpu_quota_exhausted = False _request_state.quota_reset_time = None _request_state.user_forced_cpu = False def force_cpu_mode(): """Force GPU-decorated functions to skip GPU and run on CPU for this request. Only sets the per-thread flag — does NOT move models. Moving models requires CUDA access (to copy from GPU to CPU) which is not safe outside a GPU lease and would poison the process. """ _request_state.user_forced_cpu = True @contextlib.contextmanager def cpu_mode(): """``force_cpu_mode`` for the calls inside the block, then this thread's own choice again.""" previous = is_user_forced_cpu() _request_state.user_forced_cpu = True try: yield finally: _request_state.user_forced_cpu = previous # ========================================================================= # Model cleanup helpers # ========================================================================= def _cleanup_after_gpu(): """Cleanup that runs at the END of a GPU lease. Does NOT perform any CUDA operations (no model.to("cpu"), no torch.cuda.empty_cache()). Instead, sets a stale flag so the NEXT GPU lease drains old models safely inside a fresh lease context. Why: model.to("cpu") at the lease boundary is a CUDA op that can fail if the SDK is revoking the GPU, poisoning torch's CUDA runtime state. """ global _models_stale with _lease_lock: _models_stale = True # Callables that drop model caches (e.g. the SDK runtimes' invalidate()). # Registered at pipeline import; run inside the next lease by _drain_stale_models. _stale_invalidators: list = [] def register_stale_invalidator(fn) -> None: """Register a zero-arg callable that drops a model cache at lease start.""" _stale_invalidators.append(fn) def _drain_stale_models(): """Invalidate stale model caches from a previous GPU lease. Must be called INSIDE a GPU lease (after _enter_gpu_lease()) where CUDA is safe. Runs every registered invalidator so cached models get reloaded fresh on the correct device. gc.collect() triggers CUDA tensor destructors safely inside the lease. """ global _models_stale with _lease_lock: if not _models_stale: return _models_stale = False for fn in list(_stale_invalidators): with contextlib.suppress(Exception): fn() import gc gc.collect() # CUDA tensor destructors run safely inside lease # ========================================================================= # GPU decorator with fallback # ========================================================================= #: First item a lease generator yields so the caller can strip the internal #: transport marker before relaying progress. _ENTERED = "_lease_entered" def _strip_entry_marker(stream): """Yield *stream* without its internal lease-entry marker.""" for kind, value in stream: # Compared by value: the marker is pickled on the way out of the # worker, so the caller never sees the same string object. if kind == _ENTERED: continue yield (kind, value) def _ensure_pool(): """Start the persistent CPU worker pool if a request beat the bootstrap.""" from .cpu_worker_pool import is_started, start_pool if not is_started(): # Lazy start fallback — slow first request. from config import CPU_POOL_PRELOAD_LARGE, CPU_SUBPROCESS_CONCURRENCY start_pool(CPU_SUBPROCESS_CONCURRENCY, preload_large=CPU_POOL_PRELOAD_LARGE) def _pool_dispatch(func, args, kwargs): """Run *func* on the in-Space persistent CPU worker pool.""" from .cpu_worker_pool import run_on_persistent_worker sem = _get_subprocess_semaphore() sem.acquire_with_stats() try: _ensure_pool() return run_on_persistent_worker(func, args, kwargs) finally: sem.release_with_stats() def _pool_stream(func, args, kwargs): """Stream generator *func* off the pool, holding the slot for the whole run. A generator rather than a collected list, so a stage the worker reports reaches the caller while the work is still going — which is the only reason the transport streams at all. The slot is released when this generator is exhausted or closed. """ from .cpu_worker_pool import run_generator_on_persistent_worker sem = _get_subprocess_semaphore() sem.acquire_with_stats() try: _ensure_pool() yield from run_generator_on_persistent_worker(func, args, kwargs) finally: sem.release_with_stats() def _reraise_gpu_error(e): """Translate a raw ZeroGPU failure into the app's error vocabulary. Always raises. Call it from inside an ``except`` block. """ global _models_stale err_str = str(e) err_lower = err_str.lower() err_title = getattr(e, "title", "") # Quota exhaustion -> CPU fallback (per-user, not process issue) is_quota_error = err_title == "ZeroGPU quota exceeded" if not is_quota_error: is_quota_error = 'quota' in err_lower and ('exceeded' in err_lower or 'exhausted' in err_lower) if is_quota_error: # spaces.zero wraps the quota message in an HTMLString: str(e) # returns the plain-text fallback (daily-quota prompt, no timer), # but the underlying .message holds the HTML that INCLUDES # "Try again in {timedelta}". Regex against the raw message. # "0:00:00" means daily cap (no short-term rate limit) - UI # layer translates that to a "resets at midnight UTC" hint. haystack = getattr(e, "message", None) or err_str # timedelta.__str__ produces "H:MM:SS" or "D day(s), H:MM:SS". match = re.search( r'Try again in ((?:\d+\s*days?,\s*)?\d+:\d{2}:\d{2})', haystack, ) reset_time = match.group(1) if match else None raise QuotaExhaustedError(str(e), reset_time=reset_time, detail=haystack) from e if "expired zerogpu proxy token" in err_lower: raise GpuTokenExpiredError(err_str) from e is_queue_timeout = ( err_title == "ZeroGPU queue timeout" or "no gpu was available after 60s" in err_lower ) if is_queue_timeout: raise GpuQueueTimeoutError(str(e)) from e # The scheduler failing or the task being aborted says nothing about the request # itself, so the caller reruns it on the CPU. if "/schedule error: 5" in err_lower or "gpu task aborted" in err_lower: raise GpuBypassError(err_str, notice=GPU_FAILED_NOTICE) from e # Timeout -> propagate to caller is_timeout = ( 'timeout' in err_lower or 'duration' in err_lower or 'time limit' in err_lower ) if is_timeout: raise # Worker/runtime init errors - propagate immediately. is_worker_error = ( err_title == "ZeroGPU worker error" or "no cuda gpus are available" in err_lower ) if is_worker_error: raise # CUDA runtime errors (non-timeout, non-quota): mark stale and propagate. is_cuda_runtime_error = ( "cuda" in err_lower or "cudnn" in err_lower or "nvidia" in err_lower or err_title == "CUDA error" ) if is_cuda_runtime_error: with _lease_lock: _models_stale = True raise # Unknown non-timeout errors should propagate so genuine bugs # are not silently hidden behind CPU fallback. raise def gpu_with_fallback(duration=60): """ Decorator that wraps a GPU function with quota error detection. If ZeroGPU quota is exceeded, raises QuotaExhaustedError so the caller (UI handler or API endpoint) can retry the entire pipeline with device='CPU'. This avoids running any torch code after a failed GPU lease, which would poison CUDA state for the process. The model_device_lock is held for the ENTIRE GPU lease (inference + cleanup) to prevent concurrent threads from moving models mid-inference. Error handling strategy: - Quota exhaustion → raise QuotaExhaustedError (caller retries with CPU) - Expired proxy token → raise GpuTokenExpiredError (caller retries with CPU) - Scheduler 5xx or aborted task → raise GpuBypassError (caller retries with CPU) - Timeout → propagate to caller - ZeroGPU worker/CUDA errors → propagate immediately - Unknown non-timeout errors → propagate (avoid hiding real bugs) Generator functions keep their streaming behaviour on every device: ZeroGPU streams yields back out of the lease worker and the CPU pool streams them out of the worker process, so a stage marker yielded from inside a lease reaches the caller while the lease is still running. Usage: @gpu_with_fallback(duration=60) def my_gpu_func(data): ensure_models_on_gpu() # Moves to CUDA # ... inference using model's current device ... """ def decorator(func: T) -> T: is_generator = inspect.isgeneratorfunction(func) # Inner wrapper: runs INSIDE the @spaces.GPU lease. # Holds model_device_lock for the full inference + cleanup cycle # to prevent concurrent threads from moving models mid-inference. if is_generator: @wraps(func) def func_with_cleanup(*args, **kwargs): yield (_ENTERED, None) _enter_gpu_lease() with model_device_lock: try: _drain_stale_models() yield from func(*args, **kwargs) finally: with contextlib.suppress(Exception): _cleanup_after_gpu() _exit_gpu_lease() else: @wraps(func) def func_with_cleanup(*args, **kwargs): _enter_gpu_lease() with model_device_lock: try: _drain_stale_models() return func(*args, **kwargs) finally: with contextlib.suppress(Exception): _cleanup_after_gpu() _exit_gpu_lease() # Create the GPU-wrapped version. # Always use func_with_cleanup (which holds the lock, tracks leases, # and runs cleanup) — even without ZeroGPU, local CUDA environments # need the same protections. if ZERO_GPU_AVAILABLE: gpu_func = gpu_decorator(duration=duration)(func_with_cleanup) else: gpu_func = func_with_cleanup # User-forced CPU runs on the in-Space persistent worker pool. On local # dev (no ZeroGPU) that is a no-op: running torch in the main process # is fine because there is no GPU lease state to poison. @wraps(func) def sync_wrapper(*args, **kwargs): if is_user_forced_cpu(): if not ZERO_GPU_AVAILABLE: return func(*args, **kwargs) return _pool_dispatch(func, args, kwargs) try: return gpu_func(*args, **kwargs) except Exception as e: _reraise_gpu_error(e) @wraps(func) def generator_wrapper(*args, **kwargs): if is_user_forced_cpu(): if not ZERO_GPU_AVAILABLE: yield from func(*args, **kwargs) return # The pool runs the undecorated function, so it has no entry # marker to strip. yield from _pool_stream(func, args, kwargs) return try: yield from _strip_entry_marker(gpu_func(*args, **kwargs)) except Exception as e: _reraise_gpu_error(e) wrapper = generator_wrapper if is_generator else sync_wrapper return wrapper return decorator