Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Fix black band on z-image-turbo outputs by gating VAE tiling
Adam Eivy4e80402a6b7b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b3d7ea088a..b658fe395d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,7 @@## Fixed+- **Local image gen: fixed a black band at the bottom of Z-Image-Turbo (and other diffusers-runner) outputs.** The shared runner helper unconditionally enabled VAE *tiling*, whose overlap-blend leaves a seam / dark strip at a content-dependent point near the bottom of the image — most visible at tall aspect ratios like 576×1024 (9:16). Tiling only saves memory on very large decodes and the small-to-mid resolutions PortOS renders never need it (the same reason both runners already disable tiling for image-to-image). VAE tiling is now applied only above a ~6.5 MP area floor that no standard or experimental preset reaches, so ordinary renders decode in one clean pass; pathologically large custom dimensions still get tiling as an out-of-memory safety valve. VAE slicing and attention slicing (which never affect spatial layout) stay on for every render.- **AI Providers warns before enabling the Grok Build CLI/TUI.** The Grok harness uploads your entire working repo to xAI (GCP) as it works. A callout now appears both on the `grok-cli` / `grok-tui` provider cards and in the create/edit form (when the command is `grok`) — before you enable it — telling you to add `[harness]` / `disable_codebase_upload = true` to `~/.grok/config.toml` to keep your code local. The plain `grok` API provider — which doesn't run the harness — is intentionally excluded.- **Layered Intelligence no longer wedges on a stale API-only provider.** Any install that ran the Layered Intelligence loop on an api provider (ollama/lmstudio/kimi) before it became agent-backed (#2322) had that provider carried into the per-app override by migration 184 — where it now outranks the global Schedule pin at spawn. The agent-backed loop needs a file-writing CLI/TUI harness, so those runs skipped with "the selected provider is an API-only model with no coding harness," and picking a CLI/TUI provider on the global Schedule page silently missed (it only sets the fallback pin). The loop now self-heals: an api-only per-app provider falls back to a CLI/TUI schedule pin (adopting its matched model), so the Schedule-page selection finally takes effect. It still skips with the actionable message only when no CLI/TUI provider is configured anywhere.- **Layered Intelligence no longer silently drops a proposal when a local model's JSON is slightly malformed.** A reasoning run pinned to a smaller/local model (e.g. Ollama qwen) would find a real gap, then write an almost-valid `.agent-done` envelope — wrapped in ```json fences, trailed by prose, or with literal newlines/tabs pasted into the long markdown body — that the strict sentinel parser rejected, recording "unparseable-response" and filing nothing. The completion chokepoint now falls back to the shared robust LLM-JSON extractor (strips fences, walks balanced blocks, escapes raw control chars) to recover the envelope's payload before giving up, so the proposal still gets filed as a tracker issue. The shared `jsonExtract` repair also gained a raw-control-char pass that benefits every LLM-JSON caller, and the reasoner's finish instructions now spell out "raw JSON only, no fences, escape newlines."diff --git a/scripts/_runner_common.py b/scripts/_runner_common.pyindex 2e602d3f61..cb4638e044 100644--- a/scripts/_runner_common.py+++ b/scripts/_runner_common.py@@ -241,19 +241,64 @@ def make_generator(device: str, seed: int) -> "torch.Generator":return torch.Generator().manual_seed(int(seed))-def apply_memory_optimizations(pipe) -> None:- """Enable every memory-saving knob diffusers exposes on the loaded- pipeline. Best-effort: each call is gated on hasattr so older / smaller- pipelines that don't ship a given slice / tile path still work."""+# VAE *tiling* is a memory optimization for very large decodes: it splits a+# single image's latent into overlapping spatial tiles, decodes each, and+# blends the overlaps. That blend leaves visible seams / dark bands on the+# small-to-mid resolutions PortOS actually renders — the same reason both+# runners already disable tiling on their i2i paths ("tiled encode of a small+# image produces seams"). At these sizes tiling buys no memory (the VAE decode+# is a rounding error next to the ~20 GB transformer), so only turn it on above+# an area floor no standard/experimental preset reaches. VAE-decode peak memory+# scales with output *area*, so the floor is in total pixels, not edge length:+# the largest preset that routes through these native runners is Qwen's+# experimental 1328×2048 (~2.7 MP), and the image-gen route caps a single edge+# at 3840 (so a 3840² custom render is ~14.7 MP and genuinely wants tiling to+# avoid an OOM on decode). ~6.5 MP sits between the two. VAE *slicing* (batch-dim+# split, no-op at batch 1) and attention slicing never touch spatial layout, so+# they stay unconditional.+_VAE_TILING_MIN_PIXELS = 2560 * 2560 # ~6.5 MP+++def set_vae_tiling(pipe, enabled: bool) -> None:+ """Toggle VAE tiling on a loaded pipeline, preferring the pipeline-level+ switch and falling back to the VAE's own. Best-effort (gated on hasattr) so+ pipelines that expose neither still work. Shared by the txt2img size gate in+ `apply_memory_optimizations` and the runners' i2i paths, which force tiling+ off unconditionally (tiled encode of a small init image seams regardless of+ output size)."""+ pipe_attr = "enable_vae_tiling" if enabled else "disable_vae_tiling"+ vae_attr = "enable_tiling" if enabled else "disable_tiling"+ if hasattr(pipe, pipe_attr):+ getattr(pipe, pipe_attr)()+ return+ vae = getattr(pipe, "vae", None)+ if vae is not None and hasattr(vae, vae_attr):+ getattr(vae, vae_attr)()+++def apply_memory_optimizations(pipe, width=None, height=None) -> None:+ """Enable memory-saving knobs on the loaded pipeline. Best-effort: each+ call is gated on hasattr so older / smaller pipelines that don't ship a+ given slice / tile path still work.++ Attention slicing and VAE slicing are always safe and always applied. VAE+ *tiling* is applied only when the target render is large enough to need it+ (total pixels > `_VAE_TILING_MIN_PIXELS`); below that it is explicitly+ disabled to avoid tile-seam / black-band artifacts (issue: z-image-turbo+ 576×1024 renders showed a black strip at a content-dependent point near the+ bottom). When `width`/`height` are omitted the old always-tile behavior is+ preserved for back-compat."""if hasattr(pipe, "enable_attention_slicing"):pipe.enable_attention_slicing()if hasattr(pipe, "enable_vae_slicing"):pipe.enable_vae_slicing()- vae = getattr(pipe, "vae", None)- if hasattr(pipe, "enable_vae_tiling"):- pipe.enable_vae_tiling()- elif vae is not None and hasattr(vae, "enable_tiling"):- vae.enable_tiling()++ # A diffusers default or a reused pipeline could leave tiling enabled, so+ # drive it explicitly in both directions rather than only turning it on.+ want_tiling = True+ if width and height:+ want_tiling = (int(width) * int(height)) > _VAE_TILING_MIN_PIXELS+ set_vae_tiling(pipe, want_tiling)# Headroom reserved on top of the resident weights for activations + allocatordiff --git a/scripts/_runner_common_test.py b/scripts/_runner_common_test.pynew file mode 100644index 0000000000..0255d15dd5--- /dev/null+++ b/scripts/_runner_common_test.py@@ -0,0 +1,160 @@+#!/usr/bin/env python3+"""Standalone tests for _runner_common.py pure helpers (no pytest, no torch).++Run: ./data/python/venv/bin/python scripts/_runner_common_test.py+(or any python3 — the helpers under test defer the torch/PIL imports).+Exits non-zero on first failure. Mirrors the runnable-test style of+scripts/train_mflux_lora_test.py.+"""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _runner_common import ( # noqa: E402+ apply_memory_optimizations,+ set_vae_tiling,+ _VAE_TILING_MIN_PIXELS,+)++FAILS = []+++def check(name, cond):+ print(("✅" if cond else "❌") + " " + name)+ if not cond:+ FAILS.append(name)+++class _PipeRecorder:+ """Modern pipeline: exposes the pipe-level tiling toggles and the slicing+ knobs, records every call. `vae=None` so the pipe-level path wins."""++ vae = None++ def __init__(self):+ self.calls = []++ def enable_attention_slicing(self):+ self.calls.append("attention_slicing")++ def enable_vae_slicing(self):+ self.calls.append("vae_slicing")++ def enable_vae_tiling(self):+ self.calls.append("enable_vae_tiling")++ def disable_vae_tiling(self):+ self.calls.append("disable_vae_tiling")+++class _Vae:+ def __init__(self, calls):+ self._calls = calls++ def enable_tiling(self):+ self._calls.append("vae.enable_tiling")++ def disable_tiling(self):+ self._calls.append("vae.disable_tiling")+++class _VaeSurfaceRecorder:+ """Older pipeline: no pipe-level tiling toggles, only the VAE's own — so+ apply_memory_optimizations must fall back to vae.enable/disable_tiling."""++ def __init__(self):+ self.calls = []+ self.vae = _Vae(self.calls)++ def enable_attention_slicing(self):+ self.calls.append("attention_slicing")++ def enable_vae_slicing(self):+ self.calls.append("vae_slicing")+++class _BareRecorder:+ """Pipeline with no tiling surface at all (and no vae) — must not crash."""++ vae = None++ def __init__(self):+ self.calls = []++ def enable_attention_slicing(self):+ self.calls.append("attention_slicing")++ def enable_vae_slicing(self):+ self.calls.append("vae_slicing")+++# --- slicing is always applied regardless of size ---------------------------+p = _PipeRecorder()+apply_memory_optimizations(p, width=576, height=1024)+check("attention slicing always applied", "attention_slicing" in p.calls)+check("vae slicing always applied", "vae_slicing" in p.calls)++# --- small render (the z-image 576×1024 bug case) → tiling OFF ---------------+p = _PipeRecorder()+apply_memory_optimizations(p, width=576, height=1024)+check("576×1024 does NOT enable tiling", "enable_vae_tiling" not in p.calls)+check("576×1024 explicitly disables tiling", "disable_vae_tiling" in p.calls)++# largest native-runner preset (Qwen experimental) stays untiled+p = _PipeRecorder()+apply_memory_optimizations(p, width=1328, height=2048)+check("1328×2048 (largest preset) does NOT enable tiling", "enable_vae_tiling" not in p.calls)++# --- large render → tiling ON ------------------------------------------------+p = _PipeRecorder()+apply_memory_optimizations(p, width=3840, height=3840)+check("3840×3840 enables tiling", "enable_vae_tiling" in p.calls)+check("3840×3840 does NOT disable tiling", "disable_vae_tiling" not in p.calls)+check(" ...and 3840×3840 is over the area floor", 3840 * 3840 > _VAE_TILING_MIN_PIXELS)++# just under vs just over the area floor+p = _PipeRecorder()+apply_memory_optimizations(p, width=2560, height=2560) # == floor, not over+check("area == floor does NOT enable tiling", "enable_vae_tiling" not in p.calls)++# --- back-compat: no dims → tiling stays ON (old behavior) -------------------+p = _PipeRecorder()+apply_memory_optimizations(p)+check("no width/height → tiling stays ON (back-compat)", "enable_vae_tiling" in p.calls)++# --- older vae-level toggle path (no pipe-level enable_vae_tiling) -----------+p = _VaeSurfaceRecorder()+apply_memory_optimizations(p, width=576, height=1024)+check("vae-surface small render disables via vae.disable_tiling", "vae.disable_tiling" in p.calls)+check("vae-surface small render does NOT enable via vae.enable_tiling", "vae.enable_tiling" not in p.calls)++p = _VaeSurfaceRecorder()+apply_memory_optimizations(p, width=3840, height=3840)+check("vae-surface large render enables via vae.enable_tiling", "vae.enable_tiling" in p.calls)++# --- pipeline with no tiling surface at all → no crash -----------------------+p = _BareRecorder()+apply_memory_optimizations(p, width=576, height=1024)+check("no tiling surface → slicing still applied, no crash", p.calls == ["attention_slicing", "vae_slicing"])++# --- set_vae_tiling directly (shared by the i2i paths) -----------------------+p = _PipeRecorder()+set_vae_tiling(p, False)+check("set_vae_tiling(False) prefers pipe-level disable", p.calls == ["disable_vae_tiling"])+p = _PipeRecorder()+set_vae_tiling(p, True)+check("set_vae_tiling(True) prefers pipe-level enable", p.calls == ["enable_vae_tiling"])+p = _VaeSurfaceRecorder()+set_vae_tiling(p, False)+check("set_vae_tiling(False) falls back to vae.disable_tiling", p.calls == ["vae.disable_tiling"])+p = _BareRecorder()+set_vae_tiling(p, False)+check("set_vae_tiling on bare pipe is a no-op (no crash)", p.calls == [])+++if FAILS:+ print(f"\n❌ {len(FAILS)} test(s) failed:")+ for f in FAILS:+ print(f" - {f}")+ sys.exit(1)+print("\n✅ all _runner_common tests passed")diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.pyindex a1016d5d8a..1ec34d5c9e 100755--- a/scripts/flux2_macos.py+++ b/scripts/flux2_macos.py@@ -42,6 +42,7 @@ from _runner_common import ( # noqa: E402make_generator,make_stepwise_callback,pick_device,+ set_vae_tiling,suppress_cosmetic_clip_truncation,write_sidecar,)@@ -430,7 +431,7 @@ def main() -> None:sys.exit(64)suppress_cosmetic_clip_truncation()- apply_memory_optimizations(pipe)+ apply_memory_optimizations(pipe, width=args.width, height=args.height)apply_loras(pipe, args.lora_paths or [], args.lora_scales or [])seed = args.seed if args.seed is not None else int(torch.randint(0, 2**31 - 1, (1,)).item())@@ -504,16 +505,14 @@ def main() -> None:# K/V-cache code path. The signature filter above guarantees the kwarg# is supported by the live pipeline.pipe_kwargs["image"] = reference_pils- vae = getattr(pipe, "vae", None)- if vae is not None and hasattr(vae, "disable_tiling"):- vae.disable_tiling()+ # Reference-conditioned decode: disable VAE tiling for the same reason+ # as i2i below (tiled encode of the reference images seams).+ set_vae_tiling(pipe, False)elif init_image is not None and "image" in accepted:pipe_kwargs["image"] = init_image# Disable VAE tiling for i2i — tiled encode of a small image# produces seams on the output (matches the reference impl).- vae = getattr(pipe, "vae", None)- if vae is not None and hasattr(vae, "disable_tiling"):- vae.disable_tiling()+ set_vae_tiling(pipe, False)if args.image_strength is not None and "strength" in accepted:pipe_kwargs["strength"] = float(args.image_strength)diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.pyindex a421c6e91d..0dbcc3b116 100644--- a/scripts/z_image_turbo.py+++ b/scripts/z_image_turbo.py@@ -39,6 +39,7 @@ from _runner_common import ( # noqa: E402make_stepwise_callback,pick_device,place_pipeline,+ set_vae_tiling,suppress_cosmetic_clip_truncation,write_sidecar,)@@ -244,7 +245,7 @@ def main() -> None:)init_image = None- apply_memory_optimizations(pipe)+ apply_memory_optimizations(pipe, width=args.width, height=args.height)apply_loras(pipe, args.lora_paths or [], args.lora_scales or [])seed = args.seed if args.seed is not None else int(torch.randint(0, 2**31 - 1, (1,)).item())@@ -331,9 +332,7 @@ def main() -> None:pipe_kwargs["image"] = init_image# Disable VAE tiling for i2i — tiled encode of a small image# produces seams on the output (matches flux2 reference).- vae = getattr(pipe, "vae", None)- if vae is not None and hasattr(vae, "disable_tiling"):- vae.disable_tiling()+ set_vae_tiling(pipe, False)if args.image_strength is not None and "strength" in accepted:pipe_kwargs["strength"] = float(args.image_strength)# ERNIE-Image's prompt enhancer — only pass when the loaded pipeline