File size: 17,940 Bytes
20e9692
 
 
 
 
ef8a4c9
35d8fb6
20e9692
47224bd
003b05a
20e9692
003b05a
20e9692
 
 
 
 
 
7711775
 
35d8fb6
7711775
 
35d8fb6
 
 
 
7711775
cb0af6c
58dde1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb0af6c
 
 
3d6ae90
 
 
c026fa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d6ae90
47224bd
 
20e9692
65f2050
472bb49
 
 
65f2050
 
 
3955329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
003b05a
4a0777e
 
3955329
 
 
 
4a0777e
0d7604b
 
 
 
 
1d373d6
 
0d7604b
20e9692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d7604b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65f2050
 
 
 
20e9692
47224bd
 
20e9692
 
 
47224bd
 
20e9692
 
 
 
47224bd
20e9692
 
 
47224bd
 
 
 
20e9692
 
 
0d7604b
 
 
 
 
 
47224bd
20e9692
 
3d6ae90
 
 
 
 
 
 
 
 
 
 
1d373d6
 
 
 
65f2050
1d373d6
 
 
 
 
65f2050
1d373d6
 
65f2050
1d373d6
a6f747e
 
1d373d6
 
472bb49
 
 
 
 
 
 
 
 
 
1d373d6
 
 
 
472bb49
 
 
1d373d6
 
a6f747e
 
 
 
472bb49
ef8a4c9
472bb49
1d373d6
 
65f2050
 
 
 
 
 
c6c327a
 
35d8fb6
 
 
c6c327a
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d6ae90
 
 
cb0af6c
 
 
 
 
 
 
58dde1b
 
 
 
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20e9692
 
7711775
20e9692
7711775
 
 
 
20e9692
0d7604b
 
 
7f362a6
7711775
3d6ae90
58dde1b
7f362a6
7711775
64a0a12
7f362a6
35d8fb6
 
 
 
 
20e9692
 
 
7711775
20e9692
 
 
35d8fb6
 
0d7604b
 
 
35d8fb6
 
 
c6c327a
35d8fb6
 
 
 
 
 
ef8a4c9
35d8fb6
 
 
 
 
 
 
0d7604b
35d8fb6
 
 
ef8a4c9
35d8fb6
 
0d7604b
 
 
 
 
20e9692
65f2050
20e9692
0d7604b
20e9692
35d8fb6
 
 
20e9692
35d8fb6
47224bd
3955329
df9144c
35d8fb6
20e9692
35d8fb6
 
 
 
3955329
35d8fb6
 
 
 
 
 
c6c327a
 
35d8fb6
 
3955329
20e9692
c6c327a
20e9692
35d8fb6
 
 
20e9692
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
"""
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 ("<n>s requested vs. <m>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