Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

5.6 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Waits for unrelated work to drain or refuses; arbiter handoff would cancel video or chat streams."""

from __future__ import annotations

import asyncio
import functools
import time
from typing import Any, Optional

from core.inference.gpu_arbiter import (
    DIFFUSION,
    VIDEO,
    GpuBusyForAnotherAccountError,
    raise_if_other_accounts_active,
)
from core.inference.media_switch_errors import busy, probe
from core.inference.media_switch_locks import switcher_count, waiter_count

POLL_S = 0.2


def backend_for(owner: str) -> Any:
    """The live backend object for *owner*, resolved on each call rather than cached."""
    if owner == DIFFUSION:
        from core.inference.diffusion_engine_router import get_active_diffusion_engine
        return get_active_diffusion_engine()
    from core.inference.video import get_video_backend

    return get_video_backend()


def other_owner(owner: str) -> str:
    """The media backend this one would take the GPU from."""
    return VIDEO if owner == DIFFUSION else DIFFUSION


def load_takes_the_gpu() -> bool:
    """Whether this load takes the GPU; a CPU-only device releases ownership and must not wait on chat"""
    try:
        from core.inference.diffusion_device import resolve_diffusion_device_target
        return resolve_diffusion_device_target().device != "cpu"
    except Exception:  # noqa: BLE001 -- assume the handoff, which is the careful direction
        return True


def chat_busy(count_pending: bool = True) -> bool:
    """With count_pending False, requests queued behind the held gate are not counted (not yet started)"""
    try:
        from core.inference.llama_keepwarm import other_inference_request_count
    except Exception:  # noqa: BLE001 -- no chat stack means no chat work
        return False
    try:
        # chat's counter covers media requests too, and none of those is using chat
        parked = switcher_count()
        counted = other_inference_request_count(
            current_request_counted = True, include_pending = count_pending
        )
        from core.inference.load_policy import parent_chat_counted

        # A chat tools call runs inside its chat, which waits on this switch: that chat, when it is
        # counted at all (an external-provider chat is not), is never its own blocker.
        if parent_chat_counted():
            counted -= 1
        # counted once, since a request parked on a switch lock is a waiter inside its own switch
        return max(0, counted - max(0, parked - 1)) > 0
    except Exception:  # noqa: BLE001
        return False


def backend_busy(backend: Any) -> bool:
    """One off-loop read of whether a load or generation is running. Mirrors media_keepwarm."""
    if backend.loading_repo_ids():
        return True
    return bool((backend.generate_progress() or {}).get("active"))


def other_backend_busy(owner: str) -> bool:
    """Imported lazily, so an unopened other media page does not pull torch in just to answer."""
    import sys

    other = other_owner(owner)
    wanted = (
        {"core.inference.video"}
        if other == VIDEO
        else {"core.inference.diffusion", "core.inference.sd_cpp_backend"}
    )
    if not wanted & set(sys.modules):
        return False
    try:
        return backend_busy(backend_for(other))
    except Exception:  # noqa: BLE001 -- an unavailable backend is not busy work
        return False


async def drain(
    owner: str,
    backend: Any,
    deadline: float,
    *,
    count_pending: bool = True,
    probe_deadline: Optional[float] = None,
    check_chat: bool = True,
    kind: str = "image",
    openai_errors: bool = True,
) -> bool:
    """Queued waiters are discounted, else two requests for one absent model each wait the other out."""
    from core.inference.media_keepwarm import other_request_count

    # device configuration is resolved once, not on every poll: that cost ~150 round-trips a switch
    cross_owner = await asyncio.to_thread(load_takes_the_gpu)
    while True:
        if cross_owner:
            try:
                raise_if_other_accounts_active()
            except GpuBusyForAnotherAccountError as exc:
                raise busy(kind, openai_errors, retry_after = exc.retry_after) from exc
        # this request is itself tracked and itself a waiter, so it counts as neither
        others = other_request_count(
            owner, current_request_counted = True, count_pending = count_pending
        )
        others -= waiter_count(owner)
        if cross_owner:
            other = other_owner(owner)
            others += max(
                0,
                other_request_count(other, count_pending = count_pending) - switcher_count(other),
            )
        probe_by = deadline if probe_deadline is None else probe_deadline
        bounded_probe = functools.partial(probe, kind = kind, openai_errors = openai_errors)
        if (
            others <= 0
            and not await bounded_probe(backend_busy, backend, probe_by)
            and not (cross_owner and await bounded_probe(other_backend_busy, owner, probe_by))
            and not (
                cross_owner
                and check_chat
                and await bounded_probe(functools.partial(chat_busy, count_pending), None, probe_by)
            )
        ):
            return True
        if time.monotonic() >= deadline:
            return False
        await asyncio.sleep(POLL_S)


__all__ = [
    "POLL_S",
    "backend_busy",
    "backend_for",
    "chat_busy",
    "drain",
    "load_takes_the_gpu",
    "other_backend_busy",
    "other_owner",
]