Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.
TypeScript ai-photo-editorcomfyui-alternativegenerative-fillimage-editingimage-generationinpaintinglinuxlocal-aimacosmcpmcp-servernano-banana-alternativeofflinephoto-editorprivacyqwen-imageqwen-image-2-1stable-diffusion-cppvulkanwindows
Calibrate time estimates on the user's machine
Gabriele Lozupone0a1c1c41b314
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rsindex 3d8c015..5000b44 100644--- a/crates/qls-core/src/engine.rs+++ b/crates/qls-core/src/engine.rs@@ -91,6 +91,8 @@ pub struct Engine {/// Private mode: records in memory, files under `private_dir`; wiped by `clear_private`,/// at start and at exit. Never listed in the gallery.pub private_store: Arc<Store>,+ /// Measured speed of this machine, for time estimates.+ speed: crate::speed::SpeedBook,private_dir: PathBuf,jobs: Mutex<HashMap<String, Job>>,order: Mutex<VecDeque<String>>,@@ -124,7 +126,9 @@ pub fn plan_inputs(cfg: &AppConfig, image_sizes: Vec<Size>, mask: Option<(Size,upscaler: cfg.upscaler_file().map(|_| cfg.upscaler_model.trim().to_string()),refine: cfg.refine_mode,server_vae_tiling: cfg.vae_tile_size > 0,- sage_attention: cfg.sage_attention,+ sage_attention: cfg.uses_sage_attention(),+ speed_factor: None,+ hide_uncalibrated: !crate::speed::trust_uncalibrated(cfg),}}@@ -144,6 +148,7 @@ impl Engine {server: ServerManager::new(data_dir.to_path_buf()),store,private_store,+ speed: if cfg!(test) { crate::speed::SpeedBook::in_memory() } else { crate::speed::SpeedBook::open(data_dir) },private_dir,jobs: Mutex::new(HashMap::new()),order: Mutex::new(VecDeque::new()),@@ -459,11 +464,18 @@ impl Engine {Ok((img, rec))}+ /// How this machine's measured speed compares with the time model (None: not measured).+ fn speed_factor(&self, cfg: &AppConfig) -> Option<f32> {+ self.speed.get(&crate::speed::machine_key(cfg, self.gpu().as_ref())).map(|c| c.factor)+ }+/// Dry run: the plan a request would get (used by the UI to show working sizes).pub fn preview_plan(&self, req: &GenerationRequest, sizes: Vec<Size>, mask: Option<(Size, Option<crate::geometry::Rect>, f64)>) -> AppResult<Plan> {let cfg = self.config();let vram = cfg.planning_vram_mib(self.gpu().map(|g| g.planning_mib()));- planner::plan(req, &plan_inputs(&cfg, sizes, mask, vram), &cfg.profile().recommended_settings)+ let mut inputs = plan_inputs(&cfg, sizes, mask, vram);+ inputs.speed_factor = self.speed_factor(&cfg);+ planner::plan(req, &inputs, &cfg.profile().recommended_settings)}async fn run_job(self: Arc<Self>, id: &str) -> AppResult<()> {@@ -509,7 +521,8 @@ impl Engine {let profile = cfg.profile().clone();let vram = cfg.planning_vram_mib(self.gpu().map(|g| g.planning_mib()));let mask_info = mask.as_ref().map(|(m, _)| (Size::new(m.width(), m.height()), imaging::mask_bbox(m, 16), imaging::mask_coverage(m, 16)));- let plan_inputs = plan_inputs(&cfg, images.iter().map(|i| i.size()).collect(), mask_info, vram);+ let mut plan_inputs = plan_inputs(&cfg, images.iter().map(|i| i.size()).collect(), mask_info, vram);+ plan_inputs.speed_factor = self.speed_factor(&cfg);let plan = planner::plan(&request, &plan_inputs, &profile.recommended_settings)?;let seed = request.seed.unwrap_or_else(random_seed);let mut request = request;@@ -523,7 +536,10 @@ impl Engine {});// 3. Backend.+ // A job that also starts the server is not a fair speed sample (startup, first load).+ let mut cold_start = false;if self.server.status().state != ServerState::Ready || self.server.owned_alive() == Some(false) {+ cold_start = true;self.update(id, |j| j.view.status = JobStatus::StartingBackend);self.emit_server();let r = self.server.ensure_ready(&cfg).await;@@ -592,6 +608,7 @@ impl Engine {// 5. Submit and follow.let mut lines = self.server.subscribe_lines();let detailed = self.server.status().owned;+ let submitted = Instant::now();let accepted = client.submit(&sd_req).await?;drop(sd_req); // release the base64 payloadsself.update(id, |j| {@@ -661,6 +678,13 @@ impl Engine {return self.maybe_retry_oom(id, err).await;}}+ if !cold_start {+ let key = crate::speed::machine_key(&cfg, self.gpu().as_ref());+ let predicted = planner::backend_seconds(&plan, cfg.uses_sage_attention());+ if let Some(f) = self.speed.record(&key, submitted.elapsed().as_secs_f32(), predicted) {+ tracing::info!("speed calibration {key}: x{f:.2}");+ }+ }let result = backend_job.result.unwrap_or_default();if result.images.is_empty() {return Err(AppError::new(ErrorCode::GenerationFailed, "The inference server returned no image."));diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rsindex 98bdaf4..730a26c 100644--- a/crates/qls-core/src/lib.rs+++ b/crates/qls-core/src/lib.rs@@ -13,5 +13,6 @@ pub mod pipeline;pub mod planner;pub mod process;pub mod sdcpp;+pub mod speed;pub mod store;pub mod wic;diff --git a/crates/qls-core/src/planner.rs b/crates/qls-core/src/planner.rsindex e496162..09c0f9b 100644--- a/crates/qls-core/src/planner.rs+++ b/crates/qls-core/src/planner.rs@@ -338,6 +338,11 @@ pub struct PlanInputs {pub server_vae_tiling: bool,/// SageAttention is enabled (faster steps; used for estimates only).pub sage_attention: bool,+ /// Measured speed of this machine relative to the time model (`crate::speed`).+ pub speed_factor: Option<f32>,+ /// Without a measurement, report `estimated_seconds` = 0 (unknown until the first image)+ /// instead of the uncalibrated model, which only fits the hardware it was measured on.+ pub hide_uncalibrated: bool,}// ---------------------------------------------------------------------------------------@@ -573,6 +578,14 @@ pub fn estimate_seconds(working: Size, refs: &[RefPlan], steps: u32, batch: u32,(t + decode_seconds(working.area())) * batch as f32}+/// Uncalibrated prediction of the backend part of a planned job (what `crate::speed`+/// compares with the measured time): encode, sampling and decode, no enlargement.+pub fn backend_seconds(p: &Plan, sage: bool) -> f32 {+ let detailed = p.upscale.map(|u| u.method == UpscaleMethod::Detailed).unwrap_or(false);+ let steps = if detailed { (p.steps as f32 * p.strength.unwrap_or(1.0)).ceil() as u32 } else { p.steps };+ estimate_seconds(p.working, &p.references, steps, p.batch_count, p.cache_threshold.is_some(), sage, p.cfg)+}+fn steps_for(q: Quality, rec: &RecommendedSettings) -> u32 {match q {Quality::Fast => rec.steps_fast,@@ -939,6 +952,11 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSettiestimated_seconds += esrgan_seconds(inputs.image_sizes[0].area());}}+ estimated_seconds = match inputs.speed_factor {+ Some(f) => estimated_seconds * f,+ None if inputs.hide_uncalibrated => 0.0,+ None => estimated_seconds,+ };let negative_prompt = req.negative_prompt.clone().unwrap_or_else(|| rec.negative_prompt.clone());if !negative_prompt.trim().is_empty() && !uses_guidance(cfg) && !quick_upscale {notes.push("The negative prompt is ignored at CFG 1; raise CFG in Advanced to use it.".into());@@ -978,6 +996,22 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti#[cfg(test)]mod tests {+ #[test]+ fn estimates_follow_the_measured_speed() {+ let r = GenerationRequest { prompt: "a lighthouse at dusk".into(), ..Default::default() };+ let base = PlanInputs { vram_total_mib: Some(16303), ..Default::default() };+ let raw = plan(&r, &base, &RecommendedSettings::default()).unwrap().estimated_seconds;+ assert!(raw > 0.0);+ let slow = PlanInputs { speed_factor: Some(13.0), ..base.clone() };+ let s = plan(&r, &slow, &RecommendedSettings::default()).unwrap();+ assert!((s.estimated_seconds / raw - 13.0).abs() < 0.01);+ assert!((backend_seconds(&s, false) - raw).abs() < 0.5, "the calibration compares against the uncalibrated backend time");+ let unknown = PlanInputs { hide_uncalibrated: true, ..base.clone() };+ assert_eq!(plan(&r, &unknown, &RecommendedSettings::default()).unwrap().estimated_seconds, 0.0, "unknown until measured");+ let known = PlanInputs { hide_uncalibrated: true, speed_factor: Some(2.0), ..base };+ assert!(plan(&r, &known, &RecommendedSettings::default()).unwrap().estimated_seconds > 0.0);+ }+#[test]fn unified_memory_maps_to_presets() {use crate::catalog::{TEXT_ENCODER_Q4_K_M, VISION_PROJECTOR, recommended_preset};diff --git a/crates/qls-core/src/speed.rs b/crates/qls-core/src/speed.rsnew file mode 100644index 0000000..4806110--- /dev/null+++ b/crates/qls-core/src/speed.rs@@ -0,0 +1,117 @@+//! Per-machine speed calibration for time estimates.+//!+//! The planner's time model was measured on one RTX 5070 Ti; other GPUs, engines and memory+//! modes can be 10x off (a 512² image on an M2 Pro took ~2 min against a ~9 s estimate).+//! After every finished image the measured backend time is compared with the uncalibrated+//! prediction, and the ratio (geometric moving average) scales later estimates on the same+//! machine. Stored in `<data>/speed.json`; nothing leaves the PC.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::Mutex;++use serde::{Deserialize, Serialize};++use crate::config::{AppConfig, GpuBackend};+use crate::diagnostics::GpuInfo;++/// Weight of the newest measurement. High enough that one image corrects a wrong prior,+/// low enough that one outlier (a cold SSD, another app on the GPU) does not dominate.+const NEW_WEIGHT: f32 = 0.5;++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]+pub struct Calibration {+ /// measured / predicted.+ pub factor: f32,+ pub samples: u32,+}++pub struct SpeedBook {+ path: Option<PathBuf>,+ entries: Mutex<HashMap<String, Calibration>>,+}++impl SpeedBook {+ /// Loads `<data_dir>/speed.json` (missing or unreadable: starts empty).+ pub fn open(data_dir: &Path) -> Self {+ let path = data_dir.join("speed.json");+ let entries = std::fs::read_to_string(&path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();+ Self { path: Some(path), entries: Mutex::new(entries) }+ }++ /// Not persisted (tests, private use).+ pub fn in_memory() -> Self {+ Self { path: None, entries: Mutex::new(HashMap::new()) }+ }++ pub fn get(&self, key: &str) -> Option<Calibration> {+ self.entries.lock().unwrap().get(key).copied()+ }++ /// Records one finished job; returns the updated factor. Ignores nonsense values.+ pub fn record(&self, key: &str, measured_s: f32, predicted_s: f32) -> Option<f32> {+ if !(measured_s.is_finite() && predicted_s.is_finite()) || measured_s <= 0.5 || predicted_s <= 0.0 {+ return None;+ }+ let ratio = (measured_s / predicted_s).clamp(0.05, 200.0);+ let mut map = self.entries.lock().unwrap();+ let e = map.entry(key.to_string()).or_insert(Calibration { factor: ratio, samples: 0 });+ if e.samples > 0 {+ e.factor = (e.factor.ln() * (1.0 - NEW_WEIGHT) + ratio.ln() * NEW_WEIGHT).exp();+ }+ e.samples += 1;+ let factor = e.factor;+ if let Some(p) = &self.path {+ if let Ok(json) = serde_json::to_string_pretty(&*map) {+ let _ = std::fs::write(p, json);+ }+ }+ Some(factor)+ }+}++/// What makes timings comparable: engine, GPU and how the weights are held.+pub fn machine_key(cfg: &AppConfig, gpu: Option<&GpuInfo>) -> String {+ let gpu = gpu.map(|g| g.name.as_str()).unwrap_or("unknown GPU");+ format!("{}|{}|{:?}|sage={}", cfg.gpu_backend.device_prefix(), gpu, cfg.text_encoder_placement, cfg.uses_sage_attention())+}++/// Whether the uncalibrated model is close enough to show before the first measurement:+/// only for the hardware it was measured on (NVIDIA through CUDA).+pub fn trust_uncalibrated(cfg: &AppConfig) -> bool {+ cfg.gpu_backend == GpuBackend::Cuda+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn learns_and_smooths() {+ let b = SpeedBook::in_memory();+ assert_eq!(b.get("m"), None);+ // M2 Pro case: ~120 s measured against a 9 s prediction.+ let f = b.record("m", 120.0, 9.0).unwrap();+ assert!((f - 13.33).abs() < 0.1, "the first image sets the factor: {f}");+ // An outlier only moves it halfway (geometrically).+ let f2 = b.record("m", 240.0, 9.0).unwrap();+ assert!(f2 > 13.4 && f2 < 26.0, "{f2}");+ assert_eq!(b.get("m").unwrap().samples, 2);+ assert_eq!(b.record("m", f32::NAN, 9.0), None);+ assert_eq!(b.record("m", 0.1, 9.0), None, "too short to be a real job");+ }++ #[test]+ fn persists_and_keys_by_machine() {+ let dir = tempfile::tempdir().unwrap();+ SpeedBook::open(dir.path()).record("k", 30.0, 10.0);+ assert_eq!(SpeedBook::open(dir.path()).get("k").map(|c| c.factor), Some(3.0));+ let mut cfg = AppConfig::default();+ cfg.gpu_backend = GpuBackend::Cuda;+ let gpu = GpuInfo { name: "NVIDIA GeForce RTX 5070".into(), ..Default::default() };+ let a = machine_key(&cfg, Some(&gpu));+ cfg.gpu_backend = GpuBackend::Vulkan;+ assert_ne!(a, machine_key(&cfg, Some(&gpu)), "engines are calibrated separately");+ assert!(!trust_uncalibrated(&cfg));+ }+}diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex 6314c59..9003b14 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -314,7 +314,9 @@ export function Composer() {const hint = (() => {if (error) return error;if (!plan) return "";- return `${plan.output.width}×${plan.output.height} · ~${formatDuration(plan.estimated_seconds)}`;+ // 0 = this machine's speed is not measured yet (the first image measures it).+ const time = plan.estimated_seconds > 0 ? `~${formatDuration(plan.estimated_seconds)}` : "time known after the first image";+ return `${plan.output.width}×${plan.output.height} · ${time}`;})();const hintTitle = plan? [diff --git a/src/lib/types.ts b/src/lib/types.tsindex 531900e..58abf44 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -79,6 +79,7 @@ export interface Plan {aspect_label: string;notes: string[];optimized_for_vram: boolean;+ /** Calibrated to this machine after its first image; 0 = not measured yet. */estimated_seconds: number;cache_threshold: number | null;upscaler: string | null;