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.

20.4 KB
Raw Blame
//! Which attention flag a ComfyUI that LU starts gets.
//!
//! ComfyUI's `cli_args.py` puts the attention switches into one mutually
//! exclusive argparse group (`--use-split-cross-attention`,
//! `--use-quad-cross-attention`, `--use-pytorch-cross-attention`,
//! `--use-sage-attention`, `--use-flash-attention`, `--use-ck-attention`, ...).
//! Two of them on one command line and argparse exits before ComfyUI has
//! printed a single line of its own, so the decision below always yields at
//! most ONE flag.
//!
//! Order of preference:
//!
//! 1. `--use-ck-attention` (Comfy Kitchen, ComfyUI 0.32.0 and later). The
//!    `comfy-kitchen` package is in ComfyUI's own requirements.txt, so on a
//!    current install it is there without LU fetching anything. Only on a
//!    CUDA (NVIDIA) or ROCm torch: not under `--cpu`, not under
//!    `--directml`, not on Intel XPU, never on a Mac (LU starts no ComfyUI
//!    there anyway).
//! 2. `--use-flash-attention` when flash-attn imports in this Python, the
//!    rule that was here before (process.rs, `probe_flash_attention`).
//! 3. Nothing: ComfyUI picks its own default.
//!
//! A start with the ck flag that dies before the port answers is started
//! again without it, and that outcome is remembered per ComfyUI folder and
//! version in the app's config.json (the same read, change, write as
//! `remember_bound_python_in`). A newer ComfyUI gets a fresh try, because the
//! version is part of the key. `LU_COMFY_NO_CK=1` switches the flag off
//! entirely, for a support case that needs it gone without a rebuild.

use crate::python::python_command;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::process::Stdio;
use std::sync::Mutex;

#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;

/// The Comfy Kitchen attention switch.
pub(crate) const CK_FLAG: &str = "--use-ck-attention";
/// The FlashAttention-2 switch, unchanged from before.
pub(crate) const FLASH_FLAG: &str = "--use-flash-attention";

/// The first ComfyUI release that knows `--use-ck-attention`. An older
/// ComfyUI would reject the unknown flag in argparse and never start.
pub(crate) const CK_MIN_VERSION: ComfyVersion = ComfyVersion(0, 32, 0);

/// Environment switch that keeps the ck flag off whatever else is true.
pub(crate) const NO_CK_ENV: &str = "LU_COMFY_NO_CK";

/// A ComfyUI release number, `major.minor.patch`. Ordered, so a minimum
/// version is a plain `>=`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct ComfyVersion(pub u32, pub u32, pub u32);

impl std::fmt::Display for ComfyVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}.{}", self.0, self.1, self.2)
    }
}

/// The version out of the text of ComfyUI's `comfyui_version.py`.
///
/// The file is generated by ComfyUI's release tooling and holds one line that
/// matters, `__version__ = "0.42.4"`. Single or double quotes, spaces or not
/// around the `=`, a leading `v`, and a suffix after the patch number
/// (`0.42.4rc1`) are all read; anything that does not give three numbers is
/// `None`, and `None` never unlocks the ck flag.
pub(crate) fn parse_comfyui_version(text: &str) -> Option<ComfyVersion> {
    for line in text.lines() {
        let line = line.trim();
        let Some(rest) = line.strip_prefix("__version__") else { continue };
        let Some(value) = rest.trim_start().strip_prefix('=') else { continue };
        let value = value.trim().trim_matches(|c| c == '"' || c == '\'');
        let value = value.strip_prefix('v').unwrap_or(value);
        let mut parts = value.split('.');
        let mut number = || -> Option<u32> {
            let part = parts.next()?;
            let digits: String = part.chars().take_while(|c| c.is_ascii_digit()).collect();
            digits.parse().ok()
        };
        let (major, minor, patch) = (number()?, number()?, number()?);
        return Some(ComfyVersion(major, minor, patch));
    }
    None
}

/// The installed ComfyUI's version, read from `<comfy_dir>/comfyui_version.py`.
/// A portable or very old ComfyUI without the file reads as `None`.
pub(crate) fn read_comfyui_version(comfy_dir: &Path) -> Option<ComfyVersion> {
    parse_comfyui_version(&fs::read_to_string(comfy_dir.join("comfyui_version.py")).ok()?)
}

/// Everything the ck decision depends on, gathered by the start before it
/// builds the command line. Plain data, so the rule is testable without a
/// GPU, a Python or a ComfyUI.
#[derive(Debug, Clone, Copy)]
pub(crate) struct CkFacts<'a> {
    /// `std::env::consts::OS` of this build.
    pub os: &'a str,
    /// The start passes `--cpu`.
    pub needs_cpu: bool,
    /// The device flag the start passes besides `--cpu`, today only
    /// `--directml` (process.rs, `comfy_device_flag`).
    pub device_flag: Option<&'a str>,
    /// An NVIDIA driver answers (`needs_cpu_fallback()` is false).
    pub nvidia_driver: bool,
    /// What the environment's torch reports when there is no NVIDIA driver:
    /// `"cuda"` is a ROCm (or ZLUDA) build, `"xpu"` Intel, `"directml"`.
    /// Ignored when `nvidia_driver` is true.
    pub torch_device: Option<&'a str>,
    /// The installed ComfyUI's version, `None` when unreadable.
    pub comfy_version: Option<ComfyVersion>,
    /// `LU_COMFY_NO_CK` is set.
    pub switched_off: bool,
    /// What an earlier start of this folder and version taught us:
    /// `Some(false)` = it died with the flag before the port answered.
    pub remembered: Option<bool>,
}

/// May this start try `--use-ck-attention`? Everything except the import
/// test, which costs a torch import and is therefore asked last and only
/// when this says yes.
pub(crate) fn ck_attention_eligible(f: &CkFacts) -> bool {
    if f.switched_off || f.remembered == Some(false) {
        return false;
    }
    if f.os == "macos" || f.needs_cpu || f.device_flag.is_some() {
        return false;
    }
    let cuda_or_rocm = f.nvidia_driver || f.torch_device == Some("cuda");
    if !cuda_or_rocm {
        return false;
    }
    matches!(f.comfy_version, Some(v) if v >= CK_MIN_VERSION)
}

/// The one attention flag this start passes, or none.
///
/// Both import tests are closures so each runs only when its answer can still
/// change the result: the ck probe only for an eligible start, the flash
/// probe only when ck is not taken. CPU mode passes neither (flash-attn is
/// CUDA-only, and ck is excluded by the eligibility above).
pub(crate) fn pick_attention_flag(
    needs_cpu: bool,
    ck_eligible: bool,
    ck_imports: impl FnOnce() -> bool,
    flash_imports: impl FnOnce() -> bool,
) -> Option<&'static str> {
    if needs_cpu {
        return None;
    }
    if ck_eligible && ck_imports() {
        return Some(CK_FLAG);
    }
    flash_imports().then_some(FLASH_FLAG)
}

/// Is `LU_COMFY_NO_CK` set to something that means yes?
pub(crate) fn ck_switched_off_by_env(value: Option<&str>) -> bool {
    matches!(
        value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),
        Some("1") | Some("true") | Some("yes") | Some("on")
    )
}

/// The process environment's answer to [`ck_switched_off_by_env`].
pub(crate) fn ck_switched_off() -> bool {
    ck_switched_off_by_env(std::env::var(NO_CK_ENV).ok().as_deref())
}

/// Set once a start with the ck flag died before its port answered. The
/// config.json memory below is the lasting record; this is the one that
/// cannot fail, so the retry without the flag never loops back into it, even
/// on a machine whose config folder is read-only.
static CK_FAILED_THIS_RUN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

pub(crate) fn note_ck_failed_this_run() {
    CK_FAILED_THIS_RUN.store(true, std::sync::atomic::Ordering::SeqCst);
}

pub(crate) fn ck_failed_this_run() -> bool {
    CK_FAILED_THIS_RUN.load(std::sync::atomic::Ordering::SeqCst)
}

// ── The import test ─────────────────────────────────────────────────────

/// Per (python, ComfyUI version) cache of DEFINITIVE answers, the same rule
/// as `flash_attention_cached`: a timeout is not cached, so one slow boot does
/// not switch ck off for the session. The version is part of the key because
/// an Update ComfyUI run installs `comfy-kitchen` into the same interpreter.
static CK_PROBE_CACHE: Mutex<Option<HashMap<(String, String), bool>>> = Mutex::new(None);

/// Does `import comfy_kitchen` succeed in `python`? Real import, `-I` so
/// neither the working directory nor PYTHONPATH can put a different module of
/// that name in front. Some(true/false) = the process answered, None =
/// timeout or no spawn.
pub(crate) fn probe_comfy_kitchen(python: &str) -> Option<bool> {
    if python.is_empty() {
        return Some(false);
    }
    let mut cmd = python_command(python);
    cmd.args(["-I", "-c", "import comfy_kitchen"])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    #[cfg(target_os = "windows")]
    cmd.creation_flags(crate::commands::install::CREATE_NO_WINDOW);
    let mut child = cmd.spawn().ok()?;
    // 90 s, the flash probe's ceiling: comfy_kitchen imports torch, which is
    // a few seconds warm and far longer in a boot-time disk storm, while an
    // absent package fails within seconds.
    for _ in 0..450 {
        match child.try_wait() {
            Ok(Some(status)) => return Some(status.success()),
            Ok(None) => std::thread::sleep(std::time::Duration::from_millis(200)),
            Err(_) => return None,
        }
    }
    let _ = child.kill();
    let _ = child.wait();
    None
}

/// [`probe_comfy_kitchen`] with the cache. A timeout reads as "no" for this
/// start only.
pub(crate) fn comfy_kitchen_cached(python: &str, version: Option<ComfyVersion>) -> bool {
    let key = (python.to_string(), version.map(|v| v.to_string()).unwrap_or_default());
    if let Some(v) = CK_PROBE_CACHE.lock().ok().and_then(|c| c.as_ref().and_then(|m| m.get(&key).copied())) {
        return v;
    }
    match probe_comfy_kitchen(python) {
        Some(v) => {
            if let Ok(mut c) = CK_PROBE_CACHE.lock() {
                c.get_or_insert_with(HashMap::new).insert(key, v);
            }
            v
        }
        None => {
            println!("[ComfyUI] comfy_kitchen probe timed out, starting without {CK_FLAG} (will retry next start)");
            false
        }
    }
}

// ── What earlier starts taught us ───────────────────────────────────────

/// The config.json key: `{"comfyui": <folder>, "version": "0.42.4",
/// "works": true|false}`. One entry, the ComfyUI LU starts; a second folder
/// or a new version simply replaces it.
const CK_MEMORY_KEY: &str = "comfyui_ck_attention";

/// What is remembered about the ck flag for exactly this folder and version.
pub(crate) fn remembered_ck_in(config: &Path, comfy_dir: &Path, version: ComfyVersion) -> Option<bool> {
    let json: serde_json::Value = serde_json::from_str(&fs::read_to_string(config).ok()?).ok()?;
    let entry = json.get(CK_MEMORY_KEY)?;
    let folder = entry.get("comfyui")?.as_str()?;
    let stored = entry.get("version")?.as_str()?;
    if Path::new(folder) != comfy_dir || stored != version.to_string() {
        return None;
    }
    entry.get("works")?.as_bool()
}

/// Remember how a start with the ck flag ended. Every other key in the file
/// stays.
pub(crate) fn remember_ck_in(config: &Path, comfy_dir: &Path, version: ComfyVersion, works: bool) {
    if let Some(parent) = config.parent() {
        let _ = fs::create_dir_all(parent);
    }
    let mut json: serde_json::Value = fs::read_to_string(config)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .filter(serde_json::Value::is_object)
        .unwrap_or_else(|| serde_json::json!({}));
    json[CK_MEMORY_KEY] = serde_json::json!({
        "comfyui": comfy_dir.to_string_lossy(),
        "version": version.to_string(),
        "works": works,
    });
    let _ = fs::write(config, serde_json::to_string_pretty(&json).unwrap_or_default());
}

/// How a start with the ck flag that has not proven itself yet ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CkWatch {
    /// The port answered: the flag works with this ComfyUI.
    Proven,
    /// The process exited before the port answered.
    DiedEarly,
    /// Neither within the watch, or the child was taken away (Stop pressed).
    /// Nothing is remembered.
    Undecided,
}

/// How long a first start with the ck flag is watched for its port. The
/// slowest honest start measured is about a minute; custom-node-heavy
/// installs take longer, and an undecided watch costs only that the next
/// start watches again.
pub(crate) const CK_PROOF_WATCH: std::time::Duration = std::time::Duration::from_secs(180);

/// Watch an unproven ck start until it either answers on the port or dies.
///
/// `exited` is asked first on every round and returns `Some(true)` when the
/// child is gone by itself, `Some(false)` while it lives and `None` when the
/// handle is no longer ours to watch. Closures, so the rule is testable
/// without a process or a port.
pub(crate) fn watch_ck_start(
    mut exited: impl FnMut() -> Option<bool>,
    mut port_answers: impl FnMut() -> bool,
    budget: std::time::Duration,
    step: std::time::Duration,
) -> CkWatch {
    let mut waited = std::time::Duration::ZERO;
    loop {
        match exited() {
            Some(true) => return CkWatch::DiedEarly,
            None => return CkWatch::Undecided,
            Some(false) => {}
        }
        if port_answers() {
            return CkWatch::Proven;
        }
        if waited >= budget {
            return CkWatch::Undecided;
        }
        std::thread::sleep(step);
        waited += step;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn nvidia(version: Option<ComfyVersion>) -> CkFacts<'static> {
        CkFacts {
            os: "windows",
            needs_cpu: false,
            device_flag: None,
            nvidia_driver: true,
            torch_device: None,
            comfy_version: version,
            switched_off: false,
            remembered: None,
        }
    }

    #[test]
    fn the_version_file_is_read_in_every_spelling_comfyui_has_used() {
        assert_eq!(parse_comfyui_version("# auto\n__version__ = \"0.42.4\"\n"), Some(ComfyVersion(0, 42, 4)));
        assert_eq!(parse_comfyui_version("__version__='0.32.0'"), Some(ComfyVersion(0, 32, 0)));
        assert_eq!(parse_comfyui_version("__version__ = \"v1.2.3rc1\""), Some(ComfyVersion(1, 2, 3)));
        assert_eq!(parse_comfyui_version("__version__ = \"0.3\""), None, "two numbers are not a version");
        assert_eq!(parse_comfyui_version("version = \"0.42.4\""), None);
        assert_eq!(parse_comfyui_version(""), None);
    }

    #[test]
    fn versions_compare_as_numbers_not_as_text() {
        assert!(ComfyVersion(0, 42, 4) > CK_MIN_VERSION);
        assert!(ComfyVersion(0, 32, 0) >= CK_MIN_VERSION);
        assert!(ComfyVersion(0, 31, 99) < CK_MIN_VERSION);
        // "0.4.0" sorts after "0.32.0" as text and must not here.
        assert!(ComfyVersion(0, 4, 0) < CK_MIN_VERSION);
    }

    #[test]
    fn read_comfyui_version_finds_the_file_in_the_comfy_folder() {
        let tmp = tempfile::tempdir().unwrap();
        assert_eq!(read_comfyui_version(tmp.path()), None);
        fs::write(tmp.path().join("comfyui_version.py"), "__version__ = \"0.42.4\"\n").unwrap();
        assert_eq!(read_comfyui_version(tmp.path()), Some(ComfyVersion(0, 42, 4)));
    }

    #[test]
    fn ck_is_tried_on_nvidia_and_rocm_with_a_new_enough_comfyui() {
        assert!(ck_attention_eligible(&nvidia(Some(ComfyVersion(0, 42, 4)))));
        let rocm = CkFacts { os: "linux", nvidia_driver: false, torch_device: Some("cuda"), ..nvidia(Some(ComfyVersion(0, 32, 0))) };
        assert!(ck_attention_eligible(&rocm));
    }

    #[test]
    fn ck_is_never_tried_where_it_cannot_work() {
        let v = Some(ComfyVersion(0, 42, 4));
        let cases = [
            ("old comfyui", CkFacts { comfy_version: Some(ComfyVersion(0, 31, 9)), ..nvidia(v) }),
            ("unknown version", nvidia(None)),
            ("cpu", CkFacts { needs_cpu: true, ..nvidia(v) }),
            ("directml", CkFacts { nvidia_driver: false, device_flag: Some("--directml"), torch_device: Some("directml"), ..nvidia(v) }),
            ("intel xpu", CkFacts { nvidia_driver: false, torch_device: Some("xpu"), ..nvidia(v) }),
            ("no gpu torch", CkFacts { nvidia_driver: false, torch_device: None, ..nvidia(v) }),
            ("mac", CkFacts { os: "macos", ..nvidia(v) }),
            ("switched off", CkFacts { switched_off: true, ..nvidia(v) }),
            ("died before", CkFacts { remembered: Some(false), ..nvidia(v) }),
        ];
        for (name, facts) in cases {
            assert!(!ck_attention_eligible(&facts), "ck was allowed for: {name}");
        }
        // A start that proved the flag keeps it.
        assert!(ck_attention_eligible(&CkFacts { remembered: Some(true), ..nvidia(v) }));
    }

    #[test]
    fn at_most_one_attention_flag_and_ck_wins() {
        assert_eq!(pick_attention_flag(false, true, || true, || true), Some(CK_FLAG));
        assert_eq!(pick_attention_flag(false, true, || false, || true), Some(FLASH_FLAG));
        assert_eq!(pick_attention_flag(false, false, || true, || true), Some(FLASH_FLAG));
        assert_eq!(pick_attention_flag(false, false, || true, || false), None);
        assert_eq!(pick_attention_flag(true, true, || true, || true), None, "--cpu gets no attention flag");
    }

    #[test]
    fn the_probes_run_only_when_their_answer_matters() {
        // ck taken: the flash probe (a torch import) must not run.
        let flag = pick_attention_flag(false, true, || true, || panic!("flash probed although ck was taken"));
        assert_eq!(flag, Some(CK_FLAG));
        // Not eligible: the ck probe must not run.
        let flag = pick_attention_flag(false, false, || panic!("ck probed although not eligible"), || false);
        assert_eq!(flag, None);
        // CPU: neither.
        let flag = pick_attention_flag(true, true, || panic!("ck probed under --cpu"), || panic!("flash probed under --cpu"));
        assert_eq!(flag, None);
    }

    #[test]
    fn the_env_switch_reads_the_usual_yes_values() {
        for yes in ["1", "true", "YES", " on "] {
            assert!(ck_switched_off_by_env(Some(yes)), "{yes}");
        }
        for no in ["0", "", "false", "nope"] {
            assert!(!ck_switched_off_by_env(Some(no)), "{no}");
        }
        assert!(!ck_switched_off_by_env(None));
    }

    #[test]
    fn the_memory_is_per_folder_and_version_and_keeps_other_keys() {
        let tmp = tempfile::tempdir().unwrap();
        let config = tmp.path().join("cfg").join("config.json");
        let dir = tmp.path().join("ComfyUI");
        let v = ComfyVersion(0, 42, 4);
        assert_eq!(remembered_ck_in(&config, &dir, v), None);

        fs::create_dir_all(config.parent().unwrap()).unwrap();
        fs::write(&config, r#"{"comfyui_path": "X"}"#).unwrap();
        remember_ck_in(&config, &dir, v, false);
        assert_eq!(remembered_ck_in(&config, &dir, v), Some(false));
        let json: serde_json::Value = serde_json::from_str(&fs::read_to_string(&config).unwrap()).unwrap();
        assert_eq!(json["comfyui_path"], "X", "another key was lost");

        // A new ComfyUI version gets a fresh try, another folder too.
        assert_eq!(remembered_ck_in(&config, &dir, ComfyVersion(0, 43, 0)), None);
        assert_eq!(remembered_ck_in(&config, &tmp.path().join("Other"), v), None);

        remember_ck_in(&config, &dir, v, true);
        assert_eq!(remembered_ck_in(&config, &dir, v), Some(true));
    }

    #[test]
    fn the_watch_tells_a_crash_from_a_start() {
        let step = std::time::Duration::ZERO;
        let budget = std::time::Duration::from_millis(1);
        // Dies on the third look, port never answers.
        let mut n = 0;
        let died = watch_ck_start(|| { n += 1; Some(n >= 3) }, || false, std::time::Duration::from_secs(5), step);
        assert_eq!(died, CkWatch::DiedEarly);
        // Port answers while alive.
        let mut m = 0;
        let up = watch_ck_start(|| Some(false), || { m += 1; m >= 2 }, std::time::Duration::from_secs(5), step);
        assert_eq!(up, CkWatch::Proven);
        // Stop took the child: nothing is decided.
        assert_eq!(watch_ck_start(|| None, || false, budget, step), CkWatch::Undecided);
        // Alive, silent, out of time.
        let slow = watch_ck_start(|| Some(false), || false, budget, std::time::Duration::from_millis(1));
        assert_eq!(slow, CkWatch::Undecided);
    }
}