Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

15.0 KB
Raw Blame
"""Async client of a persistent JSON-lines worker process. One owner task per worker writes the requests and a reader
task resolves their futures, so concurrent callers never interleave and no lock is held while a reply is awaited.
"""

from __future__ import annotations

import asyncio
import contextlib
import itertools
import json
import logging
import os
import sys
from collections.abc import Callable
from typing import Any

from . import aio, memguard, paths

log = logging.getLogger("mimvox.worker")

Progress = Callable[[dict[str, Any]], None]


class WorkerDied(Exception):
    """The worker process ended while a request was queued for it or running."""


class WorkerError(Exception):
    def __init__(self, code: str, message: str, permanent: bool = False) -> None:
        super().__init__(message)
        self.code = code
        self.message = message
        self.permanent = permanent


class WorkerCancelled(Exception):
    """The worker reports the op as cancelled."""


class _Request:
    __slots__ = ("abandoned", "done", "id", "msg", "progress", "seen", "stall", "start", "timeout")

    def __init__(
        self,
        rid: int,
        msg: dict[str, Any],
        progress: Progress | None,
        timeout: float | None,
        start: bool,
        stall: float | None = None,
    ) -> None:
        self.id = rid
        self.msg = msg
        self.done: asyncio.Future[dict[str, Any]] = asyncio.get_running_loop().create_future()
        self.progress = progress
        self.timeout = timeout
        self.stall = stall
        self.seen = 0.0  # loop time of the latest message about this request
        self.start = start
        self.abandoned = False


_CLIENTS: list[WorkerClient] = []


async def make_room(asking: WorkerClient) -> list[str]:
    """Every other running, idle worker drops its models. Returns the names of those that did."""
    freed = []
    for other in _CLIENTS[:]:  # a copy: releasing awaits, a client may be added meanwhile
        if other is asking or not other.alive() or other.busy():
            continue
        try:
            await other._call_once("release", None, None, 60.0, False)
            freed.append(other.name)
            for hook in other.on_release:
                hook()
        except Exception as exc:
            log.warning("the %s worker could not release its models: %s", other.name, exc)
    return freed


async def stop_idle(asking: WorkerClient) -> list[str]:
    """Every other running, idle worker ends; each starts again on its next request. A released model still leaves its
    process's CUDA context and allocator cache on the card (2.2 GB measured for the OmniVoice worker)."""
    stopped = []
    for other in _CLIENTS[:]:
        if other is asking or not other.alive() or other.busy():
            continue
        await other.stop()
        stopped.append(other.name)
        for hook in other.on_release:
            hook()
    return stopped


class WorkerClient:
    def __init__(self, name: str, argv: list[str], env: dict[str, str], start_timeout: float = 240.0) -> None:
        _CLIENTS.append(self)
        self.on_release: list[Callable[[], None]] = []
        self.name = name
        self.argv = argv
        self.env = env
        self.start_timeout = start_timeout
        self._ids = itertools.count(1)
        self._queue: asyncio.Queue[_Request | None] | None = None
        self._owner: asyncio.Task[None] | None = None
        self._proc: asyncio.subprocess.Process | None = None
        self._exited: asyncio.Future[int] | None = None
        self._ready: asyncio.Future[None] | None = None
        self._pending: dict[int, _Request] = {}
        self.current: _Request | None = None
        self.last_error: str | None = None
        self.pid: int | None = None

    def alive(self) -> bool:
        return self._proc is not None and self._proc.returncode is None

    def busy(self) -> bool:
        return self.current is not None or (self._queue is not None and not self._queue.empty())

    async def call(
        self,
        op: str,
        params: dict[str, Any] | None = None,
        progress: Progress | None = None,
        timeout: float | None = None,
        start: bool = True,
        retry: bool = True,
        stall: float | None = None,
    ) -> dict[str, Any]:
        """A worker that dies under the request is restarted and the request retried once (``retry``), but not while the
        engine shuts down.
        ``start=False``: answer ``{}`` without starting a process when none is running. ``stall``: the request
        also fails after that many seconds without a progress message from the worker (``timeout`` None: no cap)."""
        try:
            return await self._call_once(op, params, progress, timeout, start, stall)
        except WorkerDied as exc:
            self.last_error = str(exc)
            if not retry or aio.closing():
                raise
            log.warning("%s worker died under %s (%s); retrying once", self.name, op, exc)
        except WorkerError as exc:
            if exc.code != "no_vram" or not retry:
                raise
            freed = await make_room(self)
            if not freed:
                raise
            log.warning(
                "%s: not enough GPU memory for %s; %s released their models, retrying once",
                self.name,
                op,
                ", ".join(freed),
            )
        return await self._call_once(op, params, progress, timeout, start, stall)

    async def _call_once(
        self,
        op: str,
        params: dict[str, Any] | None,
        progress: Progress | None,
        timeout: float | None,
        start: bool,
        stall: float | None = None,
    ) -> dict[str, Any]:
        req = _Request(next(self._ids), {"op": op, **(params or {})}, progress, timeout, start, stall)
        memguard.refresh()
        self._ensure_owner()
        assert self._queue is not None
        self._queue.put_nowait(req)
        try:
            return await asyncio.shield(req.done)
        except asyncio.CancelledError:
            req.abandoned = True
            if self.current is req and self.alive():
                self._write({"op": "cancel", "id": req.id})
            raise

    def cancel_current(self, op: str | None = None, when: Callable[[dict[str, Any]], bool] | None = None) -> None:
        """Its caller gets ``WorkerCancelled``, or the result if the op cannot stop any more."""
        cur = self.current
        if (
            cur is not None
            and (op is None or cur.msg.get("op") == op)
            and (when is None or when(cur.msg))
            and self.alive()
        ):
            self._write({"op": "cancel", "id": cur.id})

    def _ensure_owner(self) -> None:
        if self._queue is None:
            self._queue = asyncio.Queue()
        if self._owner is None or self._owner.done():
            self._owner = aio.spawn(self._serve(self._queue), name=f"{self.name}-owner")

    async def _serve(self, queue: asyncio.Queue[_Request | None]) -> None:
        async for req in aio.queue_items(queue):
            if req.abandoned or req.done.done():
                continue
            try:
                if not self.alive():
                    if not req.start:
                        req.done.set_result({})
                        continue
                    if aio.closing():
                        raise WorkerDied(f"the engine is shutting down: the {self.name} worker is not started again")
                    await self._spawn()
                await self._exchange(req)
            except Exception as exc:
                if not req.done.done():
                    req.done.set_exception(exc)
            finally:
                self.current = None

    async def _exchange(self, req: _Request) -> None:
        self.current = req
        self._pending[req.id] = req
        self._write({"id": req.id, **req.msg})
        if req.abandoned:  # cancelled between dequeuing and sending
            self._write({"op": "cancel", "id": req.id})
        why = await _watch(req)
        if why is not None:
            self._pending.pop(req.id, None)
            req.done.set_exception(WorkerError("internal", f"the {self.name} worker {why} in {req.msg['op']}"))
            await self.stop(graceful=False)
        if req.done.done() and not req.done.cancelled():
            req.done.exception()  # mark it retrieved even when the caller has gone away

    async def _spawn(self) -> None:
        loop = asyncio.get_running_loop()
        kwargs: dict[str, Any] = {}
        if sys.platform == "win32":
            kwargs["creationflags"] = aio.NO_WINDOW
        log.info("starting the %s worker", self.name)
        proc = await asyncio.create_subprocess_exec(
            *self.argv,
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE,
            stderr=None,
            env=self.env,
            limit=64 * 1024 * 1024,
            **kwargs,
        )
        self._proc, self.pid = proc, proc.pid
        self._ready = loop.create_future()
        exited: asyncio.Future[int] = loop.create_future()
        self._exited = exited
        aio.spawn(self._read(proc, exited), name=f"{self.name}-reader")
        done, _ = await asyncio.wait(
            {self._ready, exited}, timeout=self.start_timeout, return_when=asyncio.FIRST_COMPLETED
        )
        if self._ready in done and not self._ready.cancelled():
            log.info("%s worker ready (pid %s)", self.name, proc.pid)
            return
        if exited.done():
            raise WorkerDied(f"the {self.name} worker exited during start-up (code {exited.result()}; see the log)")
        await self.stop(graceful=False)
        raise WorkerError("internal", f"the {self.name} worker did not start in time")

    async def _read(self, proc: asyncio.subprocess.Process, exited: asyncio.Future[int]) -> None:
        assert proc.stdout is not None
        try:
            async for raw in proc.stdout:
                self._dispatch(raw)
        except (ValueError, OSError) as exc:
            log.warning("%s worker output unreadable: %s", self.name, exc)
        finally:
            code = await proc.wait()
            if self._proc is proc:
                self._proc = None
            for hook in self.on_release:  # the models went with the process
                hook()
            err = WorkerDied(f"the {self.name} worker exited (code {code})")
            for req in list(self._pending.values()):
                if not req.done.done():
                    req.done.set_exception(err)
            self._pending.clear()
            if self._ready is not None and not self._ready.done():
                self._ready.cancel()
            if not exited.done():
                exited.set_result(code)
            log.info("%s worker (pid %s) exited with code %s", self.name, proc.pid, code)
            memguard.report(f"after the {self.name} worker exited")

    def _dispatch(self, raw: bytes) -> None:
        try:
            msg = json.loads(raw)
            if not isinstance(msg, dict):
                raise TypeError("not an object")
        except (ValueError, TypeError):
            log.warning("unexpected %s worker output: %s", self.name, raw[:300])
            return
        if "event" in msg:
            if msg["event"] == "ready":
                if self._ready is not None and not self._ready.done():
                    self._ready.set_result(None)
            else:
                log.info("%s worker: %s", self.name, msg)
            return
        req = self._pending.get(msg.get("id"))  # type: ignore[arg-type]
        if req is None:
            return
        req.seen = asyncio.get_running_loop().time()
        if "progress" in msg:
            if req.progress is not None and not req.abandoned:
                try:
                    req.progress(msg["progress"])
                except Exception:
                    log.exception("%s progress callback failed", self.name)
            return
        del self._pending[req.id]
        if req.done.done():
            return
        if msg.get("ok"):
            req.done.set_result(msg.get("result") or {})
        elif msg.get("code") == "cancelled":
            req.done.set_exception(WorkerCancelled())
        else:
            req.done.set_exception(
                WorkerError(
                    str(msg.get("code") or "internal"), str(msg.get("error") or "failed"), bool(msg.get("permanent"))
                )
            )

    def _write(self, obj: dict[str, Any]) -> None:
        proc = self._proc
        if proc is None or proc.stdin is None or proc.returncode is not None:
            return
        try:
            proc.stdin.write((json.dumps(obj, ensure_ascii=False, default=paths.json_default) + "\n").encode("utf-8"))
        except (OSError, RuntimeError) as exc:
            log.warning("%s worker pipe closed: %s", self.name, exc)

    async def stop(self, graceful: bool = True) -> None:
        """Pending requests fail with ``WorkerDied``."""
        proc, exited = self._proc, self._exited
        if proc is None or proc.returncode is not None:
            return
        if graceful:
            self._write({"op": "quit"})
            try:
                if proc.stdin is not None:
                    await proc.stdin.drain()
            except (OSError, ConnectionError):
                pass
            if exited is not None:
                done, _ = await asyncio.wait({exited}, timeout=5.0)
                if done:
                    return
        with contextlib.suppress(ProcessLookupError):
            proc.kill()
        if exited is not None:
            await asyncio.shield(exited)

    async def close(self) -> None:
        await self.stop()
        if self._queue is not None:
            self._queue.put_nowait(None)


async def _watch(req: _Request) -> str | None:
    """Waits for the answer; why the request gave up (past ``timeout``, or ``stall`` seconds without news), or None."""
    loop = asyncio.get_running_loop()
    begun = req.seen = loop.time()
    while True:
        now = loop.time()
        limits = []
        if req.timeout is not None:
            limits.append(begun + req.timeout - now)
        if req.stall is not None:
            limits.append(req.seen + req.stall - now)
        wait = max(0.0, min(limits)) if limits else None
        done, _ = await asyncio.wait({req.done}, timeout=wait)
        if done:
            return None
        now = loop.time()
        if req.timeout is not None and now - begun >= req.timeout:
            return "timed out"
        if req.stall is not None and now - req.seen >= req.stall:
            return f"made no progress for {req.stall:.0f} s"


def isolated() -> list[str]:
    """``-I`` ignores ``PYTHONPYCACHEPREFIX``, so the engine's bytecode cache folder is passed with ``-X``."""
    prefix = sys.pycache_prefix
    return ["-I", "-X", f"pycache_prefix={prefix}"] if prefix else ["-I"]


def child_env(**extra: str) -> dict[str, str]:
    # transformers 5.25+ fetches Hub kernels by default; the workers run offline and use the PyTorch ops.
    env = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUNBUFFERED="1", USE_HUB_KERNELS="0", **extra)
    env.pop("PYTHONPATH", None)
    return env