"""Shared GPU-first execution with CPU fallback when the GPU quota is used up, the recording is past the GPU limit, or ZeroGPU fails to run the task. A request whose ZeroGPU token expired before its lease (a long upload or download) retries on the Space's shared GPU pool first. CPU runs pass the per-caller CPU fair-use limit, except batch items, whose batch already runs them one at a time.""" from __future__ import annotations from config import ZEROGPU_QUEUE_MAX_ATTEMPTS from src.api.services import faults from src.core.alignment_admission import cpu_admission, gpu_admission from src.core.cpu_rate_limit import ( CpuActiveLimitError, CpuRateLimitError, acquire_cpu_rate_limit, release_cpu_rate_limit, ) from src.core.request_summary import external_queue_wait from src.core.zero_gpu import ( GpuBypassError, GpuQueueTimeoutError, GpuTokenExpiredError, QuotaExhaustedError, without_caller_token, ) FELL_BACK_TO_CPU = "GPU quota was exhausted, so this ran on the CPU instead." TOKEN_EXPIRED_TO_CPU = ( "The GPU request expired while the audio was still arriving and no shared GPU was free, " "so this ran on the CPU instead." ) def run( device, compute, request=None, _cpu_admission=None, _gpu_admission=None, max_gpu_attempts=None, cpu_limited=True, ): """Run one independent ML operation on GPU, falling back to the CPU on used-up quota or an expired ZeroGPU token. ``cpu_limited=False`` skips the per-caller CPU limit (batch items).""" def call(selected_device): admission = ( (_cpu_admission or (lambda: cpu_admission(request))) if selected_device == "CPU" else (_gpu_admission or (lambda: gpu_admission(request))) ) ticket = ( acquire_cpu_rate_limit(request) if selected_device == "CPU" and cpu_limited and request is not None else None ) try: with admission() as wait_s, external_queue_wait(wait_s): return compute(selected_device) finally: release_cpu_rate_limit(ticket) attempts = max( 1, (ZEROGPU_QUEUE_MAX_ATTEMPTS if max_gpu_attempts is None else max_gpu_attempts) if device == "GPU" else 1, ) for attempt in range(attempts): try: return call(device), device, None except GpuQueueTimeoutError as error: if attempt + 1 == attempts: raise faults.gpu_queue_timeout_error(error) from error except (CpuRateLimitError, CpuActiveLimitError) as error: raise faults.cpu_rate_limit_error(error) from error except ValueError as error: raise faults.unalignable_error(error) from error except QuotaExhaustedError as error: if device != "GPU": raise faults.quota_error(error) from error warning = FELL_BACK_TO_CPU break except GpuBypassError as error: print(f"[GPU] running on CPU: {error}", flush=True) warning = error.notice break except GpuTokenExpiredError: print("[GPU] caller token expired; retrying on the shared pool", flush=True) try: with without_caller_token(): return call(device), device, None except (QuotaExhaustedError, GpuQueueTimeoutError, GpuTokenExpiredError, GpuBypassError) as error: print(f"[GPU] shared pool refused too ({type(error).__name__}); running on CPU", flush=True) warning = ( error.notice if isinstance(error, GpuBypassError) else TOKEN_EXPIRED_TO_CPU ) break try: return call("CPU"), "CPU", warning except (CpuRateLimitError, CpuActiveLimitError) as error: raise faults.cpu_rate_limit_after_quota_error(error) from error except ValueError as error: raise faults.unalignable_error(error) from error