The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Workers: a worker qualifies on memory with a workflow's streaming need
Adarsh23c98b62b848
diff --git a/src/lib/lanes.ts b/src/lib/lanes.tsindex 598b1ee6..3dd2bd21 100644--- a/src/lib/lanes.ts+++ b/src/lib/lanes.ts@@ -6,7 +6,7 @@** Pure: the server, the worker program and the tests share it. `sha256hex` is passed in (node:crypto on the server).*/-import type { IndexWorkflow, RequirementIndex } from "./gpu/types";+import type { IndexWorkflow, RequirementIndex, StreamNeed } from "./gpu/types";export const BIG_FILE_BYTES = 2 * 2 ** 30;export const SMALL_LANE = "small";@@ -51,6 +51,34 @@ export const VRAM_TOLERANCE = 0.03;/** The graphics memory a workflow of `gb` whole GB needs from a worker, in bytes (3% under the whole GB). */export const minVramBytesFor = (gb: number) => Math.round((gb || 0) * 2 ** 30 * (1 - VRAM_TOLERANCE));+/** What a GPU says of its memory, as memoryFit reads it. */+export interface MemoryFacts {+ vramBytes?: number;+ /** Its system RAM. Unknown (its ComfyUI hasn't said yet): no streaming. */+ ramBytes?: number;+ /** Its ComfyUI runs with dynamic VRAM off (--disable-dynamic-vram and the like): no streaming. */+ dynamicVramOff?: boolean;+}++/**+ * Can a GPU run a workflow with its weights streamed from RAM (its streaming need, stream-needs.json): its VRAM covers the+ * need's VRAM and its RAM covers the need's RAM, each with the same 3% allowance as the VRAM test (a 32 GB PC reports+ * about 31.9 GiB). Never with no streaming need, unknown RAM, or dynamic VRAM off.+ */+export function streamFits(stream: StreamNeed | null | undefined, have: MemoryFacts): boolean {+ if (!stream || have.dynamicVramOff || !have.ramBytes || !have.vramBytes) return false;+ return minVramBytesFor(stream.vramGb) <= have.vramBytes && minVramBytesFor(stream.ramGb) <= have.ramBytes;+}++/**+ * How a GPU holds a workflow of `needGb`: every weight on its card ("vram"), part of them streamed from its RAM+ * ("stream", slower: streamFits), or not at all (null).+ */+export function memoryFit(needGb: number, stream: StreamNeed | null | undefined, have: MemoryFacts): "vram" | "stream" | null {+ if (minVramBytesFor(needGb) <= (have.vramBytes ?? 0)) return "vram";+ return streamFits(stream, have) ? "stream" : null;+}+type Sha = (text: string) => string;const bigFiles = (index: RequirementIndex, wf: IndexWorkflow) =>diff --git a/src/lib/local-comfy.ts b/src/lib/local-comfy.tsindex 6c05ebf4..53ff87fd 100644--- a/src/lib/local-comfy.ts+++ b/src/lib/local-comfy.ts@@ -6,6 +6,7 @@* through) and never sends cookies.*/import { INPUT_NAME, UUID, type HistoryEntryLike, type WantedFile } from "./relay";+import { parseArgv } from "./gpu/argv";/** Where to look, in order: Desktop's port after the usual one, then the ports people move to. */export const COMFY_PORTS = [8188, 8000, 8189, 8190, 8288, 8001, 7821] as const;@@ -327,11 +328,12 @@ export function settled(was: Finder, looks: PortLook[], remembered: number | undexport const sameFinder = (a: Finder, b: Finder): boolean => a.s === b.s && JSON.stringify({ ...a, stats: undefined }) === JSON.stringify({ ...b, stats: undefined });/**- * Facts for the server from /system_stats: never the command line, only whether its cross-site setting names this site;- * and whether Fuobe's guard answered (`guard`, when it was asked).+ * Facts for the server from /system_stats: never the command line, only whether its cross-site setting names this site+ * and whether its dynamic VRAM is off; and whether Fuobe's guard answered (`guard`, when it was asked).*/export function statsFacts(s: SystemStats, origin: string, guard?: boolean) {const argv = s.system?.argv ?? [];+ const dynamicVramOff = parseArgv(argv).dynamicVramOff;const at = argv.indexOf("--enable-cors-header");const value = at >= 0 ? argv[at + 1] : undefined;const cors = at < 0 ? undefined : !value || value.startsWith("--") || value === "*" ? ("any" as const) : value.replace(/\/+$/, "") === origin ? ("exact" as const) : ("other" as const);@@ -345,6 +347,7 @@ export function statsFacts(s: SystemStats, origin: string, guard?: boolean) {...(typeof s.system?.embedded_python === "boolean" && { portable: s.system.embedded_python }),...(cors && { cors }),...(guard !== undefined && { guard }),+ ...(dynamicVramOff && { dynamicVramOff: true as const }),};}diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex f9623bec..d218bbb3 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -235,6 +235,11 @@ export interface ComputerFacts {loras?: string[];/** A worker's GPU generation (its compute capability, "8.9"). */gpuGen?: string;+ /**+ * Its ComfyUI runs with dynamic VRAM off (--disable-dynamic-vram, --highvram, --gpu-only, --novram or --cpu), so it+ * doesn't stream model weights from RAM (src/lib/lanes.ts streamFits). Absent: on, or not said.+ */+ dynamicVramOff?: true;}export const FACT_LIMITS = { loras: 20_000, loraName: 256, text: 120 };diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 2e4da5f7..5a351044 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -3,7 +3,7 @@ import { ENGINE_WORDS } from "@/lib/engine-error";import crypto from "node:crypto";import { FINISH_KINDS, type FinishTicket } from "@/lib/finish-ticket";import { ceilingProblem, cleanCeiling, insideCeiling, lanesInside, type Ceiling } from "@/lib/job-ticket";-import { allLanes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, minVramBytesFor, needsOf, packKey, partLanes, unloadedNodes, type FileNeed, type Inventory, type NodePack, type Needs } from "@/lib/lanes";+import { allLanes, hasFiles, laneLabel, lanesFor, MEDIA_KINDS, memoryFit, needsOf, packKey, partLanes, streamFits, unloadedNodes, type FileNeed, type Inventory, type NodePack, type Needs } from "@/lib/lanes";import { fileChoices, hasVariants, pickFiles, swapGraphFiles, type FileChoice } from "@/lib/gpu/model-variants";import type { FileKey } from "@/lib/gpu/types";import { POOL_WORDS, RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type CpuSlot, type WorkerAnswer, type WorkerBeat, type WorkerHolding } from "@/lib/relay";@@ -935,17 +935,29 @@ function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): Claimed/*** The files this worker runs a workflow with (src/lib/gpu/model-variants.ts pickFiles): a model variant made for its* card's generation (gpuGen in its facts), else the workflow's own files, else another variant, by the file sets it has- * whole (its lanes' `sets`, from the files it verified) and its VRAM. Null when it has none of them, or too little VRAM.- * A worker program older than VARIANT_PROTOCOL gets the workflow's own files only.+ * whole (its lanes' `sets`, from the files it verified) and its memory: the VRAM of the set, or the workflow's streaming+ * need in VRAM and RAM (memoryFit). Null when it has none of them, or too little memory. A worker program older than+ * VARIANT_PROTOCOL gets the workflow's own files only.*/export function workerFiles(w: Pick<WorkerRow, "lanes_json" | "facts_json" | "protocol">, workflowId: string): FileChoice | null {const cap = capableOf(w);if (!cap.workflows.includes(workflowId)) return null;const whole = cap.sets?.[workflowId] ?? [null];const facts = json<ComputerFacts>(w.facts_json, {});- const vram = facts.vramBytes ?? 0;- const choices = fileChoices(loadIndex(), workflowId).filter((c) => whole.includes(c.variant));- return pickFiles(choices, { gpuGen: facts.gpuGen ?? null, has: () => true, fits: (gb) => minVramBytesFor(gb) <= vram, variants: (w.protocol ?? 0) >= VARIANT_PROTOCOL });+ const index = loadIndex();+ const stream = index.workflows[workflowId]?.stream;+ const choices = fileChoices(index, workflowId).filter((c) => whole.includes(c.variant));+ return pickFiles(choices, { gpuGen: facts.gpuGen ?? null, has: () => true, fits: (gb) => memoryFit(gb, stream, facts) !== null, variants: (w.protocol ?? 0) >= VARIANT_PROTOCOL });+}++/**+ * Has this worker the memory for a task's workflow with no model variants: the VRAM the task needs (with the 3%+ * allowance already in it), or the workflow's streaming need in VRAM and RAM (streamFits).+ */+function memoryFor(needs: Needs | null, w: Pick<WorkerRow, "facts_json">): boolean {+ const facts = json<ComputerFacts>(w.facts_json, {});+ if ((needs?.minVramBytes ?? 0) <= (facts.vramBytes ?? 0)) return true;+ return !!needs?.workflowId && streamFits(loadIndex().workflows[needs.workflowId]?.stream, facts);}/** How long a task should take on this worker: the lane's bench median there, or the task's own estimate. */@@ -978,10 +990,11 @@ function fits(t: TaskRow, w: WorkerRow, now: number): boolean {if (needs?.workflowId ? !cap.workflows.includes(needs.workflowId) : !cap.lanes.includes(lane)) return false;// The files the run adds beyond its workflow's own (a look's LoRAs): only a worker that verified each one.if (needs?.runtime?.length && !hasFiles(inventoryOf(w), needs.runtime)) return false;- // A workflow with model variants: the files (its own or a variant's) and the VRAM of the choice this worker would run.+ // A workflow with model variants: the files (its own or a variant's) and the memory of the choice this worker would+ // run. Either way, the workflow's streaming need counts as well as its VRAM need.if (needs?.workflowId && hasVariants(loadIndex(), needs.workflowId)) {if (!workerFiles(w, needs.workflowId)) return false;- } else if ((needs?.minVramBytes ?? 0) > (factsOf(w).vramBytes ?? 0)) return false;+ } else if (!memoryFor(needs, w)) return false;if (now - t.created_at < w.claim_after_ms + (allow[lane]?.delayMs ?? 0)) return false;return true;}@@ -1576,7 +1589,7 @@ function ableWorkers(workflowId: string | null, o: { size?: Needs["size"]; tickeif (!needs || !(lane! in allow) || !cap.workflows.includes(workflowId) || ceilingProblem(ceiling, { workflowId, lane, size: o.size })) return false;if (o.files?.length && !hasFiles(inventoryOf(w), o.files)) return false;if (hasVariants(loadIndex(), workflowId)) return !!workerFiles(w, workflowId);- return needs.minVramBytes <= (factsOf(w).vramBytes ?? 0);+ return memoryFor(needs, w);});}diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex db68771c..8ed6efb9 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -634,6 +634,7 @@ export function cleanFacts(f: unknown, keep?: ComputerFacts): ComputerFacts {...((o.cors === "exact" || o.cors === "any" || o.cors === "other") && { cors: o.cors }),...(typeof o.guard === "boolean" && { guard: o.guard }),...(typeof o.gpuGen === "string" && /^\d{1,2}\.\d{1,2}$/.test(o.gpuGen) && { gpuGen: o.gpuGen }),+ ...(o.dynamicVramOff === true && { dynamicVramOff: true as const }),...(loras && { loras }),};}diff --git a/tests/stream-needs.test.ts b/tests/stream-needs.test.tsindex 3fabdf39..d7c54001 100644--- a/tests/stream-needs.test.ts+++ b/tests/stream-needs.test.ts@@ -1,23 +1,35 @@import fs from "node:fs";import path from "node:path";-import { describe, expect, it, vi } from "vitest";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { buildIndex, loadInputs } from "../scripts/comfy/build-requirements.mjs";import { parseIndex } from "@/lib/gpu/requirements";import type { RequirementIndex } from "@/lib/gpu/types";+import { memoryFit, minVramBytesFor, streamFits } from "@/lib/lanes";+import { statsFacts } from "@/lib/local-comfy";+import { tempDir } from "./helpers/temp-dir";/*** Streaming needs (workflows/comfyui/stream-needs.json): a workflow a card can't hold whole still runs on it with part of- * its weights kept in system RAM and streamed to the card each step (ComfyUI's dynamic VRAM loading). The requirements- * build checks the file and writes each workflow's need into requirements.json.+ * its weights kept in system RAM and streamed to the card each step (ComfyUI's dynamic VRAM loading). The build checks+ * the file; a worker qualifies on memory with the workflow's VRAM, or with the streaming need's VRAM and RAM (3%+ * allowance on both, never with unknown RAM or dynamic VRAM off).*/vi.setConfig({ testTimeout: 60_000 });+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-stream-needs-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+delete process.env.FUOBE_PASSWORD;const ROOT = path.resolve(__dirname, "..");const LIBRARY = path.join(ROOT, "workflows/comfyui");const idx: RequirementIndex = parseIndex(JSON.parse(fs.readFileSync(path.join(LIBRARY, "requirements.json"), "utf8")));+const GB = 2 ** 30;const H3 = "minimax-h3-image-t2i";+const KREA = "krea2-turbo-t2i";const STREAMED = ["minimax-h3-image-t2i","minimax-h3-image-edit",@@ -56,3 +68,123 @@ describe("the catalog's streaming needs (build-requirements.mjs)", () => {expect(build([entry({ vramGb: 12, ramGb: 48 })]).workflows[H3].stream).toEqual({ vramGb: 12, ramGb: 48 });});});++describe("the memory rule (memoryFit, streamFits)", () => {+ const stream = { vramGb: 10, ramGb: 32 };+ it("VRAM alone, as before", () => {+ expect(memoryFit(32, stream, { vramBytes: 32 * GB })).toBe("vram");+ expect(memoryFit(32, undefined, { vramBytes: 24 * GB, ramBytes: 64 * GB })).toBeNull();+ });++ it("the streaming need's VRAM and RAM", () => {+ expect(memoryFit(32, stream, { vramBytes: 10 * GB, ramBytes: 32 * GB })).toBe("stream");+ expect(memoryFit(32, stream, { vramBytes: 8 * GB, ramBytes: 64 * GB })).toBeNull();+ expect(memoryFit(32, stream, { vramBytes: 12 * GB, ramBytes: 16 * GB })).toBeNull();+ });++ it("never with unknown RAM, unknown VRAM, or dynamic VRAM off", () => {+ expect(memoryFit(32, stream, { vramBytes: 10 * GB })).toBeNull();+ expect(streamFits(stream, { ramBytes: 64 * GB })).toBe(false);+ expect(memoryFit(32, stream, { vramBytes: 10 * GB, ramBytes: 64 * GB, dynamicVramOff: true })).toBeNull();+ });++ it("allows 3% under the whole GB for both, as the VRAM test does", () => {+ // A 32 GB PC reports about 31.9 GiB of RAM; a 10 GB card a little under 10 GiB.+ expect(memoryFit(32, stream, { vramBytes: 9.8 * GB, ramBytes: 31.9 * GB })).toBe("stream");+ expect(streamFits(stream, { vramBytes: minVramBytesFor(10), ramBytes: minVramBytesFor(32) })).toBe(true);+ expect(streamFits(stream, { vramBytes: minVramBytesFor(10) - 1, ramBytes: 64 * GB })).toBe(false);+ expect(streamFits(stream, { vramBytes: 12 * GB, ramBytes: minVramBytesFor(32) - 1 })).toBe(false);+ });++ it("a ComfyUI's facts say when its dynamic VRAM is off", () => {+ const stats = (argv: string[]) => statsFacts({ system: { argv, ram_total: 32 * GB }, devices: [] }, "https://studio.test");+ expect(stats(["main.py"]).dynamicVramOff).toBeUndefined();+ expect(stats(["main.py", "--disable-dynamic-vram"]).dynamicVramOff).toBe(true);+ expect(stats(["main.py", "--highvram"]).dynamicVramOff).toBe(true);+ });+});++const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const tasks = await import("@/server/computer/tasks");+const pool = await import("@/server/computer/pool");+const workers = await import("@/server/computer/workers");+const { loadIndex } = await import("@/server/gpu/index-file");++describe("which workers qualify on memory (the claim)", () => {+ let clock = Date.UTC(2026, 10, 3, 3, 0, 0);+ const VERSION = "d".repeat(64);+ type W = { id: string; token: string };+ const row = (w: W) => workers.getWorker(w.id)!;+ const filesOf = (id: string) =>+ [...loadIndex().workflows[id].files, ...(loadIndex().workflows[id].variants ?? []).flatMap((v) => Object.values(v.files))].map((k) => {+ const f = loadIndex().files[k];+ return { folder: f.folder, name: f.file, size: f.sizeBytes, sha256: "a".repeat(64) };+ });+ const beat = (w: W) =>+ pool.workerBeat(+ row(w),+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 5, version: "1.0.0", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: VERSION }),+ clock,+ );+ function worker(name: string, id: string, facts: Record<string, unknown>): W {+ const w = pool.addWorker(name);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: { [pool.poolLane(id)]: { delayMs: 0 } }, claimAfterMs: 0 });+ beat(w);+ pool.saveInventory(row(w), { files: filesOf(id), nodePacks: [], media: ["image"] });+ db().prepare("UPDATE relay_workers SET facts_json = ?, catalog_version = ? WHERE id = ?").run(JSON.stringify(facts), VERSION, w.id);+ beat(w);+ return w;+ }+ let gens = 0;+ function job(id: string): string {+ const gid = `gen-s-${++gens}`;+ db()+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', '{}', '[]', ?, ?)")+ .run(gid, clock, clock);+ const graph = JSON.parse(fs.readFileSync(path.join(LIBRARY, `${id}.json`), "utf8"));+ const t = tasks.createTask({ principal: "owner", generationId: gid, graph, workflowId: id, pool: pool.poolFields(id, {}, clock) }).id;+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(clock, t);+ return t;+ }+ const claim = (w: W) => pool.workerClaim(row(w), [], clock);++ beforeAll(() => setSetting("comfyWhere", "workers"));+ beforeEach(() => {+ resetRates();+ clock += 60 * 60_000;+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+ });++ it("VRAM only: a card that holds it whole, as before", () => {+ const id = job(H3);+ expect(claim(worker("big", H3, { vramBytes: 32 * GB }))?.id).toBe(id);+ });++ it("VRAM and RAM: a 10 GB card with 32 GB of RAM takes it, and a run counts it", () => {+ const id = job(H3);+ const w = worker("small", H3, { vramBytes: 9.8 * GB, ramBytes: 31.9 * GB });+ expect(pool.workersCanRun(H3)).toBe(true);+ expect(claim(w)?.id).toBe(id);+ });++ it("unknown RAM, too little RAM, too small a card, or dynamic VRAM off: it takes nothing", () => {+ job(H3);+ expect(claim(worker("no-ram", H3, { vramBytes: 10 * GB }))).toBeNull();+ expect(claim(worker("little-ram", H3, { vramBytes: 10 * GB, ramBytes: 16 * GB }))).toBeNull();+ expect(claim(worker("small-card", H3, { vramBytes: 8 * GB, ramBytes: 64 * GB }))).toBeNull();+ expect(claim(worker("dyn-off", H3, { vramBytes: 10 * GB, ramBytes: 64 * GB, dynamicVramOff: true }))).toBeNull();+ expect(pool.workersCanRun(H3)).toBe(false);+ });++ it("a workflow with model variants: the streaming need counts for the files the worker runs", () => {+ const id = job(KREA);+ const c = claim(worker("ampere", KREA, { vramBytes: 10 * GB, ramBytes: 32 * GB, gpuGen: "8.6" }))!;+ expect(c.id).toBe(id);+ expect(c.variant).toBe("int8");+ job(KREA);+ expect(claim(worker("ampere-low-ram", KREA, { vramBytes: 10 * GB, ramBytes: 16 * GB, gpuGen: "8.6" }))).toBeNull();+ });+});