Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(comfy): one picture or video model across two cards (C56)

purple54aca9b2d8b5
diff --git a/e2e/comfy-split-two-cards.spec.ts b/e2e/comfy-split-two-cards.spec.ts
new file mode 100644
index 00000000..25d2a50d
--- /dev/null
+++ b/e2e/comfy-split-two-cards.spec.ts
@@ -0,0 +1,165 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { seedOnboardingDone } from './support/cloud-mock'
+import { gradientPng } from './support/png'
+
+/**
+ * C56 (3.1.0), the_cave_dweller on Discord: RTX 4090 + RTX 5080, 64 GB RAM.
+ * "One big model across two cards", clicked through on simulated cards and a
+ * stand-in ComfyUI (Windows), no real two-card machine:
+ * (a) Settings → Hardware shows the toggle next to "Card per task", the
+ * default puts the model on the bigger card, and Rust gets the split.
+ * (b) Create with the split on and a ComfyUI that sees both cards: the graph
+ * posted to /prompt has ComfyUI's own Select CLIP/VAE Device nodes on
+ * gpu:1 behind the loaders, and every reader goes through them.
+ * (c) The same with a ComfyUI that still runs on one card: the graph goes
+ * out exactly as before.
+ * LU_SHOTS=<folder> writes the screenshots there.
+ */
+
+const MODEL = 'juggernautXL.safetensors'
+const SHOTS = process.env.LU_SHOTS
+const PNG = gradientPng(512, 384).toString('base64')
+
+const R5080 = { index: 0, vendor: 'nvidia', name: 'NVIDIA GeForce RTX 5080', memory_mib: 16303, source: 'nvidia-smi' }
+const R4090 = { index: 1, vendor: 'nvidia', name: 'NVIDIA GeForce RTX 4090', memory_mib: 24564, source: 'nvidia-smi' }
+/** ComfyUI v0.42.4 /system_stats with LU's split: model card first. */
+const TWO = [
+ { name: 'cuda:0 NVIDIA GeForce RTX 4090 : cudaMallocAsync', type: 'cuda', index: 0, vram_total: 25757220864 },
+ { name: 'cuda:1 NVIDIA GeForce RTX 5080 : cudaMallocAsync', type: 'cuda', index: 1, vram_total: 17094475776 },
+]
+const ONE = [TWO[0]]
+
+type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>
+
+async function boot(page: Page, devices: unknown[]) {
+ await page.addInitScript(tauriMockInit, { assistantReply: 'ok', modelName: DEFAULT_MODEL_NAME, platform: 'windows' as const })
+ await seedOnboardingDone(page)
+ await page.addInitScript(([model, cards, devs]) => {
+ const w = window as unknown as { __PROMPTS__: string[]; __ROLES__: unknown[]; __TAURI_INTERNALS__: { invoke: (c: string, a: { url?: string; method?: string; body?: string; roles?: unknown }) => Promise<unknown> } }
+ if (!localStorage.getItem('create-store')) {
+ localStorage.setItem('create-store', JSON.stringify({ state: { backend: 'local', imageModel: model }, version: 2 }))
+ }
+ w.__PROMPTS__ = []
+ w.__ROLES__ = []
+ const bridge = w.__TAURI_INTERNALS__
+ const invoke = bridge.invoke
+ const combo = (v: string[]) => [v]
+ // Outputs as ComfyUI v0.42.4 declares them: the split reads them.
+ const nodes: Record<string, unknown> = {
+ CheckpointLoaderSimple: { input: { required: { ckpt_name: combo([model as string]) } }, output: ['MODEL', 'CLIP', 'VAE'] },
+ VAELoader: { input: { required: { vae_name: combo(['sdxl_vae.safetensors']) } }, output: ['VAE'] },
+ KSampler: { input: { required: { sampler_name: combo(['euler']), scheduler: combo(['simple']) } }, output: ['LATENT'] },
+ EmptyLatentImage: { input: { required: {} }, output: ['LATENT'] },
+ CLIPTextEncode: { input: { required: {} }, output: ['CONDITIONING'] },
+ VAEDecode: { input: { required: {} }, output: ['IMAGE'] },
+ SaveImage: { input: { required: {} }, output: [] },
+ SelectCLIPDevice: { input: { required: { clip: ['CLIP'], device: [['default', 'cpu', 'gpu:0', 'gpu:1']] } }, output: ['CLIP'] },
+ SelectVAEDevice: { input: { required: { vae: ['VAE'], device: [['default', 'gpu:0', 'gpu:1']] } }, output: ['VAE'] },
+ }
+ bridge.invoke = (command, args) => {
+ if (command === 'detect_gpus') return Promise.resolve(cards)
+ if (command === 'set_gpu_roles') { w.__ROLES__.push(args?.roles); return Promise.resolve(null) }
+ if (command === 'describe_gpu_roles') return Promise.resolve([])
+ if (command === 'sniff_model_files') return Promise.resolve([])
+ if (command !== 'proxy_localhost' || !args?.url?.includes(':8188')) return invoke(command, args)
+ const url = args.url
+ if (url.includes('/system_stats')) return Promise.resolve(JSON.stringify({ system: { comfyui_version: '0.42.4' }, devices: devs }))
+ if (url.endsWith('/prompt') && args.method === 'POST') {
+ w.__PROMPTS__.push(String(args.body))
+ return Promise.resolve(JSON.stringify({ prompt_id: `p${w.__PROMPTS__.length}`, number: 1, node_errors: {} }))
+ }
+ const hist = /\/history\/(p(\d+))/.exec(url)
+ if (hist) {
+ return Promise.resolve(JSON.stringify({ [hist[1]]: { status: { status_str: 'success', completed: true, messages: [] }, outputs: { '9': { images: [{ filename: `split_${hist[1]}.png`, subfolder: '', type: 'output' }] } } } }))
+ }
+ if (url.includes('/queue')) return Promise.resolve(JSON.stringify({ queue_running: [], queue_pending: [] }))
+ const one = /\/object_info\/([^/?]+)/.exec(url)
+ if (one) return Promise.resolve(JSON.stringify(one[1] in nodes ? { [one[1]]: nodes[one[1]] } : {}))
+ if (url.includes('/object_info')) return Promise.resolve(JSON.stringify(nodes))
+ return Promise.resolve('{}')
+ }
+ }, [MODEL, [R5080, R4090], devices] as const)
+ await page.route(/:8188\/view/, (route) => route.fulfill({ status: 200, contentType: 'image/png', body: Buffer.from(PNG, 'base64') }))
+}
+
+const shot = async (page: Page, name: string) => {
+ if (!SHOTS) return
+ await page.waitForTimeout(400)
+ await page.screenshot({ path: `${SHOTS}/${name}.png` })
+}
+
+const posted = (page: Page) => page.evaluate(() => (window as unknown as { __PROMPTS__: string[] }).__PROMPTS__.map((p) => (JSON.parse(p) as { prompt: Graph }).prompt))
+
+/** Settings → Hardware → the toggle, as a user turns it on. Persisted, so
+ * the next page load keeps it. */
+async function turnOnSplit(page: Page) {
+ await page.goto('/')
+ await page.getByRole('banner').getByRole('button', { name: 'Settings' }).click()
+ await page.getByRole('button', { name: 'Hardware (GPU picker)' }).click()
+ const toggle = page.getByLabel('One big model across two cards')
+ await expect(toggle).toBeVisible({ timeout: 15_000 })
+ return toggle
+}
+
+/** `stay`: go to Create inside the running app. A page load would undo the
+ * setting, because seedOnboardingDone writes the settings on every load. */
+async function createOnePicture(page: Page, stay = false) {
+ if (!stay) await page.goto('/')
+ await page.getByRole('button', { name: /^Create$/ }).click()
+ await page.getByRole('radio', { name: 'Image', exact: true }).click()
+ await page.getByRole('textbox').filter({ hasText: '' }).first().fill('a lighthouse at dusk')
+ await page.getByRole('button', { name: /^Create$/ }).last().click()
+ await expect.poll(async () => (await posted(page)).length, { timeout: 20_000 }).toBe(1)
+ return (await posted(page))[0]
+}
+
+test('(a) Settings → Hardware: the toggle, the bigger card for the model, Rust gets the split', async ({ page }) => {
+ await boot(page, TWO)
+ const toggle = await turnOnSplit(page)
+ await toggle.scrollIntoViewIfNeeded()
+ await shot(page, 'c56-1-hardware-aus')
+ await toggle.check()
+ await expect(page.getByLabel('Model on')).toHaveValue('nvidia:1')
+ await expect(page.getByLabel('Text encoder and VAE on')).toHaveValue('nvidia:0')
+ await expect(page.getByLabel('Pictures and video (ComfyUI)')).toBeDisabled()
+ await expect(page.getByTestId('gpu-roles-restart-hint')).toBeVisible()
+ await page.getByTestId('comfy-split').scrollIntoViewIfNeeded()
+ await shot(page, 'c56-2-hardware-an')
+ await expect.poll(() => page.evaluate(() => {
+ const roles = (window as unknown as { __ROLES__: Array<{ comfySplit?: { model: { index: number }; helper: { index: number } } }> }).__ROLES__
+ const last = roles[roles.length - 1]
+ return last?.comfySplit ? [last.comfySplit.model.index, last.comfySplit.helper.index] : null
+ })).toEqual([1, 0])
+})
+
+test('(b) Create with the split on and ComfyUI on both cards: text encoder and VAE go to gpu:1', async ({ page }) => {
+ await boot(page, TWO)
+ await (await turnOnSplit(page)).check()
+ const graph = await createOnePicture(page, true)
+ const selects = Object.entries(graph).filter(([, n]) => n.class_type === 'SelectCLIPDevice' || n.class_type === 'SelectVAEDevice')
+ expect(selects.map(([, n]) => n.class_type).sort()).toEqual(['SelectCLIPDevice', 'SelectVAEDevice'])
+ for (const [, n] of selects) expect(n.inputs.device).toBe('gpu:1')
+ const clipNode = selects.find(([, n]) => n.class_type === 'SelectCLIPDevice')![0]
+ const vaeNode = selects.find(([, n]) => n.class_type === 'SelectVAEDevice')![0]
+ for (const n of Object.values(graph)) {
+ if (n.class_type === 'CLIPTextEncode') expect((n.inputs.clip as [string, number])[0]).toBe(clipNode)
+ if (n.class_type === 'VAEDecode') expect((n.inputs.vae as [string, number])[0]).toBe(vaeNode)
+ // The diffusion model stays on ComfyUI's default card.
+ if (n.class_type === 'KSampler') expect(graph[(n.inputs.model as [string, number])[0]].class_type).not.toMatch(/^Select/)
+ }
+ await shot(page, 'c56-3-create-mit-split')
+})
+
+test('(c) the split on but ComfyUI still on one card: the graph goes out as before', async ({ page }) => {
+ await boot(page, ONE)
+ await (await turnOnSplit(page)).check()
+ const graph = await createOnePicture(page, true)
+ expect(Object.values(graph).some((n) => n.class_type.startsWith('Select'))).toBe(false)
+})
+
+test('(d) the split off: the graph goes out as before', async ({ page }) => {
+ await boot(page, TWO)
+ const graph = await createOnePicture(page)
+ expect(Object.values(graph).some((n) => n.class_type.startsWith('Select'))).toBe(false)
+})
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index 98dda990..27cc2dab 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -5779,7 +5779,9 @@ fn describe_gpu_roles_blocking(app: &AppHandle, state: &AppState) -> Result<Vec<
use crate::commands::gpu_roles::{effective_selection, env_of, GpuRole, RolePlan};
let mut out = Vec::new();
let comfy = effective_selection(state, GpuRole::Comfy).unwrap_or_default();
- out.push(RolePlan { service: "ComfyUI".into(), env: env_of(&comfy), args: vec![], note: None });
+ // C56: with the split on, say which card holds which part.
+ let comfy_note = crate::commands::gpu_roles::comfy_split(state).map(|s| crate::commands::gpu_roles::split_note(&s));
+ out.push(RolePlan { service: "ComfyUI".into(), env: env_of(&comfy), args: vec![], note: comfy_note });
let chat = effective_selection(state, GpuRole::Chat).unwrap_or_default();
out.push(RolePlan {
service: "Ollama".into(),
diff --git a/src-tauri/src/commands/gpu_roles.rs b/src-tauri/src/commands/gpu_roles.rs
index f3f21302..b97bf008 100644
--- a/src-tauri/src/commands/gpu_roles.rs
+++ b/src-tauri/src/commands/gpu_roles.rs
@@ -52,6 +52,39 @@ pub struct GpuRoles {
pub chat: Option<GpuRef>,
#[serde(default)]
pub comfy: Option<GpuRef>,
+ /// 3.1.0 (C56): one picture or video model across two cards. Set, it
+ /// wins over `comfy` for ComfyUI: ComfyUI sees both cards, `model` first.
+ #[serde(default, rename = "comfySplit", alias = "comfy_split")]
+ pub comfy_split: Option<ComfySplit>,
+}
+
+/// One ComfyUI over two cards (3.1.0, C56).
+///
+/// ComfyUI gets both cards, `model` first, so torch calls it `cuda:0` and
+/// ComfyUI's own default device: the diffusion model and the sampling stay
+/// there. `helper` becomes `cuda:1`, which ComfyUI's own nodes call `gpu:1`;
+/// the app puts ComfyUI's core nodes "Select CLIP Device" and "Select VAE
+/// Device" (comfy_extras/nodes_multigpu.py, in ComfyUI since 0.42) with
+/// `gpu:1` behind every text encoder and VAE loader of a workflow
+/// (src/lib/comfy-split.ts). No custom node, no foreign code.
+///
+/// NVIDIA only: the order of two cards is pinned by their UUIDs in
+/// CUDA_VISIBLE_DEVICES, which nothing guarantees for HIP or oneAPI, and on
+/// Windows ComfyUI forces a single card unless CUDA_VISIBLE_DEVICES is set
+/// (main.py), which this sets.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ComfySplit {
+ /// The diffusion model and the sampling.
+ pub model: GpuRef,
+ /// The text encoder and the VAE.
+ pub helper: GpuRef,
+}
+
+impl ComfySplit {
+ /// Two different NVIDIA cards; anything else is no split.
+ pub fn usable(&self) -> bool {
+ self.model.vendor == "nvidia" && self.helper.vendor == "nvidia" && self.model.index != self.helper.index
+ }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -74,11 +107,23 @@ impl GpuRoles {
};
r.filter(|r| known_vendor(&r.vendor))
}
+
+ /// The split, when it can be applied.
+ pub fn split(&self) -> Option<&ComfySplit> {
+ self.comfy_split.as_ref().filter(|s| s.usable())
+ }
}
/// What a service is started with: its role's card when one is set, the
/// global pick otherwise. Pure, so the whole matrix is a unit test.
pub fn selection_for_role(role: GpuRole, global: &GpuSelection, roles: &GpuRoles) -> GpuSelection {
+ // C56: the split gives ComfyUI both cards, the model card first. The
+ // order is the point: it is what makes the model card `cuda:0`.
+ if role == GpuRole::Comfy {
+ if let Some(split) = roles.split() {
+ return GpuSelection { vendor: "nvidia".into(), indices: vec![split.model.index, split.helper.index] };
+ }
+ }
match roles.get(role) {
Some(card) => GpuSelection { vendor: card.vendor.clone(), indices: vec![card.index] },
None => global.clone(),
@@ -94,6 +139,19 @@ pub fn effective_selection(state: &AppState, role: GpuRole) -> Option<GpuSelecti
Some(selection_for_role(role, &global, &roles))
}
+/// The split, when one is set and usable.
+pub fn comfy_split(state: &AppState) -> Option<ComfySplit> {
+ state.gpu_roles.lock().ok().and_then(|r| r.split().cloned())
+}
+
+/// The ComfyUI line of the readout when the split is on, in words.
+pub fn split_note(split: &ComfySplit) -> String {
+ format!(
+ "One model across two cards: the diffusion model on #{} {}, text encoders and VAE on #{} {} (ComfyUI calls it gpu:1).",
+ split.model.index, split.model.name, split.helper.index, split.helper.name
+ )
+}
+
/// The chat role's card, when one is set.
pub fn chat_card(state: &AppState) -> Option<GpuRef> {
state.gpu_roles.lock().ok().and_then(|r| r.get(GpuRole::Chat).cloned())
@@ -393,25 +451,97 @@ Available devices:
#[test]
fn each_service_gets_its_own_card() {
let global = GpuSelection::default();
- let roles = GpuRoles { chat: Some(card(0, "A")), comfy: Some(card(1, "B")) };
+ let roles = GpuRoles { chat: Some(card(0, "A")), comfy: Some(card(1, "B")), ..Default::default() };
assert_eq!(selection_for_role(GpuRole::Chat, &global, &roles).indices, vec![0]);
assert_eq!(selection_for_role(GpuRole::Comfy, &global, &roles).indices, vec![1]);
// One role set: the other service keeps the global pick.
- let only_comfy = GpuRoles { chat: None, comfy: Some(card(1, "B")) };
+ let only_comfy = GpuRoles { chat: None, comfy: Some(card(1, "B")), ..Default::default() };
assert_eq!(selection_for_role(GpuRole::Chat, &global, &only_comfy).vendor, "auto");
assert_eq!(selection_for_role(GpuRole::Comfy, &global, &only_comfy).indices, vec![1]);
}
+ fn split(model: u32, helper: u32) -> Option<ComfySplit> {
+ Some(ComfySplit { model: card(model, "RTX 4090"), helper: card(helper, "RTX 5080") })
+ }
+
+ /// C56: the 4090 + 5080 machine from Discord, simulated. ComfyUI gets
+ /// both UUIDs, the model card FIRST, whatever the bus order says.
+ #[test]
+ fn the_split_gives_comfyui_both_cards_model_card_first() {
+ let global = GpuSelection::default();
+ let roles = GpuRoles { comfy_split: split(1, 0), ..Default::default() };
+ let s = selection_for_role(GpuRole::Comfy, &global, &roles);
+ assert_eq!((s.vendor.as_str(), s.indices.as_slice()), ("nvidia", [1u32, 0].as_slice()));
+ // The chat is not touched by the split.
+ assert_eq!(selection_for_role(GpuRole::Chat, &global, &roles).vendor, "auto");
+ }
+
+ #[test]
+ fn the_split_wins_over_the_comfy_card_and_leaves_the_chat_card() {
+ let global = GpuSelection::default();
+ let roles = GpuRoles { chat: Some(card(2, "C")), comfy: Some(card(1, "B")), comfy_split: split(0, 1) };
+ assert_eq!(selection_for_role(GpuRole::Comfy, &global, &roles).indices, vec![0, 1]);
+ assert_eq!(selection_for_role(GpuRole::Chat, &global, &roles).indices, vec![2]);
+ }
+
+ #[test]
+ fn a_split_that_cannot_work_changes_nothing() {
+ let global = GpuSelection { vendor: "nvidia".into(), indices: vec![0] };
+ // The same card twice.
+ let same = GpuRoles { comfy_split: split(0, 0), ..Default::default() };
+ assert_eq!(selection_for_role(GpuRole::Comfy, &global, &same).indices, vec![0]);
+ // Not NVIDIA.
+ let amd = GpuRoles {
+ comfy_split: Some(ComfySplit {
+ model: GpuRef { vendor: "amd".into(), index: 0, name: "RX".into() },
+ helper: GpuRef { vendor: "amd".into(), index: 1, name: "RX".into() },
+ }),
+ comfy: Some(GpuRef { vendor: "amd".into(), index: 1, name: "RX".into() }),
+ ..Default::default()
+ };
+ let s = selection_for_role(GpuRole::Comfy, &global, &amd);
+ assert_eq!((s.vendor.as_str(), s.indices.as_slice()), ("amd", [1u32].as_slice()), "the comfy card applies as before");
+ }
+
+ #[test]
+ fn the_split_env_pins_the_order_without_an_nvidia_smi() {
+ // No nvidia-smi on this test machine: the fallback is the bare
+ // indices in the given order, plus the bus order net.
+ let roles = GpuRoles { comfy_split: split(1, 0), ..Default::default() };
+ let env = env_of(&selection_for_role(GpuRole::Comfy, &GpuSelection::default(), &roles));
+ assert!(env.contains(&"CUDA_DEVICE_ORDER=PCI_BUS_ID".to_string()), "{env:?}");
+ let cvd = env.iter().find(|e| e.starts_with("CUDA_VISIBLE_DEVICES=")).expect("CUDA_VISIBLE_DEVICES");
+ let value = cvd.trim_start_matches("CUDA_VISIBLE_DEVICES=");
+ let parts: Vec<&str> = value.split(',').collect();
+ assert_eq!(parts.len(), 2, "{value}");
+ if !parts[0].starts_with("GPU-") {
+ assert_eq!(parts, ["1", "0"]);
+ }
+ }
+
+ #[test]
+ fn the_split_from_the_frontend_deserializes() {
+ let r: GpuRoles = serde_json::from_str(
+ r#"{"chat":null,"comfy":null,"comfySplit":{"model":{"vendor":"nvidia","index":0,"name":"RTX 4090"},"helper":{"vendor":"nvidia","index":1,"name":"RTX 5080"}}}"#,
+ )
+ .unwrap();
+ assert_eq!(r.split().map(|s| (s.model.index, s.helper.index)), Some((0, 1)));
+ // A roles value from 3.0.8 has no split at all.
+ let old: GpuRoles = serde_json::from_str(r#"{"chat":null,"comfy":{"vendor":"nvidia","index":1}}"#).unwrap();
+ assert_eq!(old.comfy_split, None);
+ assert!(split_note(r.split().unwrap()).contains("gpu:1"));
+ }
+
#[test]
fn a_role_with_an_unknown_vendor_is_ignored() {
let global = GpuSelection { vendor: "amd".into(), indices: vec![0] };
- let roles = GpuRoles { chat: Some(GpuRef { vendor: "apple".into(), index: 0, name: "M3".into() }), comfy: None };
+ let roles = GpuRoles { chat: Some(GpuRef { vendor: "apple".into(), index: 0, name: "M3".into() }), comfy: None, ..Default::default() };
assert_eq!(selection_for_role(GpuRole::Chat, &global, &roles).vendor, "amd");
}
#[test]
fn an_amd_role_is_forwarded_as_hip() {
- let roles = GpuRoles { chat: None, comfy: Some(GpuRef { vendor: "amd".into(), index: 1, name: "RX".into() }) };
+ let roles = GpuRoles { chat: None, comfy: Some(GpuRef { vendor: "amd".into(), index: 1, name: "RX".into() }), ..Default::default() };
let env = env_of(&selection_for_role(GpuRole::Comfy, &GpuSelection::default(), &roles));
assert!(env.contains(&"HIP_VISIBLE_DEVICES=1".to_string()), "{env:?}");
assert!(env.contains(&"ROCR_VISIBLE_DEVICES=1".to_string()), "{env:?}");
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index e511e841..27776e91 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -2286,7 +2286,14 @@ pub(crate) fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Val
// 3.0.8 (A2): the ComfyUI role's card when one is set, the global pick
// otherwise. With a role set, ComfyUI sees that one card only, so a video
// can never spill onto the chat's card.
+ // 3.1.0 (C56): with "One model across two cards" ComfyUI sees both
+ // cards, the model card first (gpu_roles.rs, ComfySplit).
let gpu_selection = crate::commands::gpu_roles::effective_selection(state, crate::commands::gpu_roles::GpuRole::Comfy);
+ if let Some(split) = crate::commands::gpu_roles::comfy_split(state) {
+ let line = format!("[start] {}", crate::commands::gpu_roles::split_note(&split));
+ println!("[ComfyUI] {line}");
+ info!(model = split.model.index, helper = split.helper.index, "comfyui split over two cards");
+ }
if let Some(sel) = gpu_selection {
crate::commands::gpu::apply_gpu_env(&mut cmd, &sel);
}
diff --git a/src/api/comfy-split.ts b/src/api/comfy-split.ts
new file mode 100644
index 00000000..4651abfe
--- /dev/null
+++ b/src/api/comfy-split.ts
@@ -0,0 +1,64 @@
+/**
+ * The live half of "One model across two cards" (3.1.0, C56): decide per
+ * submit whether the running ComfyUI can take the split, and apply it. The
+ * graph surgery itself is pure and lives in lib/comfy-split.ts.
+ *
+ * Nothing here may stop a render. Every failure, a missing node, a ComfyUI
+ * that sees one card, an unreachable /system_stats, ends in "send the
+ * workflow as it is", which is exactly what LU did before 3.1.0.
+ */
+
+import { comfyuiUrl, localFetch } from './backend'
+import { log } from '../lib/logger'
+import { useSettingsStore } from '../stores/settingsStore'
+import { comfySplitOf } from '../lib/gpu-roles'
+import {
+ splitAcrossCards,
+ comfySeesSplit,
+ SELECT_CLIP_DEVICE,
+ SELECT_VAE_DEVICE,
+ SPLIT_HELPER_DEVICE,
+} from '../lib/comfy-split'
+import type { ComfyApiGraph } from '../types/comfy-graph'
+
+const STATS_TIMEOUT_MS = 5_000
+
+/** The workflow with the split applied when it is on and the running
+ * ComfyUI can do it; otherwise the workflow unchanged. */
+export async function withComfySplit(workflow: ComfyApiGraph): Promise<ComfyApiGraph> {
+ let split
+ try {
+ split = comfySplitOf(useSettingsStore.getState().settings.gpuRoles)
+ } catch {
+ return workflow
+ }
+ if (!split) return workflow
+ try {
+ const res = await localFetch(comfyuiUrl('/system_stats'), { timeoutMs: STATS_TIMEOUT_MS })
+ if (!res.ok) return workflow
+ const stats = await res.json()
+ if (!comfySeesSplit(stats?.devices, split.model.name, split.helper.name)) {
+ log.warn('comfyui.split_skipped', {
+ reason: 'ComfyUI does not see the two cards in split order; restart ComfyUI to apply the setting',
+ devices: Array.isArray(stats?.devices) ? stats.devices.map((d: { name?: unknown }) => String(d?.name ?? '')) : [],
+ })
+ return workflow
+ }
+ const { getAllNodeInfo } = await import('./comfyui-nodes')
+ const info = await getAllNodeInfo()
+ const clip = SELECT_CLIP_DEVICE in info
+ const vae = SELECT_VAE_DEVICE in info
+ if (!clip && !vae) {
+ log.info('comfyui.split_skipped', { reason: 'this ComfyUI has no Select CLIP/VAE Device node (needs 0.23 or newer)' })
+ return workflow
+ }
+ const out = splitAcrossCards(workflow, (cls) => info[cls]?.output, { clip, vae, device: SPLIT_HELPER_DEVICE })
+ if (out.inserted.length > 0) {
+ log.info('comfyui.split_applied', { device: SPLIT_HELPER_DEVICE, inserted: out.inserted })
+ }
+ return out.graph
+ } catch (e) {
+ log.warn('comfyui.split_skipped', { reason: String(e) })
+ return workflow
+ }
+}
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index 7d2901dd..f4f76abf 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -2260,8 +2260,13 @@ export async function submitWorkflow(
clientId?: string,
opts: { previewMethod?: 'auto' | 'latent2rgb' | 'taesd' } = {},
): Promise<string> {
+ // 3.1.0 (C56): with "One model across two cards" on and a ComfyUI that
+ // sees both cards, the text encoders and the VAE go to the second card.
+ // Off, or anything missing: the workflow goes out unchanged.
+ const { withComfySplit } = await import('./comfy-split')
+ const placed = await withComfySplit(workflow)
// Every run its own output names (comfyui-graph tagOutputPrefixes).
- const payload: Record<string, unknown> = { prompt: tagOutputPrefixes(workflow, newRunTag()) }
+ const payload: Record<string, unknown> = { prompt: tagOutputPrefixes(placed, newRunTag()) }
if (clientId) payload.client_id = clientId
// B28: live previews for this prompt only. ComfyUI starts with previews off
// (--preview-method none) and takes a per-prompt override in extra_data
@@ -2293,7 +2298,7 @@ export async function submitWorkflow(
} catch {
if (rawText) errMsg = rawText.slice(0, 500)
}
- log.error('comfyui.workflow_rejected', { errMsg, workflow: JSON.stringify(workflow).slice(0, 2000) })
+ log.error('comfyui.workflow_rejected', { errMsg, workflow: JSON.stringify(placed).slice(0, 2000) })
throw new Error(`ComfyUI rejected workflow: ${errMsg}`)
}
const data: unknown = await res.json()
@@ -2308,7 +2313,7 @@ export async function submitWorkflow(
if (isRecord(nodeErrors) && Object.keys(nodeErrors).length > 0) {
if (promptId) await abandonPrompt(promptId)
const errMsg = describeComfyRejection(data) ?? 'some output nodes failed validation'
- log.error('comfyui.workflow_rejected', { errMsg, partial: true, workflow: JSON.stringify(workflow).slice(0, 2000) })
+ log.error('comfyui.workflow_rejected', { errMsg, partial: true, workflow: JSON.stringify(placed).slice(0, 2000) })
throw new Error(`ComfyUI rejected workflow: ${errMsg}`)
}
if (!promptId) throw new Error('ComfyUI accepted the workflow but returned no prompt_id.')
diff --git a/src/components/settings/GpuRolesPicker.tsx b/src/components/settings/GpuRolesPicker.tsx
index 7d1fa337..a7b1d52e 100644
--- a/src/components/settings/GpuRolesPicker.tsx
+++ b/src/components/settings/GpuRolesPicker.tsx
@@ -6,8 +6,8 @@
import { useEffect, useMemo, useState } from 'react'
import { useSettingsStore } from '../../stores/settingsStore'
import { backendCall, isTauri } from '../../api/backend'
-import { normalizeGpuRoles, gpuRolesSeparate, sameCard } from '../../lib/gpu-roles'
-import type { GpuRef, GpuRoles } from '../../types/settings'
+import { normalizeGpuRoles, gpuRolesSeparate, sameCard, comfySplitOf, comfyCards } from '../../lib/gpu-roles'
+import type { ComfySplit, GpuRef } from '../../types/settings'
import { Hinweis } from '../ui/Hinweis'
import { HINWEIS_TEXT } from '../../lib/hinweis'
import { formatBytes } from '../../lib/formatters'
@@ -33,6 +33,29 @@ export function roleCards(gpus: RoleCard[]): RoleCard[] {
return gpus.filter((g) => PICKABLE.has(g.vendor))
}
+/** The cards the split can use: NVIDIA only (gpu_roles.rs, ComfySplit). */
+export function splitCards(gpus: RoleCard[]): RoleCard[] {
+ return gpus.filter((g) => g.vendor === 'nvidia')
+}
+
+function refOf(g: RoleCard): GpuRef {
+ return { vendor: g.vendor as GpuRef['vendor'], index: g.index, name: g.name }
+}
+
+/**
+ * The split a fresh tick starts with: the model on the ComfyUI card when
+ * one is picked, else on the card with the most memory; the text encoders and
+ * the VAE on the biggest of the others.
+ */
+export function defaultSplit(cards: RoleCard[], comfy: GpuRef | null): ComfySplit | null {
+ const nv = splitCards(cards)
+ if (nv.length < 2) return null
+ const bySize = [...nv].sort((a, b) => (b.memory_mib ?? 0) - (a.memory_mib ?? 0) || a.index - b.index)
+ const model = (comfy && nv.find((g) => sameCard(refOf(g), comfy))) || bySize[0]
+ const helper = bySize.find((g) => g.index !== model.index)!
+ return { model: refOf(model), helper: refOf(helper) }
+}
+
function keyOf(r: GpuRef | null): string {
return r ? `${r.vendor}:${r.index}` : ''
}
@@ -67,21 +90,45 @@ export function GpuRolesPicker({ gpus }: { gpus: RoleCard[] }) {
if (cards.length < 2) return null
- const pick = (role: keyof GpuRoles, key: string) => {
+ const split = comfySplitOf(roles)
+ const nvCards = splitCards(cards)
+
+ const pick = (role: 'chat' | 'comfy', key: string) => {
const card = cards.find((g) => `${g.vendor}:${g.index}` === key)
- const ref: GpuRef | null = card ? { vendor: card.vendor as GpuRef['vendor'], index: card.index, name: card.name } : null
+ const ref: GpuRef | null = card ? refOf(card) : null
updateSettings({ gpuRoles: { ...roles, [role]: ref } })
setChanged(true)
}
- const select = (role: keyof GpuRoles, title: string, help: string) => (
+ const setSplit = (next: ComfySplit | null) => {
+ const { comfySplit: _old, ...rest } = roles
+ void _old
+ updateSettings({ gpuRoles: next ? { ...rest, comfySplit: next } : rest })
+ setChanged(true)
+ }
+
+ const pickSplit = (part: 'model' | 'helper', key: string) => {
+ if (!split) return
+ const card = nvCards.find((g) => `${g.vendor}:${g.index}` === key)
+ if (!card) return
+ const other = part === 'model' ? 'helper' : 'model'
+ const next: ComfySplit = { ...split, [part]: refOf(card) }
+ // Picking the other part's card swaps the two, so they never coincide.
+ if (sameCard(next[part], next[other])) next[other] = split[part]
+ setSplit(next)
+ }
+
+ const selectClass = 'mt-0.5 w-full rounded border border-gray-300 dark:border-white/10 bg-white dark:bg-white/[0.03] px-1.5 py-1 t-micro text-gray-800 dark:text-gray-200 disabled:opacity-50'
+
+ const select = (role: 'chat' | 'comfy', title: string, help: string, disabled = false) => (
<label className="block">
<span className="t-micro text-gray-700 dark:text-gray-300">{title}</span>
<select
value={keyOf(roles[role])}
onChange={(e) => pick(role, e.target.value)}
aria-label={title}
- className="mt-0.5 w-full rounded border border-gray-300 dark:border-white/10 bg-white dark:bg-white/[0.03] px-1.5 py-1 t-micro text-gray-800 dark:text-gray-200"
+ disabled={disabled}
+ className={selectClass}
>
<option value="">Same as above</option>
{cards.map((g) => (
@@ -92,7 +139,7 @@ export function GpuRolesPicker({ gpus }: { gpus: RoleCard[] }) {
</label>
)
- const shared = !!roles.chat && !!roles.comfy && sameCard(roles.chat, roles.comfy)
+ const shared = !!roles.chat && comfyCards(roles).some((c) => sameCard(roles.chat, c))
return (
<div className="pt-2 border-t border-white/[0.06] space-y-2" data-testid="gpu-roles">
@@ -103,7 +150,53 @@ export function GpuRolesPicker({ gpus }: { gpus: RoleCard[] }) {
</div>
</div>
{select('chat', 'Chat (LU Engine, Ollama)', 'The chat model loads onto this card only.')}
- {select('comfy', 'Pictures and video (ComfyUI)', 'ComfyUI sees this card only.')}
+ {select(
+ 'comfy',
+ 'Pictures and video (ComfyUI)',
+ split ? 'ComfyUI uses both cards below, so this pick waits until the split is off.' : 'ComfyUI sees this card only.',
+ !!split,
+ )}
+ {nvCards.length >= 2 && (
+ <div className="space-y-1.5" data-testid="comfy-split">
+ <label className="flex items-start gap-1.5 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={!!split}
+ onChange={(e) => setSplit(e.target.checked ? defaultSplit(nvCards, roles.comfy) : null)}
+ aria-label="One big model across two cards"
+ className="mt-0.5"
+ />
+ <span>
+ <span className="block t-micro text-gray-700 dark:text-gray-300">One big model across two cards</span>
+ <span className="block t-micro text-gray-500 leading-relaxed">
+ For a picture or video model that does not fit on one card. The model keeps the first card to itself, the text encoder and the VAE load onto the second, instead of spilling into system memory.
+ </span>
+ </span>
+ </label>
+ {split && (
+ <div className="pl-5 space-y-1.5">
+ {(['model', 'helper'] as const).map((part) => {
+ const title = part === 'model' ? 'Model on' : 'Text encoder and VAE on'
+ return (
+ <label key={part} className="block">
+ <span className="t-micro text-gray-700 dark:text-gray-300">{title}</span>
+ <select
+ value={keyOf(split[part])}
+ onChange={(e) => pickSplit(part, e.target.value)}
+ aria-label={title}
+ className={selectClass}
+ >
+ {nvCards.map((g) => (
+ <option key={`${g.vendor}:${g.index}`} value={`${g.vendor}:${g.index}`}>{label(g)}</option>
+ ))}
+ </select>
+ </label>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ )}
{gpuRolesSeparate(roles) && (
<Hinweis>
Two cards: LU no longer takes the chat model off its card to make room for a picture or a video.
diff --git a/src/components/settings/__tests__/ein-modell-ueber-zwei-karten.test.tsx b/src/components/settings/__tests__/ein-modell-ueber-zwei-karten.test.tsx
new file mode 100644
index 00000000..0a47e174
--- /dev/null
+++ b/src/components/settings/__tests__/ein-modell-ueber-zwei-karten.test.tsx
@@ -0,0 +1,124 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * C56 (3.1.0, the_cave_dweller on Discord: RTX 4090 + RTX 5080, 64 GB RAM):
+ * Settings, Hardware offers "One big model across two cards" next to "Card
+ * per task". Simulated cards, no real two-card machine. The 5080 is listed
+ * first on purpose (bus order), so the default has to pick the bigger card
+ * for the model, not the first one.
+ *
+ * Negative controls: one card shows nothing; an NVIDIA card next to an AMD
+ * one gets "Card per task" but no split (the split is NVIDIA only); turning
+ * it off leaves exactly the roles of 3.0.8.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/ein-modell-ueber-zwei-karten.test.tsx
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react'
+
+const calls: Array<{ cmd: string; args?: unknown }> = []
+let cards: unknown[] = []
+vi.mock('../../../api/backend', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../api/backend')>()),
+ isTauri: () => true,
+ isMacOS: () => false,
+ backendCall: vi.fn(async (cmd: string, args?: unknown) => {
+ calls.push({ cmd, args })
+ if (cmd === 'detect_gpus') return cards
+ if (cmd === 'describe_gpu_roles') {
+ return [{
+ service: 'ComfyUI',
+ env: ['CUDA_DEVICE_ORDER=PCI_BUS_ID', 'CUDA_VISIBLE_DEVICES=GPU-4090,GPU-5080'],
+ args: [],
+ note: 'One model across two cards: the diffusion model on #1 NVIDIA GeForce RTX 4090, text encoders and VAE on #0 NVIDIA GeForce RTX 5080 (ComfyUI calls it gpu:1).',
+ }]
+ }
+ return null
+ }),
+}))
+vi.mock('../../../api/mlx-image', () => ({ isMlxImageHost: () => false }))
+vi.mock('../../../api/comfy-restart', () => ({ restartComfyForNewNodes: async () => {} }))
+
+const { HardwareSettings } = await import('../HardwareSettings')
+const { useSettingsStore } = await import('../../../stores/settingsStore')
+const { DEFAULT_SETTINGS } = await import('../../../lib/constants')
+
+const R5080 = { index: 0, vendor: 'nvidia', name: 'NVIDIA GeForce RTX 5080', memory_mib: 16303, source: 'nvidia-smi' }
+const R4090 = { index: 1, vendor: 'nvidia', name: 'NVIDIA GeForce RTX 4090', memory_mib: 24564, source: 'nvidia-smi' }
+const ref = (c: typeof R4090) => ({ vendor: 'nvidia', index: c.index, name: c.name })
+
+const lastRoles = () => [...calls].reverse().find((c) => c.cmd === 'set_gpu_roles')?.args as { roles: unknown } | undefined
+const TOGGLE = 'One big model across two cards'
+
+beforeEach(() => {
+ calls.length = 0
+ useSettingsStore.setState((s) => ({ settings: { ...s.settings, ...DEFAULT_SETTINGS } }))
+})
+afterEach(() => cleanup())
+
+describe('one big model across two cards', () => {
+ it('4090 + 5080: on, the model goes to the 4090, text encoder and VAE to the 5080, Rust gets it', async () => {
+ cards = [R5080, R4090]
+ render(<HardwareSettings />)
+ fireEvent.click(await screen.findByLabelText(TOGGLE))
+ const want = { chat: null, comfy: null, comfySplit: { model: ref(R4090), helper: ref(R5080) } }
+ expect(useSettingsStore.getState().settings.gpuRoles).toEqual(want)
+ await waitFor(() => expect(lastRoles()?.roles).toEqual(want))
+ expect((screen.getByLabelText('Model on') as HTMLSelectElement).value).toBe('nvidia:1')
+ expect((screen.getByLabelText('Text encoder and VAE on') as HTMLSelectElement).value).toBe('nvidia:0')
+ // ComfyUI's single card waits while the split is on.
+ expect((screen.getByLabelText('Pictures and video (ComfyUI)') as HTMLSelectElement).disabled).toBe(true)
+ expect(screen.getByTestId('gpu-roles-restart-hint')).toBeTruthy()
+ await waitFor(() => expect(screen.getByTestId('gpu-roles-plan').textContent).toContain('CUDA_VISIBLE_DEVICES=GPU-4090,GPU-5080'))
+ })
+
+ it('picking the other card for the model swaps the two', async () => {
+ cards = [R5080, R4090]
+ render(<HardwareSettings />)
+ fireEvent.click(await screen.findByLabelText(TOGGLE))
+ fireEvent.change(screen.getByLabelText('Model on'), { target: { value: 'nvidia:0' } })
+ expect(useSettingsStore.getState().settings.gpuRoles.comfySplit).toEqual({ model: ref(R5080), helper: ref(R4090) })
+ })
+
+ it('a picked ComfyUI card becomes the model card', async () => {
+ cards = [R5080, R4090]
+ useSettingsStore.getState().updateSettings({ gpuRoles: { chat: null, comfy: ref(R5080) as never } })
+ render(<HardwareSettings />)
+ fireEvent.click(await screen.findByLabelText(TOGGLE))
+ expect(useSettingsStore.getState().settings.gpuRoles.comfySplit).toEqual({ model: ref(R5080), helper: ref(R4090) })
+ })
+
+ it('the chat on one of the two cards says it still makes room', async () => {
+ cards = [R5080, R4090]
+ render(<HardwareSettings />)
+ fireEvent.click(await screen.findByLabelText(TOGGLE))
+ fireEvent.change(screen.getByLabelText('Chat (LU Engine, Ollama)'), { target: { value: 'nvidia:0' } })
+ expect(screen.getByText(/still has to make room/)).toBeTruthy()
+ expect(screen.queryByText(/no longer takes the chat model off its card/)).toBeNull()
+ })
+
+ it('off again: exactly the roles of 3.0.8, no split key left', async () => {
+ cards = [R5080, R4090]
+ render(<HardwareSettings />)
+ fireEvent.click(await screen.findByLabelText(TOGGLE))
+ fireEvent.click(screen.getByLabelText(TOGGLE))
+ expect(useSettingsStore.getState().settings.gpuRoles).toEqual({ chat: null, comfy: null })
+ expect((screen.getByLabelText('Pictures and video (ComfyUI)') as HTMLSelectElement).disabled).toBe(false)
+ })
+
+ it('NEGATIVE: one card, no toggle', async () => {
+ cards = [R4090]
+ render(<HardwareSettings />)
+ await waitFor(() => expect(calls.some((c) => c.cmd === 'detect_gpus')).toBe(true))
+ await screen.findAllByText(/RTX 4090/)
+ expect(screen.queryByLabelText(TOGGLE)).toBeNull()
+ expect(screen.queryByTestId('comfy-split')).toBeNull()
+ })
+
+ it('NEGATIVE: NVIDIA + AMD, Card per task yes, the split no', async () => {
+ cards = [R4090, { index: 0, vendor: 'amd', name: 'AMD Radeon RX 7900 XTX', memory_mib: 24560, source: 'rocm-smi' }]
+ render(<HardwareSettings />)
+ await screen.findByLabelText('Chat (LU Engine, Ollama)')
+ expect(screen.queryByLabelText(TOGGLE)).toBeNull()
+ })
+})
diff --git a/src/lib/__tests__/comfy-split.test.ts b/src/lib/__tests__/comfy-split.test.ts
new file mode 100644
index 00000000..4a83858c
--- /dev/null
+++ b/src/lib/__tests__/comfy-split.test.ts
@@ -0,0 +1,329 @@
+/**
+ * C56 (3.1.0): one picture or video model across two cards, without a real
+ * two-card machine. What is checked here:
+ * - the graph surgery on graphs LU's own builders make (Flux, Wan 2.2) and
+ * on the real LTX 2.5 template of Comfy-Org (two VAEs, two text models,
+ * a subgraph), with node definitions written down from ComfyUI v0.42.4
+ * - the shapes it must leave alone (a LoRA chain, a graph that already
+ * places its parts, an unknown node)
+ * - the check that the running ComfyUI really sees the two cards in the
+ * right order (simulated /system_stats of a 4090 + 5080 machine)
+ *
+ * The other half, ComfyUI being started with both cards, is in Rust
+ * (commands/gpu_roles.rs, `the_split_*` tests).
+ *
+ * Run: npx vitest run src/lib/__tests__/comfy-split.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import type { ComfyApiGraph } from '../../types/comfy-graph'
+import type { ComfyNodeDefs } from '../../api/comfy-ui-format'
+
+vi.mock('../../api/comfyui-nodes', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../api/comfyui-nodes')>()
+ return { ...actual, getAllNodeInfo: vi.fn() }
+})
+vi.mock('../../api/backend', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../api/backend')>()
+ return { ...actual, localFetch: vi.fn(), comfyuiUrl: (p: string) => `http://test${p}` }
+})
+
+const { splitAcrossCards, comfySeesSplit, SELECT_CLIP_DEVICE, SELECT_VAE_DEVICE } = await import('../comfy-split')
+const { getAllNodeInfo } = await import('../../api/comfyui-nodes')
+const { localFetch } = await import('../../api/backend')
+const { useSettingsStore } = await import('../../stores/settingsStore')
+const { withComfySplit } = await import('../../api/comfy-split')
+
+/** RETURN_TYPES of the core nodes involved, from the ComfyUI v0.42.4 sources
+ * (nodes.py, comfy_extras/*). */
+const OUTPUTS: Record<string, string[]> = {
+ CheckpointLoaderSimple: ['MODEL', 'CLIP', 'VAE'],
+ UNETLoader: ['MODEL'],
+ UnetLoaderGGUF: ['MODEL'],
+ CLIPLoader: ['CLIP'],
+ DualCLIPLoader: ['CLIP'],
+ TripleCLIPLoader: ['CLIP'],
+ QuadrupleCLIPLoader: ['CLIP'],
+ VAELoader: ['VAE'],
+ LoraLoader: ['MODEL', 'CLIP'],
+ LoraLoaderModelOnly: ['MODEL'],
+ CLIPSetLastLayer: ['CLIP'],
+ CLIPTextEncode: ['CONDITIONING'],
+ CLIPVisionLoader: ['CLIP_VISION'],
+ KSampler: ['LATENT'],
+ VAEDecode: ['IMAGE'],
+ VAEDecodeTiled: ['IMAGE'],
+ VAEEncode: ['LATENT'],
+ EmptySD3LatentImage: ['LATENT'],
+ EmptyLatentImage: ['LATENT'],
+ ModelSamplingSD3: ['MODEL'],
+ Wan22ImageToVideoLatent: ['LATENT'],
+ SaveImage: [],
+ SaveVideo: [],
+ CreateVideo: ['VIDEO'],
+ VHS_VideoCombine: ['VHS_FILENAMES'],
+ SelectCLIPDevice: ['CLIP'],
+ SelectVAEDevice: ['VAE'],
+}
+const outputsOf = (cls: string) => OUTPUTS[cls]
+
+const BOTH = { clip: true, vae: true }
+
+/** Every link in the graph that carries a CLIP or a VAE, with what reads it. */
+function partLinks(g: ComfyApiGraph, outs: (c: string) => readonly string[] | undefined) {
+ const found: Array<{ reader: string; input: string; from: string; type: string }> = []
+ for (const [id, node] of Object.entries(g)) {
+ for (const [input, v] of Object.entries(node.inputs ?? {})) {
+ if (!Array.isArray(v) || v.length !== 2 || typeof v[0] !== 'string' || typeof v[1] !== 'number') continue
+ const src = g[v[0]]
+ const type = src ? outs(src.class_type)?.[v[1]] : undefined
+ if (type === 'CLIP' || type === 'VAE') found.push({ reader: `${id}:${node.class_type}`, input, from: src!.class_type, type })
+ }
+ }
+ return found
+}
+
+/** After the split every text encoder and VAE reader either is a Select
+ * node or a node that hands a CLIP on (LoRA), or reads from one of those. */
+function everyPartGoesThroughTheSecondCard(g: ComfyApiGraph, outs: (c: string) => readonly string[] | undefined) {
+ for (const l of partLinks(g, outs)) {
+ const isSelect = l.reader.endsWith(`:${SELECT_CLIP_DEVICE}`) || l.reader.endsWith(`:${SELECT_VAE_DEVICE}`)
+ const fromLoader = !['SelectCLIPDevice', 'SelectVAEDevice', 'LoraLoader', 'CLIPSetLastLayer'].includes(l.from)
+ if (fromLoader) expect(isSelect, `${l.reader}.${l.input} reads ${l.type} straight from ${l.from}`).toBe(true)
+ }
+ for (const node of Object.values(g)) {
+ if (node.class_type === SELECT_CLIP_DEVICE || node.class_type === SELECT_VAE_DEVICE) {
+ expect(node.inputs?.device).toBe('gpu:1')
+ }
+ }
+}
+
+describe('the graph surgery', () => {
+ it('Flux as LU builds it: one CLIP node and one VAE node, every reader rewired, input untouched', async () => {
+ vi.mocked(localFetch).mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ CLIPLoader: { input: { required: { clip_name: [['t5xxl_fp8_e4m3fn.safetensors', 'clip_l.safetensors']] } } },
+ VAELoader: { input: { required: { vae_name: [['ae.safetensors']] } } },
+ UNETLoader: { input: { required: { unet_name: [['flux1-dev-fp8.safetensors']] } } },
+ }),
+ } as never)
+ const { buildFluxImgWorkflow } = await import('../../api/comfyui')
+ const g = await buildFluxImgWorkflow({
+ model: 'flux1-dev-fp8.safetensors', prompt: 'a red apple', negativePrompt: '',
+ sampler: 'euler', scheduler: 'simple', steps: 20, cfgScale: 1, width: 1024, height: 1024, seed: 1, batchSize: 1,
+ })
+ const before = JSON.stringify(g)
+ const { graph, inserted } = splitAcrossCards(g, outputsOf, BOTH)
+ expect(JSON.stringify(g)).toBe(before)
+ expect(inserted).toEqual(['CLIPLoader:0 -> SelectCLIPDevice', 'VAELoader:0 -> SelectVAEDevice'])
+ expect(graph['10']).toMatchObject({ class_type: 'SelectCLIPDevice', inputs: { clip: ['2', 0], device: 'gpu:1' } })
+ expect(graph['11']).toMatchObject({ class_type: 'SelectVAEDevice', inputs: { vae: ['3', 0], device: 'gpu:1' } })
+ // Both prompts and the decode read the moved parts; the model stays put.
+ expect(graph['4'].inputs?.clip).toEqual(['10', 0])
+ expect(graph['5'].inputs?.clip).toEqual(['10', 0])
+ expect(graph['8'].inputs?.vae).toEqual(['11', 0])
+ expect(graph['7'].inputs?.model).toEqual(['1', 0])
+ everyPartGoesThroughTheSecondCard(graph, outputsOf)
+ })
+
+ it('Wan 2.2 as LU builds it: the UMT5 encoder and the Wan VAE move, the latent node reads the moved VAE', async () => {
+ vi.mocked(getAllNodeInfo).mockResolvedValue({
+ UNETLoader: { input: { required: { unet_name: [['wan2.2_ti2v_5B_fp16.safetensors']] } } },
+ CLIPLoader: { input: { required: { clip_name: [['umt5_xxl_fp8_e4m3fn_scaled.safetensors']] } } },
+ VAELoader: { input: { required: { vae_name: [['wan2.2_vae.safetensors']] } } },
+ Wan22ImageToVideoLatent: { input: { required: { vae: ['VAE'], width: ['INT'], height: ['INT'], length: ['INT'], batch_size: ['INT'] }, optional: { start_image: ['IMAGE', {}] } } },
+ ModelSamplingSD3: { input: { required: { model: ['MODEL'], shift: ['FLOAT'] } } },
+ KSampler: { input: { required: {} } },
+ CLIPTextEncode: { input: { required: {} } },
+ VAEDecode: { input: { required: {} } },
+ ImageScale: { input: { required: {} } },
+ LoadImage: { input: { required: {} } },
+ VHS_VideoCombine: { input: { required: {} } },
+ } as never)
+ vi.mocked(localFetch).mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ CLIPLoader: { input: { required: { clip_name: [['umt5_xxl_fp8_e4m3fn_scaled.safetensors']] } } },
+ VAELoader: { input: { required: { vae_name: [['wan2.2_vae.safetensors']] } } },
+ }),
+ } as never)
+ const { buildDynamicWorkflow } = await import('../../api/dynamic-workflow')
+ const g = await buildDynamicWorkflow({
+ model: 'wan2.2_ti2v_5B_fp16.safetensors', prompt: 'a red apple', negativePrompt: '',
+ sampler: 'euler', scheduler: 'simple', steps: 30, cfgScale: 5, width: 1024, height: 576, seed: 42, batchSize: 1,
+ frames: 49, fps: 24,
+ } as never)
+ const { graph, inserted } = splitAcrossCards(g, outputsOf, BOTH)
+ expect(inserted.sort()).toEqual(['CLIPLoader:0 -> SelectCLIPDevice', 'VAELoader:0 -> SelectVAEDevice'])
+ const latent = Object.values(graph).find((n) => n.class_type === 'Wan22ImageToVideoLatent')!
+ const vaeRef = latent.inputs?.vae as [string, number]
+ expect(graph[vaeRef[0]].class_type).toBe('SelectVAEDevice')
+ everyPartGoesThroughTheSecondCard(graph, outputsOf)
+ })
+
+ it('a LoRA chain: the node sits behind the loader, the LoRA hands the moved copy on and gets none of its own', () => {
+ const g: ComfyApiGraph = {
+ '1': { class_type: 'CheckpointLoaderSimple', inputs: { ckpt_name: 'sdxl.safetensors' } },
+ '2': { class_type: 'LoraLoader', inputs: { model: ['1', 0], clip: ['1', 1], lora_name: 'a.safetensors', strength_model: 1, strength_clip: 1 } },
+ '3': { class_type: 'CLIPSetLastLayer', inputs: { clip: ['2', 1], stop_at_clip_layer: -2 } },
+ '4': { class_type: 'CLIPTextEncode', inputs: { text: 'x', clip: ['3', 0] } },
+ '5': { class_type: 'CLIPTextEncode', inputs: { text: '', clip: ['3', 0] } },
+ '6': { class_type: 'EmptyLatentImage', inputs: { width: 1024, height: 1024, batch_size: 1 } },
+ '7': { class_type: 'KSampler', inputs: { model: ['2', 0], positive: ['4', 0], negative: ['5', 0], latent_image: ['6', 0] } },
+ '8': { class_type: 'VAEDecode', inputs: { samples: ['7', 0], vae: ['1', 2] } },
+ '9': { class_type: 'SaveImage', inputs: { images: ['8', 0], filename_prefix: 'x' } },
+ }
+ const { graph, inserted } = splitAcrossCards(g, outputsOf, BOTH)
+ expect(inserted).toEqual(['CheckpointLoaderSimple:1 -> SelectCLIPDevice', 'CheckpointLoaderSimple:2 -> SelectVAEDevice'])
+ expect(graph['2'].inputs?.clip).toEqual(['10', 0])
+ expect(graph['3'].inputs?.clip).toEqual(['2', 1])
+ expect(graph['8'].inputs?.vae).toEqual(['11', 0])
+ // The checkpoint's model output is not touched.
+ expect(graph['2'].inputs?.model).toEqual(['1', 0])
+ everyPartGoesThroughTheSecondCard(graph, outputsOf)
+ })
+
+ it('a graph that places its parts itself, an unknown loader and a part nobody reads are left alone', () => {
+ const g: ComfyApiGraph = {
+ '1': { class_type: 'CLIPLoader', inputs: { clip_name: 't5.safetensors' } },
+ '2': { class_type: 'SelectCLIPDevice', inputs: { clip: ['1', 0], device: 'gpu:0' } },
+ '3': { class_type: 'CLIPTextEncode', inputs: { text: 'x', clip: ['2', 0] } },
+ '4': { class_type: 'SomeoneElsesLoader', inputs: {} },
+ '5': { class_type: 'VAEDecode', inputs: { samples: ['9', 0], vae: ['4', 0] } },
+ '6': { class_type: 'VAELoader', inputs: { vae_name: 'unused.safetensors' } },
+ }
+ const out = splitAcrossCards(g, outputsOf, BOTH)
+ expect(out.inserted).toEqual([])
+ expect(out.graph).toBe(g)
+ })
+
+ it('a ComfyUI that has only one of the two nodes gets only that one', () => {
+ const g: ComfyApiGraph = {
+ '1': { class_type: 'CLIPLoader', inputs: {} },
+ '2': { class_type: 'VAELoader', inputs: {} },
+ '3': { class_type: 'CLIPTextEncode', inputs: { clip: ['1', 0] } },
+ '4': { class_type: 'VAEDecode', inputs: { vae: ['2', 0] } },
+ }
+ expect(splitAcrossCards(g, outputsOf, { clip: false, vae: true }).inserted).toEqual(['VAELoader:0 -> SelectVAEDevice'])
+ expect(splitAcrossCards(g, outputsOf, { clip: false, vae: false }).graph).toBe(g)
+ })
+
+ it('the real LTX 2.5 template (two VAEs, two text models, a subgraph): every part moves', async () => {
+ const DIR = join(process.cwd(), 'src/api/__tests__/fixtures/comfy-ui')
+ const defs = JSON.parse(readFileSync(join(DIR, 'object-info-ltx25.json'), 'utf8')) as ComfyNodeDefs
+ const text = readFileSync(join(DIR, 'templates/video_ltx2_5_i2v.json'), 'utf8')
+ const { readWorkflowText } = await import('../../api/workflow-import')
+ const read = await readWorkflowText(text, async (types: string[]) => {
+ const out: ComfyNodeDefs = {}
+ for (const t of types) if (defs[t]) out[t] = defs[t]
+ return out
+ })
+ if (!read.ok) throw new Error(read.reason)
+ const outs = (cls: string) => (defs[cls] as { output?: string[] } | undefined)?.output ?? OUTPUTS[cls]
+ const before = partLinks(read.graph, outs)
+ expect(before.length).toBeGreaterThan(4)
+ const { graph, inserted } = splitAcrossCards(read.graph, outs, BOTH)
+ // Two text models (Gemma encoder, prompt enhancer) and two VAEs (video, audio).
+ expect(inserted.filter((s) => s.endsWith('SelectCLIPDevice'))).toHaveLength(2)
+ expect(inserted.filter((s) => s.endsWith('SelectVAEDevice'))).toHaveLength(2)
+ everyPartGoesThroughTheSecondCard(graph, outs)
+ // New ids never collide with the template's own.
+ expect(Object.keys(graph)).toHaveLength(Object.keys(read.graph).length + 4)
+ })
+})
+
+/** /system_stats of ComfyUI v0.42.4 on the 4090 + 5080 machine, as LU starts
+ * it with the split on: the model card first. */
+const STATS_SPLIT = [
+ { name: 'cuda:0 NVIDIA GeForce RTX 4090 : cudaMallocAsync', type: 'cuda', index: 0, vram_total: 25757220864 },
+ { name: 'cuda:1 NVIDIA GeForce RTX 5080 : cudaMallocAsync', type: 'cuda', index: 1, vram_total: 17094475776 },
+]
+
+describe('does the running ComfyUI see the split', () => {
+ it('two cards in the right order: yes', () => {
+ expect(comfySeesSplit(STATS_SPLIT, 'NVIDIA GeForce RTX 4090', 'NVIDIA GeForce RTX 5080')).toBe(true)
+ })
+ it('one card (started before the setting, or a one-card box): no', () => {
+ expect(comfySeesSplit([STATS_SPLIT[0]], 'NVIDIA GeForce RTX 4090', 'NVIDIA GeForce RTX 5080')).toBe(false)
+ expect(comfySeesSplit([{ name: 'cpu', type: 'cpu' }], 'a', 'b')).toBe(false)
+ expect(comfySeesSplit(undefined, 'a', 'b')).toBe(false)
+ })
+ it('the cards the other way round (a ComfyUI LU did not start): no', () => {
+ expect(comfySeesSplit([...STATS_SPLIT].reverse(), 'NVIDIA GeForce RTX 4090', 'NVIDIA GeForce RTX 5080')).toBe(false)
+ })
+ it('two identical cards: yes', () => {
+ const twins = [
+ { name: 'cuda:0 NVIDIA GeForce RTX 3090 : cudaMallocAsync', type: 'cuda' },
+ { name: 'cuda:1 NVIDIA GeForce RTX 3090 : cudaMallocAsync', type: 'cuda' },
+ ]
+ expect(comfySeesSplit(twins, 'NVIDIA GeForce RTX 3090', 'NVIDIA GeForce RTX 3090')).toBe(true)
+ })
+})
+
+describe('at submit (withComfySplit)', () => {
+ const flux: ComfyApiGraph = {
+ '1': { class_type: 'UNETLoader', inputs: { unet_name: 'flux.safetensors' } },
+ '2': { class_type: 'CLIPLoader', inputs: { clip_name: 't5.safetensors' } },
+ '3': { class_type: 'VAELoader', inputs: { vae_name: 'ae.safetensors' } },
+ '4': { class_type: 'CLIPTextEncode', inputs: { text: 'x', clip: ['2', 0] } },
+ '8': { class_type: 'VAEDecode', inputs: { samples: ['7', 0], vae: ['3', 0] } },
+ }
+ const split = {
+ model: { vendor: 'nvidia' as const, index: 0, name: 'NVIDIA GeForce RTX 4090' },
+ helper: { vendor: 'nvidia' as const, index: 1, name: 'NVIDIA GeForce RTX 5080' },
+ }
+ const nodeInfo = Object.fromEntries(Object.entries(OUTPUTS).map(([k, v]) => [k, { input: { required: {} }, output: v }]))
+ const stats = (devices: unknown[]) => ({ ok: true, json: async () => ({ devices }) }) as never
+
+ beforeEach(() => {
+ vi.mocked(localFetch).mockReset()
+ vi.mocked(getAllNodeInfo).mockReset()
+ vi.mocked(getAllNodeInfo).mockResolvedValue(nodeInfo as never)
+ })
+ const setRoles = (comfySplit: unknown) =>
+ useSettingsStore.setState((s) => ({ settings: { ...s.settings, gpuRoles: { chat: null, comfy: null, ...(comfySplit ? { comfySplit } : {}) } as never } }))
+
+ it('off (every one-card machine): the same object, and not one request', async () => {
+ setRoles(null)
+ expect(await withComfySplit(flux)).toBe(flux)
+ expect(localFetch).not.toHaveBeenCalled()
+ })
+
+ it('on, and ComfyUI sees both cards: the parts move', async () => {
+ setRoles(split)
+ vi.mocked(localFetch).mockResolvedValue(stats(STATS_SPLIT))
+ const out = await withComfySplit(flux)
+ expect(Object.values(out).map((n) => n.class_type)).toEqual(expect.arrayContaining(['SelectCLIPDevice', 'SelectVAEDevice']))
+ })
+
+ it('on, but ComfyUI still runs on one card: unchanged', async () => {
+ setRoles(split)
+ vi.mocked(localFetch).mockResolvedValue(stats([STATS_SPLIT[0]]))
+ expect(await withComfySplit(flux)).toBe(flux)
+ })
+
+ it('on, but this ComfyUI has no Select nodes (older than 0.23): unchanged', async () => {
+ setRoles(split)
+ vi.mocked(localFetch).mockResolvedValue(stats(STATS_SPLIT))
+ const { SelectCLIPDevice: _c, SelectVAEDevice: _v, ...old } = nodeInfo
+ void _c; void _v
+ vi.mocked(getAllNodeInfo).mockResolvedValue(old as never)
+ expect(await withComfySplit(flux)).toBe(flux)
+ })
+
+ it('on, and ComfyUI does not answer: unchanged, no throw', async () => {
+ setRoles(split)
+ vi.mocked(localFetch).mockRejectedValue(new Error('connection refused'))
+ expect(await withComfySplit(flux)).toBe(flux)
+ })
+
+ it('a stored split on one card or on AMD is no split', async () => {
+ setRoles({ model: split.model, helper: split.model })
+ expect(await withComfySplit(flux)).toBe(flux)
+ setRoles({ model: { ...split.model, vendor: 'amd' }, helper: { ...split.helper, vendor: 'amd' } })
+ expect(await withComfySplit(flux)).toBe(flux)
+ expect(localFetch).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/__tests__/gpu-roles.test.ts b/src/lib/__tests__/gpu-roles.test.ts
index 7103996b..cb95b448 100644
--- a/src/lib/__tests__/gpu-roles.test.ts
+++ b/src/lib/__tests__/gpu-roles.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { normalizeGpuRoles, gpuRolesSeparate, sameCard, NO_GPU_ROLES } from '../gpu-roles'
+import { normalizeGpuRoles, gpuRolesSeparate, sameCard, NO_GPU_ROLES, comfySplitOf, comfyCards } from '../gpu-roles'
const a = { vendor: 'nvidia' as const, index: 0, name: 'RTX 4090' }
const b = { vendor: 'nvidia' as const, index: 1, name: 'RTX 3060' }
@@ -30,4 +30,27 @@ describe('gpu roles', () => {
expect(gpuRolesSeparate({ chat: a, comfy: { vendor: 'amd', index: 0, name: 'RX' } })).toBe(true)
expect(sameCard(a, null)).toBe(false)
})
+
+ // C56 (3.1.0): one model across two cards.
+ const c = { vendor: 'nvidia' as const, index: 2, name: 'RTX 5080' }
+
+ it('a stored split survives only as two different NVIDIA cards', () => {
+ expect(normalizeGpuRoles({ chat: null, comfy: null, comfySplit: { model: a, helper: b } })).toEqual({
+ chat: null, comfy: null, comfySplit: { model: a, helper: b },
+ })
+ // Same card, AMD, half a split: gone, the rest stays.
+ expect(normalizeGpuRoles({ chat: a, comfySplit: { model: a, helper: a } })).toEqual({ chat: a, comfy: null })
+ expect(normalizeGpuRoles({ comfySplit: { model: { ...a, vendor: 'amd' }, helper: { ...b, vendor: 'amd' } } })).toEqual(NO_GPU_ROLES)
+ expect(normalizeGpuRoles({ comfySplit: { model: a } })).toEqual(NO_GPU_ROLES)
+ expect(comfySplitOf({ chat: null, comfy: null })).toBeNull()
+ })
+
+ it('a split ComfyUI holds both its cards, the chat is apart only on a third', () => {
+ const split = { model: a, helper: b }
+ expect(comfyCards({ chat: null, comfy: c, comfySplit: split })).toEqual([a, b])
+ expect(gpuRolesSeparate({ chat: c, comfy: null, comfySplit: split })).toBe(true)
+ expect(gpuRolesSeparate({ chat: a, comfy: null, comfySplit: split })).toBe(false)
+ expect(gpuRolesSeparate({ chat: b, comfy: c, comfySplit: split })).toBe(false)
+ expect(gpuRolesSeparate({ chat: null, comfy: null, comfySplit: split })).toBe(false)
+ })
})
diff --git a/src/lib/comfy-split.ts b/src/lib/comfy-split.ts
new file mode 100644
index 00000000..d6679479
--- /dev/null
+++ b/src/lib/comfy-split.ts
@@ -0,0 +1,169 @@
+/**
+ * One picture or video model across two cards (3.1.0, C56).
+ *
+ * What it is for: a model that does not fit on the main card. Without this,
+ * ComfyUI keeps the diffusion model, the text encoder and the VAE on one card
+ * and moves what does not fit into system memory, which is slow. With two
+ * cards the diffusion model keeps the main card to itself and the text
+ * encoders and the VAE go to the second one.
+ *
+ * How, without any custom node: ComfyUI itself has "Select CLIP Device" and
+ * "Select VAE Device" (comfy_extras/nodes_multigpu.py, core since 0.23, LU
+ * pins 0.42.4). Each takes a CLIP or a VAE and a device (`gpu:N`) and hands
+ * on a copy that loads onto that card. The Rust side starts ComfyUI with
+ * both cards visible and the model card first (commands/gpu_roles.rs,
+ * ComfySplit), so the model card is `gpu:0`, ComfyUI's default device, and
+ * the helper card is `gpu:1`.
+ *
+ * This file is the pure part: put one such node behind every text encoder
+ * and VAE LOADER of a graph and point every consumer at it. A node that takes
+ * a CLIP and gives one back (a LoRA loader) is not a loader, it hands on the
+ * copy it was given, so it gets no node of its own. A graph that already
+ * places a CLIP or a VAE itself is left as it is.
+ *
+ * Safe in both directions by ComfyUI's own design: on a machine where
+ * `gpu:1` does not exist, or behind a loader that cannot be reloaded on
+ * another card (a GGUF loader without a reload factory), the node logs a line
+ * and passes its input through unchanged.
+ */
+
+import type { ComfyApiGraph, ComfyApiNode, ComfyInputValue } from '../types/comfy-graph'
+
+export const SELECT_CLIP_DEVICE = 'SelectCLIPDevice'
+export const SELECT_VAE_DEVICE = 'SelectVAEDevice'
+
+/** ComfyUI's name for the second visible card. */
+export const SPLIT_HELPER_DEVICE = 'gpu:1'
+
+/** The output types of a node class (`/object_info` `output`), or undefined
+ * when the class is unknown. */
+export type OutputTypesOf = (classType: string) => readonly string[] | undefined
+
+export interface SplitOptions {
+ /** Put a node behind text encoder loaders. False when ComfyUI lacks it. */
+ clip: boolean
+ /** Put a node behind VAE loaders. False when ComfyUI lacks it. */
+ vae: boolean
+ device?: string
+}
+
+export interface SplitResult {
+ graph: ComfyApiGraph
+ /** One entry per node put in: `<loader class>:<slot> -> <select class>`. */
+ inserted: string[]
+}
+
+const SELECT_FOR: Record<string, string> = { CLIP: SELECT_CLIP_DEVICE, VAE: SELECT_VAE_DEVICE }
+
+function isLink(v: ComfyInputValue | undefined): v is [string, number] {
+ return Array.isArray(v) && v.length === 2 && typeof v[0] === 'string' && typeof v[1] === 'number'
+}
+
+function nextIds(graph: ComfyApiGraph): () => string {
+ let max = 0
+ for (const id of Object.keys(graph)) {
+ const n = Number(id)
+ if (Number.isInteger(n) && n > max) max = n
+ }
+ return () => String(++max)
+}
+
+/**
+ * The graph with a Select CLIP/VAE Device node behind every text encoder and
+ * VAE loader. Never mutates its input; a graph with nothing to do comes back
+ * as the same object.
+ */
+export function splitAcrossCards(graph: ComfyApiGraph, outputsOf: OutputTypesOf, opts: SplitOptions): SplitResult {
+ const device = opts.device ?? SPLIT_HELPER_DEVICE
+ const wanted = new Set<string>()
+ if (opts.clip) wanted.add('CLIP')
+ if (opts.vae) wanted.add('VAE')
+ if (wanted.size === 0) return { graph, inserted: [] }
+
+ const typeOf = (id: string, slot: number): string | undefined => {
+ const node = graph[id]
+ return node ? outputsOf(node.class_type)?.[slot] : undefined
+ }
+
+ // Who reads which output.
+ const consumers = new Map<string, Array<{ id: string; input: string }>>()
+ for (const [id, node] of Object.entries(graph)) {
+ for (const [input, v] of Object.entries(node.inputs ?? {})) {
+ if (!isLink(v)) continue
+ const key = `${v[0]}:${v[1]}`
+ const list = consumers.get(key) ?? []
+ list.push({ id, input })
+ consumers.set(key, list)
+ }
+ }
+
+ const placements: Array<{ id: string; slot: number; select: string }> = []
+ for (const [id, node] of Object.entries(graph)) {
+ if (node.class_type === SELECT_CLIP_DEVICE || node.class_type === SELECT_VAE_DEVICE) continue
+ const outputs = outputsOf(node.class_type)
+ if (!outputs) continue
+ outputs.forEach((type, slot) => {
+ if (!wanted.has(type)) return
+ // Not a loader: it takes this type in and hands it on.
+ const takesSameType = Object.values(node.inputs ?? {}).some((v) => isLink(v) && typeOf(v[0], v[1]) === type)
+ if (takesSameType) return
+ const readers = consumers.get(`${id}:${slot}`) ?? []
+ if (readers.length === 0) return
+ // The graph places this one itself.
+ if (readers.some((r) => graph[r.id]?.class_type === SELECT_FOR[type])) return
+ placements.push({ id, slot, select: SELECT_FOR[type] })
+ })
+ }
+ if (placements.length === 0) return { graph, inserted: [] }
+
+ const out: ComfyApiGraph = {}
+ for (const [id, node] of Object.entries(graph)) out[id] = { ...node, inputs: { ...node.inputs } }
+ const newId = nextIds(graph)
+ const inserted: string[] = []
+ for (const p of placements) {
+ const sid = newId()
+ const inputName = p.select === SELECT_CLIP_DEVICE ? 'clip' : 'vae'
+ const selectNode: ComfyApiNode = {
+ class_type: p.select,
+ inputs: { [inputName]: [p.id, p.slot], device },
+ _meta: { title: `LU: ${inputName === 'clip' ? 'text encoder' : 'VAE'} on the second card` },
+ }
+ for (const r of consumers.get(`${p.id}:${p.slot}`) ?? []) {
+ const target = out[r.id]
+ target.inputs = { ...(target.inputs ?? {}), [r.input]: [sid, 0] }
+ }
+ out[sid] = selectNode
+ inserted.push(`${graph[p.id].class_type}:${p.slot} -> ${p.select}`)
+ }
+ return { graph: out, inserted }
+}
+
+/** One `/system_stats` device entry, as far as this needs it. */
+export interface StatsDevice {
+ name?: unknown
+ type?: unknown
+}
+
+function norm(s: string): string {
+ return s.toLowerCase().replace(/\s+/g, ' ').trim()
+}
+
+/**
+ * Whether the running ComfyUI sees the two cards in the order the split
+ * needs: at least two GPU devices, the first one the model card and the
+ * second one the helper card. ComfyUI names a device
+ * `cuda:1 NVIDIA GeForce RTX 5080 : cudaMallocAsync`, so a card's name is
+ * looked for inside it. A ComfyUI started before the setting was turned on
+ * (one card visible), one LU did not start, or one that sees the cards the
+ * other way round all answer false, and the workflow goes out unchanged.
+ */
+export function comfySeesSplit(devices: unknown, modelName: string, helperName: string): boolean {
+ if (!Array.isArray(devices)) return false
+ const gpus = (devices as StatsDevice[]).filter((d) => {
+ const type = String(d?.type ?? '').toLowerCase()
+ return type !== 'cpu' && !String(d?.name ?? '').toLowerCase().startsWith('cpu')
+ })
+ if (gpus.length < 2) return false
+ const has = (d: StatsDevice, name: string) => !name.trim() || norm(String(d?.name ?? '')).includes(norm(name))
+ return has(gpus[0], modelName) && has(gpus[1], helperName)
+}
diff --git a/src/lib/gpu-roles.ts b/src/lib/gpu-roles.ts
index 0f3efbb2..9c619a21 100644
--- a/src/lib/gpu-roles.ts
+++ b/src/lib/gpu-roles.ts
@@ -1,4 +1,4 @@
-import type { GpuRef, GpuRoles } from '../types/settings'
+import type { ComfySplit, GpuRef, GpuRoles } from '../types/settings'
/**
* Which card each service runs on (3.0.8, A2, .molot's two-GPU wish).
@@ -24,23 +24,53 @@ function normalizeRef(raw: unknown): GpuRef | null {
return { vendor: r.vendor as GpuRef['vendor'], index, name: typeof r.name === 'string' ? r.name : '' }
}
+/** A stored split, kept only when it can work: two different NVIDIA cards
+ * (the Rust side, `ComfySplit::usable`, applies the same rule). */
+function normalizeSplit(raw: unknown): ComfySplit | null {
+ if (!raw || typeof raw !== 'object') return null
+ const r = raw as Record<string, unknown>
+ const model = normalizeRef(r.model)
+ const helper = normalizeRef(r.helper)
+ if (!model || !helper) return null
+ if (model.vendor !== 'nvidia' || helper.vendor !== 'nvidia' || model.index === helper.index) return null
+ return { model, helper }
+}
+
/** A stored value of any age as roles. Anything unreadable is "no pick". */
export function normalizeGpuRoles(raw: unknown): GpuRoles {
if (!raw || typeof raw !== 'object') return { ...NO_GPU_ROLES }
const r = raw as Record<string, unknown>
- return { chat: normalizeRef(r.chat), comfy: normalizeRef(r.comfy) }
+ const comfySplit = normalizeSplit(r.comfySplit)
+ return { chat: normalizeRef(r.chat), comfy: normalizeRef(r.comfy), ...(comfySplit ? { comfySplit } : {}) }
}
export function sameCard(a: GpuRef | null, b: GpuRef | null): boolean {
return !!a && !!b && a.vendor === b.vendor && a.index === b.index
}
+/** The split, when one is set that can work. */
+export function comfySplitOf(roles: GpuRoles | null | undefined): ComfySplit | null {
+ return normalizeSplit(roles?.comfySplit)
+}
+
+/** The cards ComfyUI runs on when it is pinned: both split cards, or the
+ * ComfyUI card. Empty when ComfyUI is not pinned at all. */
+export function comfyCards(roles: GpuRoles | null | undefined): GpuRef[] {
+ const split = comfySplitOf(roles)
+ if (split) return [split.model, split.helper]
+ return roles?.comfy ? [roles.comfy] : []
+}
+
/**
* Chat and ComfyUI are pinned to two different cards. Only then is the VRAM
* hand-off pointless: with one of them unpinned it may still land on the
* other's card, so the old rules keep applying.
*/
export function gpuRolesSeparate(roles: GpuRoles | null | undefined): boolean {
- if (!roles?.chat || !roles.comfy) return false
- return !sameCard(roles.chat, roles.comfy)
+ const chat = roles?.chat ?? null
+ const comfy = comfyCards(roles)
+ if (!chat || comfy.length === 0) return false
+ // C56: a split ComfyUI holds BOTH its cards, so the chat is apart only on
+ // a third one.
+ return comfy.every((c) => !sameCard(chat, c))
}
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 5098f640..97e9381e 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -599,4 +599,13 @@ export interface GpuRef {
export interface GpuRoles {
chat: GpuRef | null
comfy: GpuRef | null
+ /** 3.1.0 (C56): one picture or video model across two cards. Set, ComfyUI
+ * sees both cards and this wins over `comfy` (lib/comfy-split.ts). */
+ comfySplit?: ComfySplit | null
+}
+
+/** The diffusion model on `model`, the text encoders and the VAE on `helper`. */
+export interface ComfySplit {
+ model: GpuRef
+ helper: GpuRef
}