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
Worker: its ComfyUI starts with Comfy Kitchen attention
Adarsh45a682b341e9
diff --git a/bin/lib/worker/comfy.mjs b/bin/lib/worker/comfy.mjsindex 4a9f3fdc..2b9e48f7 100644--- a/bin/lib/worker/comfy.mjs+++ b/bin/lib/worker/comfy.mjs@@ -129,10 +129,67 @@ export function partnerFlag(comfyDir) {}}+/** The flags this ComfyUI's own argument list names (comfy/cli_args.py), or an empty set when it can't be read. */+export function comfyFlags(comfyDir) {+ try {+ return new Set(fs.readFileSync(path.join(comfyDir ?? "", "comfy", "cli_args.py"), "utf8").match(/"--[a-z0-9-]+"/g)?.map((f) => f.slice(1, -1)) ?? []);+ } catch {+ return new Set();+ }+}++/** The option that turns on Comfy Kitchen attention, which the GPU's ComfyUI gets by default. */+export const KITCHEN = "--use-ck-attention";+/** What ComfyUI says when it was asked for Comfy Kitchen attention that it can't load (it then exits). */+export const KITCHEN_MISSING = "Comfy Kitchen attention is unavailable";+/** The attention options: ComfyUI takes one at most. */+const ATTENTION = new Set([KITCHEN, "--use-sage-attention", "--use-flash-attention", "--use-pytorch-cross-attention"]);+/** Options with no value that worker.json's `comfyOptions` may give. */+const PLAIN_OPTIONS = new Set([...ATTENTION, "--disable-dynamic-vram"]);+/** The values `--fast` takes (none: all of them). */+const FAST_VALUES = new Set(["fp16_accumulation", "fp8_matrix_mult", "cublas_ops", "autotune"]);++/**+ * The extra options of its ComfyUI: worker.json's `comfyOptions` when it gives a list (`[]`: none), else Comfy Kitchen+ * attention where this ComfyUI has the flag. Only speed and memory options are taken: an attention option (one at+ * most), `--disable-dynamic-vram`, `--vram-headroom <GB>` and `--fast [values]`, each only if this ComfyUI names it.+ * Anything else (ports, folders, listening, custom nodes…) is left out, and said in `dropped`. The CPU slot's ComfyUI+ * (`cfg.cpuOnly`) gets none. `o.flags`: comfyFlags of this ComfyUI; `o.noKitchen`: leave Kitchen attention out.+ * @returns {{ options: string[]; dropped: string[] }}+ */+export function comfyOptions(cfg, o = {}) {+ if (cfg.cpuOnly) return { options: [], dropped: [] };+ const flags = o.flags ?? new Set();+ const given = (Array.isArray(cfg.comfyOptions) ? cfg.comfyOptions.map(String) : flags.has(KITCHEN) ? [KITCHEN] : []).filter((a) => !(o.noKitchen && a === KITCHEN));+ const options = [];+ const dropped = [];+ for (let i = 0; i < given.length; i++) {+ const [name, inline] = given[i].startsWith("--") && given[i].includes("=") ? [given[i].slice(0, given[i].indexOf("=")), given[i].slice(given[i].indexOf("=") + 1)] : [given[i], null];+ const known = flags.has(name) && !options.includes(name);+ if (PLAIN_OPTIONS.has(name) && inline === null) {+ if (known && !(ATTENTION.has(name) && options.some((x) => ATTENTION.has(x)))) options.push(name);+ else dropped.push(name);+ } else if (name === "--vram-headroom") {+ const value = inline ?? (given[i + 1]?.startsWith("--") ? undefined : given[i + 1]);+ if (inline === null && value !== undefined) i++;+ const gb = Number(value);+ if (known && value !== undefined && String(value).trim() !== "" && Number.isFinite(gb) && gb >= 0 && gb <= 1024) options.push(name, String(gb));+ else dropped.push(`${name} ${value ?? ""}`.trim());+ } else if (name === "--fast" && inline === null) {+ const values = [];+ while (i + 1 < given.length && !given[i + 1].startsWith("--")) values.push(given[++i]);+ if (known && values.every((v) => FAST_VALUES.has(v))) options.push(name, ...new Set(values));+ else dropped.push([name, ...values].join(" "));+ } else dropped.push(given[i]);+ }+ return { options, dropped };+}+/*** ComfyUI's start arguments (3.3): localhost only, its own folders, no metadata, no browser, only the packs it needs,* and no partner nodes where this ComfyUI has the flag. `o.port`: this start's port (else worker.json's). The CPU slot's- * ComfyUI (`cfg.cpuOnly`) runs on the CPU only, and never touches the GPU.+ * ComfyUI (`cfg.cpuOnly`) runs on the CPU only, and never touches the GPU. `o.options`: the extra options (else+ * comfyOptions with `o.flags` and `o.noKitchen`).*/export function comfyArgs(cfg, packs = [], o = {}) {const f = folders(cfg.workDir);@@ -150,6 +207,7 @@ export function comfyArgs(cfg, packs = [], o = {}) {"--disable-all-custom-nodes",...(packs.length ? ["--whitelist-custom-nodes", ...packs] : []),...(cfg.cpuOnly ? ["--cpu"] : []),+ ...(o.options ?? comfyOptions(cfg, o).options),];}@@ -315,6 +373,12 @@ export class OwnComfy {/** When it last answered anything (a ComfyUI that stops answering is stuck). */this.answeredAt = 0;this.log = null;+ /** Its ComfyUI couldn't load Comfy Kitchen attention: it starts without it for the rest of this run of the worker. */+ this.noKitchen = false;+ /** The options left out of worker.json's comfyOptions were said (once a run). */+ this.droppedSaid = false;+ /** The end of what its ComfyUI printed since this start. */+ this.tail = "";}/** This start's address (port 0, which nothing answers, while no ComfyUI of its own is up). */@@ -456,8 +520,14 @@ export class OwnComfy {this.key = crypto.randomBytes(32).toString("hex");let cmd;let marker;+ const { options, dropped } = comfyOptions(this.cfg, { flags: comfyFlags(this.cfg.comfyDir), noKitchen: this.noKitchen });+ if (dropped.length && !this.droppedSaid) {+ this.droppedSaid = true;+ this.o.log?.(`Left out of its ComfyUI's options (comfyOptions in worker.json takes only speed and memory options this ComfyUI knows): ${dropped.join(", ")}.`);+ }if (this.cfg.comfyCommand) {- cmd = this.cfg.comfyCommand.map((a) => String(a).replaceAll("{port}", String(this.port)));+ // A test's command: "{options}" stands for the extra options.+ cmd = this.cfg.comfyCommand.flatMap((a) => (a === "{options}" ? options : [String(a).replaceAll("{port}", String(this.port))]));marker = cmd.slice(1).find((a) => /[\\/]/.test(a)) ?? cmd.join(" ");}this.crashes = this.crashes.filter((c) => (this.o.now ?? Date.now)() - c.at < 3_600_000);@@ -472,7 +542,7 @@ export class OwnComfy {fs.rmSync(path.dirname(guard), { recursive: true, force: true });fs.mkdirSync(path.dirname(guard), { recursive: true });fs.copyFileSync(path.join(here, "comfy_guard.py"), guard);- cmd = [this.cfg.python || pythonFor(this.cfg.comfyDir), ...guardFlags(env), guard, path.join(this.cfg.comfyDir, "main.py"), ...comfyArgs(this.cfg, packs, { port: this.port, partnerFlag: partnerFlag(this.cfg.comfyDir) })];+ cmd = [this.cfg.python || pythonFor(this.cfg.comfyDir), ...guardFlags(env), guard, path.join(this.cfg.comfyDir, "main.py"), ...comfyArgs(this.cfg, packs, { port: this.port, partnerFlag: partnerFlag(this.cfg.comfyDir), options })];marker = guard;}// Its working folder is the worker folder: a node that writes a relative path writes there, not into ComfyUI's.@@ -482,8 +552,14 @@ export class OwnComfy {if (child.pid) fs.writeFileSync(this.pidFile, JSON.stringify({ pid: child.pid, port: this.port, marker, at: this.startedAt, worker: this.o.owner ?? null }), { mode: 0o600 });this.log?.close();const log = (this.log = new RotatingLog(path.join(this.cfg.workDir, "comfyui.log")));- child.stdout.on("data", (d) => log.write(d));- child.stderr.on("data", (d) => log.write(d));+ this.tail = "";+ const out = (d) => {+ log.write(d);+ this.tail = (this.tail + String(d)).slice(-16_384);+ };+ child.stdout.on("data", out);+ child.stderr.on("data", out);+ const closed = new Promise((r) => child.once("close", r));child.once("error", () => {});child.once("exit", (code) => {this.ready = false;@@ -500,7 +576,22 @@ export class OwnComfy {await this.stop();throw ended();}- if (!this.alive()) throw new Error("ComfyUI stopped while starting (see comfyui.log in the worker folder)");+ if (!this.alive()) {+ // It stopped because Comfy Kitchen attention can't load there: once, it starts again without it, and keeps it+ // out until the worker restarts. That stop counts as no crash.+ if (options.includes(KITCHEN) && !this.noKitchen) {+ await Promise.race([closed, new Promise((r) => setTimeout(r, 2_000))]);+ if (this.tail.includes(KITCHEN_MISSING)) {+ this.noKitchen = true;+ this.crashes = this.crashes.filter((c) => c.at < this.startedAt);+ this.inARow = Math.max(0, this.inARow - 1);+ fs.rmSync(this.pidFile, { force: true });+ this.o.log?.(`Its ComfyUI failed to start with Comfy Kitchen attention (${KITCHEN_MISSING} there, see comfyui.1.log): starting it again without it, until the worker restarts.`);+ return this.start(packs, o);+ }+ }+ throw new Error("ComfyUI stopped while starting (see comfyui.log in the worker folder)");+ }try {if (!proof) proof = await this.proven(child.pid);if (proof) {diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex d50bc3af..c80cc58e 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -209,6 +209,12 @@ The worker always starts and stops its own ComfyUI process. It never uses a Comfto `false` on every VideoHelperSuite save node (`VHS_VideoCombine`) of each graph before its ComfyUI gets it (elsethe node writes the graph and the PC's local time into each clip), and it takes the `<metadata>` element out of eachSVG result from ComfyUI's SVG save node before it keeps or sends the result;+- starts with Comfy Kitchen attention (`--use-ck-attention`) when that ComfyUI has the flag. To start it with other+ options, set `comfyOptions` in `worker.json` (for example `{ "comfyOptions": ["--use-sage-attention"] }`; `[]` for+ none). The worker takes only an attention option, `--disable-dynamic-vram`, `--vram-headroom <GB>` and+ `--fast [values]`, and leaves out anything else. If ComfyUI stops at its start because it can't load Kitchen+ attention, the worker starts it again once without it, keeps it out until the worker restarts, and says so in its+ log. The CPU slot's ComfyUI gets none of these options;- loads only the custom node packs that the worker found (`--disable-all-custom-nodes --whitelist-custom-nodes …`).The worker finds a pack whatever the case of its folder name, and gives ComfyUI the folder name as it is on disk;- gets only the environment variables that it needs: the system's own, `PATH`, the temp folder, the user foldersdiff --git a/tests/worker-comfy-options.test.ts b/tests/worker-comfy-options.test.tsnew file mode 100644index 00000000..fd901055--- /dev/null+++ b/tests/worker-comfy-options.test.ts@@ -0,0 +1,183 @@+/**+ * The extra options of a worker's own ComfyUI (bin/lib/worker/comfy.mjs comfyOptions): Comfy Kitchen attention by+ * default where that ComfyUI has the flag, worker.json's `comfyOptions` in its place (speed and memory options only),+ * none for the CPU slot, and one start again without Kitchen attention when ComfyUI can't load it.+ * Never a real ComfyUI, never a GPU.+ */+import fs from "node:fs";+import path from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { comfyArgs, comfyFlags, comfyOptions, GUARD, KITCHEN, KITCHEN_MISSING, OwnComfy } from "../bin/lib/worker/comfy.mjs";+import { tempDir } from "./helpers/temp-dir";++vi.setConfig({ testTimeout: 60_000 });++/** A ComfyUI folder whose comfy/cli_args.py names these flags. */+function comfyWith(flags: string[]): string {+ const dir = tempDir("fuobe-comfy-options-");+ fs.mkdirSync(path.join(dir, "comfy"));+ fs.writeFileSync(path.join(dir, "comfy", "cli_args.py"), flags.map((f) => `parser.add_argument("${f}", action="store_true")\n`).join(""));+ return dir;+}++const ALL = ["--use-ck-attention", "--use-sage-attention", "--use-flash-attention", "--use-pytorch-cross-attention", "--disable-dynamic-vram", "--vram-headroom", "--fast", "--listen", "--port", "--cpu"];++describe("its ComfyUI's extra options", () => {+ it("reads the flags this ComfyUI names, and none where it can't", () => {+ expect([...comfyFlags(comfyWith(["--use-ck-attention", "--fast"]))].sort()).toEqual(["--fast", "--use-ck-attention"]);+ expect(comfyFlags(tempDir("fuobe-comfy-none-")).size).toBe(0);+ expect(comfyFlags(undefined).size).toBe(0);+ });++ it("starts with Comfy Kitchen attention by default, where this ComfyUI has the flag", () => {+ const flags = comfyFlags(comfyWith(ALL));+ expect(comfyOptions({}, { flags })).toEqual({ options: [KITCHEN], dropped: [] });+ const args = comfyArgs({ workDir: "/w" }, [], { port: 41_000, flags });+ expect(args).toContain(KITCHEN);+ // An older ComfyUI without the flag starts as before.+ expect(comfyOptions({}, { flags: comfyFlags(comfyWith(["--use-sage-attention"])) })).toEqual({ options: [], dropped: [] });+ expect(comfyArgs({ workDir: "/w" }, [], { port: 41_000, flags: new Set() })).not.toContain(KITCHEN);+ expect(comfyArgs({ workDir: "/w" }, [], { port: 41_000 })).not.toContain(KITCHEN);+ });++ it("gives the CPU slot's ComfyUI no extra options", () => {+ const flags = comfyFlags(comfyWith(ALL));+ expect(comfyOptions({ cpuOnly: true }, { flags })).toEqual({ options: [], dropped: [] });+ expect(comfyOptions({ cpuOnly: true, comfyOptions: ["--use-sage-attention"] }, { flags })).toEqual({ options: [], dropped: [] });+ const args = comfyArgs({ workDir: "/w", cpuOnly: true }, [], { port: 41_000, flags });+ expect(args).toContain("--cpu");+ expect(args).not.toContain(KITCHEN);+ });++ it("takes worker.json's comfyOptions in place of the default, and [] for none", () => {+ const flags = comfyFlags(comfyWith(ALL));+ expect(comfyOptions({ comfyOptions: [] }, { flags })).toEqual({ options: [], dropped: [] });+ expect(comfyOptions({ comfyOptions: ["--use-sage-attention"] }, { flags }).options).toEqual(["--use-sage-attention"]);+ expect(comfyOptions({ comfyOptions: ["--use-ck-attention", "--disable-dynamic-vram", "--vram-headroom", "2.5"] }, { flags }).options).toEqual([+ "--use-ck-attention",+ "--disable-dynamic-vram",+ "--vram-headroom",+ "2.5",+ ]);+ expect(comfyOptions({ comfyOptions: ["--vram-headroom=3"] }, { flags }).options).toEqual(["--vram-headroom", "3"]);+ expect(comfyOptions({ comfyOptions: ["--vram-headroom", 1] }, { flags }).options).toEqual(["--vram-headroom", "1"]);+ expect(comfyOptions({ comfyOptions: ["--vram-headroom", "--use-ck-attention"] }, { flags })).toEqual({ options: ["--use-ck-attention"], dropped: ["--vram-headroom"] });+ expect(comfyOptions({ comfyOptions: ["--fast"] }, { flags }).options).toEqual(["--fast"]);+ expect(comfyOptions({ comfyOptions: ["--fast", "fp16_accumulation", "cublas_ops", "--use-flash-attention"] }, { flags }).options).toEqual([+ "--fast",+ "fp16_accumulation",+ "cublas_ops",+ "--use-flash-attention",+ ]);+ const args = comfyArgs({ workDir: "/w", comfyOptions: ["--use-pytorch-cross-attention"] }, [], { port: 41_000, flags });+ expect(args).toContain("--use-pytorch-cross-attention");+ expect(args).not.toContain(KITCHEN);+ });++ it("leaves out anything but speed and memory options, and options this ComfyUI doesn't know", () => {+ const flags = comfyFlags(comfyWith(ALL));+ const r = comfyOptions(+ {+ comfyOptions: [+ "--listen", "0.0.0.0", "--port", "8188", "--output-directory", "C:/elsewhere", "--enable-cors-header", "*",+ "--whitelist-custom-nodes", "evil", "--cpu", "--use-sage-attention", "--use-ck-attention", "--use-sage-attention",+ "--vram-headroom", "lots", "--fast", "everything", "--use-ck-attention=1", "--front-end-root",+ ],+ },+ { flags },+ );+ // One attention option at most (ComfyUI refuses two): the first one given.+ expect(r.options).toEqual(["--use-sage-attention"]);+ expect(r.dropped).toEqual([+ "--listen", "0.0.0.0", "--port", "8188", "--output-directory", "C:/elsewhere", "--enable-cors-header", "*",+ "--whitelist-custom-nodes", "evil", "--cpu", "--use-ck-attention", "--use-sage-attention",+ "--vram-headroom lots", "--fast everything", "--use-ck-attention=1", "--front-end-root",+ ]);+ // Flags this ComfyUI doesn't name would stop it at its start: left out too.+ expect(comfyOptions({ comfyOptions: ["--use-flash-attention", "--disable-dynamic-vram"] }, { flags: comfyFlags(comfyWith(["--disable-dynamic-vram"])) })).toEqual({+ options: ["--disable-dynamic-vram"],+ dropped: ["--use-flash-attention"],+ });+ // Not a list: the default.+ expect(comfyOptions({ comfyOptions: "--listen 0.0.0.0" }, { flags }).options).toEqual([KITCHEN]);+ });++ it("leaves Kitchen attention out once it couldn't load", () => {+ const flags = comfyFlags(comfyWith(ALL));+ expect(comfyOptions({}, { flags, noKitchen: true })).toEqual({ options: [], dropped: [] });+ expect(comfyOptions({ comfyOptions: [KITCHEN, "--disable-dynamic-vram"] }, { flags, noKitchen: true }).options).toEqual(["--disable-dynamic-vram"]);+ expect(comfyArgs({ workDir: "/w" }, [], { port: 41_000, flags, noKitchen: true })).not.toContain(KITCHEN);+ });+});++describe("a ComfyUI that can't load Comfy Kitchen attention", () => {+ const started: OwnComfy[] = [];+ afterEach(async () => {+ for (const c of started.splice(0)) await c.stop();+ });++ /**+ * A stand-in ComfyUI behind the worker's guard. Given Kitchen attention it says what ComfyUI says and exits (`kitchen`+ * "missing"), or exits with another message ("crash"); else it answers like a ComfyUI that started.+ */+ function standIn(dir: string, kitchen: "missing" | "crash") {+ const script = path.join(dir, "stand-in.mjs");+ fs.writeFileSync(+ script,+ `import http from "node:http"; import crypto from "node:crypto"; const key = process.env.${GUARD.env}; const port = Number(process.argv[2]);+if (process.argv.includes(${JSON.stringify(KITCHEN)})) {+ console.error(${JSON.stringify(kitchen === "missing" ? `${KITCHEN_MISSING}. Install a Comfy Kitchen build with attention support to use ${KITCHEN}.` : "Something else went wrong")});+ process.exit(255);+}+http.createServer((q, s) => {+ if (q.url.startsWith("${GUARD.hello}")) { s.writeHead(200, { "content-type": "application/json" });+ return s.end(JSON.stringify({ proof: crypto.createHmac("sha256", key).update(String(q.headers["${GUARD.challenge.toLowerCase()}"])).digest("hex"), pid: process.pid })); }+ if (q.headers["${GUARD.key.toLowerCase()}"] !== key) { s.writeHead(403); return s.end(); }+ s.writeHead(200, { "content-type": "application/json" }); s.end("{}");+}).listen(port, "127.0.0.1");`,+ );+ return [process.execPath, script, "{port}", "{options}"];+ }++ it("starts it again once without it, keeps it out for this run, says so, and counts no crash", async () => {+ const dir = comfyWith(ALL);+ const lines: string[] = [];+ const crashes: unknown[] = [];+ const c = new OwnComfy({ workDir: dir, comfyDir: dir, comfyCommand: standIn(dir, "missing"), comfyGuard: true }, { log: (l: string) => lines.push(l) });+ c.onCrash = (code: unknown) => crashes.push(code);+ started.push(c);+ await c.start();+ expect(c.ready).toBe(true);+ expect(c.noKitchen).toBe(true);+ expect(c.crashes).toEqual([]);+ expect(c.inARow).toBe(0);+ expect(lines.filter((l) => l.includes("Comfy Kitchen attention"))).toHaveLength(1);+ expect(lines.find((l) => l.includes("Comfy Kitchen attention"))).toMatch(/failed/);+ // The first try's output is in the log before this start's.+ expect(fs.readFileSync(path.join(dir, "comfyui.1.log"), "utf8")).toContain(KITCHEN_MISSING);+ // Its next start (after a stop) leaves it out too, with nothing said again.+ await c.stop();+ await c.start();+ expect(c.ready).toBe(true);+ expect(lines.filter((l) => l.includes("Comfy Kitchen attention"))).toHaveLength(1);+ expect(fs.readFileSync(path.join(dir, "comfyui.log"), "utf8")).not.toContain(KITCHEN_MISSING);+ });++ it("starts nothing again for another stop at its start", async () => {+ const dir = comfyWith(ALL);+ const c = new OwnComfy({ workDir: dir, comfyDir: dir, comfyCommand: standIn(dir, "crash"), comfyGuard: true });+ started.push(c);+ await expect(c.start()).rejects.toThrow(/stopped while starting/);+ expect(c.noKitchen).toBe(false);+ expect(c.crashes).toHaveLength(1);+ });++ it("never starts it with Kitchen attention where worker.json's comfyOptions leaves it out", async () => {+ const dir = comfyWith(ALL);+ const c = new OwnComfy({ workDir: dir, comfyDir: dir, comfyCommand: standIn(dir, "crash"), comfyGuard: true, comfyOptions: [] });+ started.push(c);+ await c.start();+ expect(c.ready).toBe(true);+ expect(c.noKitchen).toBe(false);+ });+});