// THE GPU ARBITER — one place that says who may use the 8 GB card now // (release 27, S6). Four users share it: transcription (the worker pool's // local engines), text-to-speech with a GPU engine (Orpheus), local-model // drafting (`report-draft` on `draft:local`, ollama) and the local digest lane // (ollama too). // // The rules: // - a DIGEST yields to transcription — digestYield.ts's // transcriptionActivity(), unchanged (its CPU carve-out and gap signal); // - TTS waits for transcription on a GPU worker AND for a running draft call; // - a DRAFT call waits for transcription (the digest's signal) AND for a // running GPU synthesis. // Each is a YIELD at the start of one unit of work (a synthesis, one ollama // call), never an interruption: a call in flight finishes. // // "Running" is the in-process hold a user takes around its unit of work // (`holdGpu`), so the check is exact and needs no registry scan; the editor is // one process and every one of these runs in it. A draft's hold wraps each // ollama request (gpuGatedFetch), so a synthesis can slip in between two calls // of a long draft, and a draft waits out a synthesis between its calls. import { getWorkerPool } from "../jobs/workerPool"; import { transcriptionActivity } from "./digestYield"; export type GpuUser = "tts" | "draft-local"; const holds: Record = { tts: 0, "draft-local": 0 }; // Take the GPU for one unit of work; the release is idempotent. export function holdGpu(user: GpuUser): () => void { holds[user]++; let released = false; return () => { if (released) return; released = true; holds[user] = Math.max(0, holds[user] - 1); }; } export function gpuHolds(): Readonly> { return { ...holds }; } // A transcription running on a local worker that is not explicitly on the CPU // (an unknown device may be the GPU: parakeet-cli's default can be). export function transcriptionOnGpu(): boolean { try { return getWorkerPool() .summary() .some((w) => w.busy && w.kind === "local" && (w.device ?? "").toLowerCase() !== "cpu"); } catch { return false; // fail open: an unreadable pool must not wedge a lane } } export type GpuVerdict = { busy: boolean; reason: string | null }; // Whether `user` must wait now, and for whom. The signals are injectable for // the tests (and default to the live ones). export function gpuBusyFor( user: GpuUser, signals: { transcriptionOnGpu?: () => boolean; transcriptionLane?: () => boolean; holds?: Readonly> } = {}, ): GpuVerdict { const h = signals.holds ?? holds; if (user === "tts") { if ((signals.transcriptionOnGpu ?? transcriptionOnGpu)()) return { busy: true, reason: "a transcription is running" }; if (h["draft-local"] > 0) return { busy: true, reason: "a local model is drafting" }; return { busy: false, reason: null }; } const lane = signals.transcriptionLane ?? (() => { try { return transcriptionActivity().busy; } catch { return false; } }); if (lane()) return { busy: true, reason: "a transcription is running" }; if (h.tts > 0) return { busy: true, reason: "a synthesis is running" }; return { busy: false, reason: null }; } // Wait until `busy()` is false — to START; a unit of work running is never // interrupted. Answers the milliseconds waited. Abortable. export async function waitForGpu(opts: { busy: () => boolean | GpuVerdict; onLog: (line: string) => void; signal?: AbortSignal; pollMs?: number; what?: string; }): Promise { const t0 = Date.now(); const check = (): GpuVerdict => { const v = opts.busy(); return typeof v === "boolean" ? { busy: v, reason: v ? "a transcription is running" : null } : v; }; let v = check(); if (!v.busy) return 0; opts.onLog(`Waiting for the GPU: ${v.reason ?? "it is in use"}…`); while (v.busy) { if (opts.signal?.aborted) throw new Error("cancelled while waiting for the GPU"); await new Promise((r) => setTimeout(r, opts.pollMs ?? 5000)); v = check(); } const waited = Date.now() - t0; opts.onLog(`The GPU is free (waited ${(waited / 1000).toFixed(1)}s)`); return waited; } // Wait for the GPU and hold it as `user` around `work`. export async function withGpu( user: GpuUser, work: () => Promise, opts: { onLog: (line: string) => void; signal?: AbortSignal; pollMs?: number; busy?: () => boolean | GpuVerdict }, ): Promise { await waitForGpu({ busy: opts.busy ?? (() => gpuBusyFor(user)), onLog: opts.onLog, signal: opts.signal, pollMs: opts.pollMs }); const release = holdGpu(user); try { return await work(); } finally { release(); } } // A fetch for the ollama config of a `draft:local` job: every chat request // waits for the GPU and holds it as a draft while in flight. The unload call // (`/api/generate` with keep_alive 0) frees memory and is never held back. export function gpuGatedFetch( base: typeof fetch, opts: { onLog: (line: string) => void; signal?: AbortSignal; pollMs?: number; busy?: () => boolean | GpuVerdict }, ): typeof fetch { return (async (input: Parameters[0], init?: Parameters[1]) => { const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; if (!/\/api\/chat$/.test(url)) return base(input, init); // The body is read inside the hold: ollama answers once it has generated, // and the hold ends when the answer is in hand. return withGpu( "draft-local", async () => { const res = await base(input, init); const body = await res.arrayBuffer(); return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers }); }, opts, ); }) as typeof fetch; }