Skip to content

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

fix: make Windows local image-gen fast + fix the FLUX.2 venv installer

[._.]/ Adam Eivy595b95def795
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index eb75668c31..d30436a814 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -37,6 +37,7 @@
- **[issue-737] Keyframe-interpolation video is smoother on high-memory Macs** — When you interpolate a video between two keyframes, the result no longer stutters on machines with plenty of memory. The clip-length cap that governs motion quality used to be pinned to a conservative 48 GB-safe value, which on any machine clamped interpolated clips so short that motion advanced in juddery near-duplicate pairs. That cap now scales with your Mac's unified memory — a 128 GB machine renders the longer clips needed for smooth motion out of the box, while machines with 64 GB or less behave exactly as before. You can still override it with the `FFLF_LTX2_PIXEL_BUDGET` setting.
- **[issue-915] Chief of Staff dry-run preview now matches what would really run** — In Dry-run autonomy mode, the "would spawn" preview for auto-run system tasks now lists only the tasks the Chief of Staff would actually start — accounting for free agent slots, retry limits, app cooldowns, and per-app caps — instead of every queued task regardless of whether it could run. The preview is now a faithful plan of the next pass.
+- **Local image generation no longer thrashes VRAM on large diffusers models (Windows/CUDA)** — The shared diffusers runner behind Z-Image-Turbo, ERNIE, HiDream, and Qwen loaded a model's full weights onto the GPU at once. The big bf16 pipelines are ~19–20 GB, which on a 24 GB card leaves no room for the forward pass's activations — and on Windows the NVIDIA driver answers the overflow with silent "system memory fallback" (spilling to host RAM over PCIe) instead of an out-of-memory error, so every denoising step ran ~50× slower than the GPU is capable of. A single 1024px Z-Image-Turbo image took **35 minutes**. The runner now measures each pipeline's weight footprint and, when it would fill most of the card, switches to diffusers' model CPU offload — keeping only the active component resident (the transformer stays on the GPU across the whole denoising loop while the text encoder and VAE are paged in just for their one-shot pass). The same image now renders in **~1.5 minutes** with live step previews intact, and peak VRAM drops from ~21 GB to ~13 GB. Small models (SD-1.5, SDXL) keep the faster full-residency path. The stepwise live-preview decode is fixed to target the VAE's execution device so previews still render under offload. Override the heuristic with `PORTOS_IMAGE_OFFLOAD=1` (force offload) or `PORTOS_IMAGE_OFFLOAD=0` (force full residency).
- **[issue-934] City archive district no longer overlaps the AI Core on sparse installs** — On installs with few or no active apps, the archived-apps "warehouse" district (and its ARCHIVE DISTRICT sign) sat right on top of the central AI Core landmark — most visibly on an all-archived install with no active apps, where the sign landed on the monument. The district is now floored to always sit clear of the core. Installs with several active apps are unaffected — their layout is unchanged.
- **[issue-894] Numeric edge-case hardening** — Task-learning duration stats can no longer go negative when resetting a task type against an older or hand-edited store, goal velocity reports no trend (instead of a garbage value) when a progress entry has a malformed date, and a stray non-numeric music gain falls back to the default instead of breaking an audio render.
- **Federated peers with PortOS password auth now connect** — If a remote PortOS instance has its built-in password enabled (Settings → Security), peer probes were always returning 401 even with the correct credential set in the Instances UI. The root cause: PortOS's auth gate only accepted session cookies and `Authorization: Bearer` tokens; peer probes send `Authorization: Basic <base64>`, which was silently ignored. The auth gate now also validates HTTP Basic credentials against the stored password hash, so federated probes, syncs, and the live socket relay all authenticate correctly. The backoff-reset fix is bundled: if a peer was deep in exponential backoff (up to 24 h) from prior 401 failures, re-saving the credential in the Instances UI immediately clears the backoff and re-probes without waiting.
diff --git a/scripts/_runner_common.py b/scripts/_runner_common.py
index f9408398d2..ff12d86060 100644
--- a/scripts/_runner_common.py
+++ b/scripts/_runner_common.py
@@ -20,6 +20,7 @@ walker that turns a buried `GatedRepoError` into a friendly link — belongs her
import json
import logging
+import os
import sys
import threading
from contextlib import contextmanager
@@ -136,6 +137,98 @@ def apply_memory_optimizations(pipe) -> None:
vae.enable_tiling()
+# Headroom reserved on top of the resident weights for activations + allocator
+# fragmentation when deciding whether a pipeline fits in *currently free* VRAM.
+# Catches the case where another process is hogging the card even for a
+# mid-size model.
+_ACTIVATION_RESERVE_BYTES = 3 * 1024 ** 3
+
+# Second, resolution-independent offload trigger: when the weights alone exceed
+# this fraction of the card's *total* VRAM, force offload regardless of how
+# much is momentarily free. A model that fills most of the card leaves no
+# bounded margin for high-res activations or the per-step stepwise VAE decode,
+# and on Windows the NVIDIA driver answers the overflow with silent sysmem
+# fallback (~50x slowdown) rather than OOM — so a fixed activation reserve
+# can't protect against it. Offload is cheap for these (the transformer stays
+# resident across the whole denoising loop), so erring toward it costs a few
+# seconds of one-time component paging and removes the thrash cliff entirely.
+# 0.5 keeps SDXL (~7 GB) / SD-1.5 (~2 GB) fully resident on a 24 GB card while
+# routing the ~19-20 GB Z-Image / ERNIE / Qwen bf16 pipelines to offload.
+_OFFLOAD_VRAM_FRACTION = 0.5
+
+
+def _pipeline_weight_bytes(pipe) -> int:
+ """Total bytes of the pipeline's parameters + buffers, de-duplicated by
+ storage pointer so tied / shared weights aren't double-counted."""
+ components = getattr(pipe, "components", None) or {}
+ modules = [m for m in components.values() if hasattr(m, "parameters")]
+ seen = set()
+ total = 0
+ for module in modules:
+ for tensor in list(module.parameters()) + list(module.buffers()):
+ key = tensor.data_ptr()
+ if key in seen or key == 0:
+ continue
+ seen.add(key)
+ total += tensor.numel() * tensor.element_size()
+ return total
+
+
+def place_pipeline(pipe, device: str) -> str:
+ """Move a loaded diffusers pipeline onto the compute device, choosing
+ between full-GPU residency and model CPU offload based on free VRAM.
+
+ On CUDA, a pipeline whose weights nearly fill the card (Z-Image-Turbo /
+ ERNIE / Qwen bf16 are ~20 GB on a 24 GB GPU) leaves no room for the
+ forward pass's activations. On Windows the NVIDIA driver then silently
+ spills the overflow into system RAM ("sysmem fallback") instead of
+ OOM-ing, and every denoising step thrashes across PCIe — ~50x slower than
+ the GPU is capable of. When the weights plus an activation reserve won't
+ fit in free VRAM, fall back to `enable_model_cpu_offload()`: the
+ transformer stays resident across the loop while the text encoder and VAE
+ are paged in only for their one-shot forward, so peak VRAM drops well
+ under the card's limit and the steps run at full GPU speed.
+
+ MPS / CPU keep the plain `.to(device)` path — offload is a CUDA+accelerate
+ feature and the sysmem-fallback failure mode it guards against is
+ CUDA-specific. Override the heuristic with `PORTOS_IMAGE_OFFLOAD=1`
+ (force offload) or `PORTOS_IMAGE_OFFLOAD=0` (force full residency).
+ Returns the effective placement string for logging.
+ """
+ if device != "cuda":
+ pipe.to(device)
+ return device
+
+ import torch
+
+ override = os.environ.get("PORTOS_IMAGE_OFFLOAD", "").strip().lower()
+ can_offload = hasattr(pipe, "enable_model_cpu_offload")
+ if override in ("0", "false", "never"):
+ force_offload = False
+ elif override in ("1", "true", "force", "always"):
+ force_offload = True
+ else:
+ weight_bytes = _pipeline_weight_bytes(pipe)
+ free_bytes, total_bytes = torch.cuda.mem_get_info()
+ fits_now = (weight_bytes + _ACTIVATION_RESERVE_BYTES) <= free_bytes
+ fills_card = weight_bytes > _OFFLOAD_VRAM_FRACTION * total_bytes
+ force_offload = fills_card or not fits_now
+ gb = 1024 ** 3
+ reason = "fills card" if fills_card else ("low free VRAM" if not fits_now else "fits")
+ print(
+ f"🧮 image-gen VRAM: weights ~{weight_bytes / gb:.1f}GB, "
+ f"free ~{free_bytes / gb:.1f}GB, total ~{total_bytes / gb:.1f}GB ({reason}) → "
+ f"{'model CPU offload' if force_offload else 'full GPU residency'}",
+ file=sys.stderr, flush=True,
+ )
+
+ if force_offload and can_offload:
+ pipe.enable_model_cpu_offload()
+ return "cuda+offload"
+ pipe.to(device)
+ return device
+
+
def write_sidecar(output: str, payload: dict) -> None:
"""Write `<output>.metadata.json` next to the generated image. The
server's gallery scanner picks this up to surface prompt/seed/model
@@ -192,6 +285,16 @@ def make_stepwise_callback(
vae_dtype, vae_device = vae_param.dtype, vae_param.device
except StopIteration:
vae_dtype, vae_device = None, None
+ # Under `enable_model_cpu_offload()` (see place_pipeline) the VAE's params
+ # rest on CPU but its forward runs on the accelerate hook's execution
+ # device (CUDA) — and the hook moves the *weights* there without moving the
+ # latents we hand it, so aligning the preview latents to the resting
+ # (CPU) device decodes with "weight on cuda:0, other tensors on cpu". Target
+ # the execution device instead, so the latents land where the VAE will run.
+ _vae_hook = getattr(vae, "_hf_hook", None)
+ _exec_device = getattr(_vae_hook, "execution_device", None)
+ if _exec_device is not None:
+ vae_device = _exec_device
fired = {"count": 0, "saved": 0}
diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.py
index 245e71d5bd..a421c6e91d 100644
--- a/scripts/z_image_turbo.py
+++ b/scripts/z_image_turbo.py
@@ -38,6 +38,7 @@ from _runner_common import ( # noqa: E402
make_generator,
make_stepwise_callback,
pick_device,
+ place_pipeline,
suppress_cosmetic_clip_truncation,
write_sidecar,
)
@@ -169,7 +170,7 @@ def load_pipeline(
)
print("STAGE:move-to-device", file=sys.stderr, flush=True)
with heartbeat("move-to-device"):
- pipe.to(device)
+ place_pipeline(pipe, device)
return pipe
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index d72bfdbeea..4121d4232a 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -61,16 +61,23 @@ const PYTHON_CANDIDATES = IS_WIN
join(PATHS.data, 'python', 'venv', 'Scripts', 'python.exe'),
join(HOME, '.portos', 'venv', 'Scripts', 'python.exe'),
join(HOME, '.pixie-forge', 'venv', 'Scripts', 'python.exe'),
- join(HOME, 'miniconda3', 'python.exe'),
- join(HOME, 'anaconda3', 'python.exe'),
- 'C:\\miniconda3\\python.exe',
- 'C:\\anaconda3\\python.exe',
+ // Standalone python.org installs are preferred over conda on Windows.
+ // A venv created from a conda/miniconda base inherits conda's MKL +
+ // OpenMP DLLs, which make torch fail to load at runtime with
+ // "WinError 1114: c10.dll initialization routine failed" — so a
+ // conda-based FLUX.2 venv installs cleanly but can't import torch.
+ // Conda stays last as a usable-for-non-torch fallback when it's the
+ // only Python present.
join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python313', 'python.exe'),
join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python312', 'python.exe'),
join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python311', 'python.exe'),
'C:\\Python313\\python.exe',
'C:\\Python312\\python.exe',
'C:\\Python311\\python.exe',
+ join(HOME, 'miniconda3', 'python.exe'),
+ join(HOME, 'anaconda3', 'python.exe'),
+ 'C:\\miniconda3\\python.exe',
+ 'C:\\anaconda3\\python.exe',
]
: [
join(PATHS.data, 'python', 'venv', 'bin', 'python3'),
@@ -128,6 +135,16 @@ export async function detectArm64Python() {
return firstArchMatch(present, (a) => a === 'arm64');
}
+// True when an NVIDIA GPU is present (nvidia-smi lists at least one device).
+// Used to decide whether the Windows FLUX.2 install pulls CUDA torch from the
+// PyTorch index vs. the default CPU wheel. Best-effort: a missing nvidia-smi
+// or any failure reads as "no GPU".
+export async function hasNvidiaGpu() {
+ const { stdout } = await execFileAsync('nvidia-smi', ['-L'], { timeout: 8000 })
+ .catch(() => ({ stdout: '' }));
+ return /GPU \d+:/.test(stdout);
+}
+
// FLUX.2 runs in its own venv because mflux (MLX) and torch+diffusers-from-git
// have hostile dependency trees. Bootstrap with `INSTALL_FLUX2=1
// scripts/setup-image-video.sh`. We probe a small candidate list rather than
@@ -389,12 +406,25 @@ export function installPackages(pythonPath, importNames, onLog) {
};
}
+// torch + torchvision are split out from the rest of the FLUX.2 venv specs
+// because Windows needs the CUDA-enabled wheels from PyTorch's own index: the
+// default PyPI `torch` wheel on Windows is CPU-only (`torch==X+cpu`), which
+// makes local image-gen unusably slow on an NVIDIA box. Linux's default PyPI
+// torch already bundles CUDA and macOS uses the default MPS-capable wheel, so
+// only Windows + NVIDIA needs the index swap (see installFlux2Venv).
+export const FLUX2_TORCH_SPECS = ['torch>=2.5', 'torchvision'];
+
+// PyTorch CUDA wheel index used on Windows + NVIDIA. cu126 (CUDA 12.6) is the
+// broadest-compatible recent index — drivers >= ~525 support it — and serves
+// current torch builds. Override with PORTOS_TORCH_CUDA_INDEX (e.g.
+// https://download.pytorch.org/whl/cu130) if a newer/older CUDA is needed.
+export const WIN_TORCH_CUDA_INDEX = 'https://download.pytorch.org/whl/cu126';
+
// Pip specs for the FLUX.2 venv. Mirrors scripts/setup-image-video.sh so the
// shell path and the in-app installer stay in sync. diffusers + sdnq are
// git-only because Flux2KleinPipeline isn't in any tagged release yet.
export const FLUX2_PIP_SPECS = [
- 'torch>=2.5',
- 'torchvision',
+ ...FLUX2_TORCH_SPECS,
'accelerate',
'transformers>=4.51',
'sentencepiece',
@@ -449,7 +479,26 @@ export function installFlux2Venv(onLog) {
if (killed) return { ok: false, stage: 'upgrade-pip', cancelled: true };
stage('install', 'Installing torch + diffusers + sdnq + transformers (~6-10 min — large download)…');
- if (!await runPython([venvPython, '-m', 'pip', 'install', '--upgrade', '--progress-bar', 'on', ...FLUX2_PIP_SPECS])) {
+ if (IS_WIN) {
+ // Windows: install torch+torchvision first so the right wheel sticks,
+ // then the rest WITHOUT torch in the list — otherwise the `--upgrade`
+ // below would re-pull the CPU-only PyPI torch over the CUDA build.
+ const useCuda = await hasNvidiaGpu();
+ const cudaIndex = process.env.PORTOS_TORCH_CUDA_INDEX || WIN_TORCH_CUDA_INDEX;
+ log(useCuda
+ ? `NVIDIA GPU detected — installing CUDA torch from ${cudaIndex}`
+ : 'No NVIDIA GPU detected — installing CPU torch (image-gen will be slow)');
+ const torchArgs = ['install', '--upgrade', '--progress-bar', 'on', ...FLUX2_TORCH_SPECS];
+ if (useCuda) torchArgs.push('--index-url', cudaIndex);
+ if (!await runPython([venvPython, '-m', 'pip', ...torchArgs])) {
+ return { ok: false, stage: 'install' };
+ }
+ if (killed) return { ok: false, stage: 'install', cancelled: true };
+ const otherSpecs = FLUX2_PIP_SPECS.filter((s) => !FLUX2_TORCH_SPECS.includes(s));
+ if (!await runPython([venvPython, '-m', 'pip', 'install', '--upgrade', '--progress-bar', 'on', ...otherSpecs])) {
+ return { ok: false, stage: 'install' };
+ }
+ } else if (!await runPython([venvPython, '-m', 'pip', 'install', '--upgrade', '--progress-bar', 'on', ...FLUX2_PIP_SPECS])) {
return { ok: false, stage: 'install' };
}
if (killed) return { ok: false, stage: 'install', cancelled: true };