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: harden qwen image MPS decode (#9241)

Adam Eivya1a34dd98932
diff --git a/scripts/_runner_common.py b/scripts/_runner_common.py
index a212421e06..0a84008596 100644
--- a/scripts/_runner_common.py
+++ b/scripts/_runner_common.py
@@ -61,6 +61,17 @@ def register_source_namespace(package_name: str, package_dir: "str | Path"):
return package
+def decode_with_finite_retry(decode, retry_decode, isfinite):
+ """Decode once, retry once after non-finite output, then fail closed."""
+ decoded = decode()
+ if bool(isfinite(decoded).all().item()):
+ return decoded, False
+ decoded = retry_decode()
+ if bool(isfinite(decoded).all().item()):
+ return decoded, True
+ raise FloatingPointError("decode produced non-finite values after retry")
+
+
@contextmanager
def heartbeat(stage: "str | Callable[[], str]", interval: float = 20.0):
"""Emit a periodic STAGE:<stage>:heartbeat:Ns marker so the JS idle
diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.py
index 36b2b7907e..b6a03105ad 100644
--- a/scripts/z_image_turbo.py
+++ b/scripts/z_image_turbo.py
@@ -33,6 +33,7 @@ from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _runner_common import ( # noqa: E402
apply_memory_optimizations,
+ decode_with_finite_retry,
emit_image_execution_marker,
heartbeat,
install_hf_error_handler,
@@ -190,6 +191,44 @@ def to_i2i_pipeline(pipe):
return AutoPipelineForImage2Image.from_pipe(pipe)
+def decode_qwen21_latents(pipe, latents, height: int, width: int):
+ vae = pipe.vae
+ unpacked = pipe._unpack_latents(latents, height, width, pipe.vae_scale_factor)
+
+ def decode(dtype):
+ vae.to(dtype=dtype)
+ aligned = unpacked.to(dtype=dtype)
+ mean = (
+ torch.tensor(vae.config.latents_mean)
+ .view(1, vae.config.z_dim, 1, 1, 1)
+ .to(device=aligned.device, dtype=dtype)
+ )
+ std = (
+ torch.tensor(vae.config.latents_std)
+ .view(1, vae.config.z_dim, 1, 1, 1)
+ .to(device=aligned.device, dtype=dtype)
+ )
+ return vae.decode(aligned * std + mean, return_dict=False)[0]
+
+ try:
+ decoded, retried = decode_with_finite_retry(
+ lambda: decode(vae.dtype),
+ lambda: decode(torch.float32),
+ torch.isfinite,
+ )
+ except FloatingPointError as err:
+ message = (
+ "Qwen Image 2.1 MPS VAE decode produced NaNs after a float32 retry — "
+ "try float32 or a different model"
+ )
+ print("USER_ERROR:qwen_mps_nan", file=sys.stderr, flush=True)
+ print(f"❌ {message}", file=sys.stderr, flush=True)
+ raise RuntimeError(message) from err
+ if retried:
+ print("⚠️ qwen-image-2.1 VAE decode recovered after a float32 retry", file=sys.stderr)
+ return pipe.image_processor.postprocess(decoded[:, :, 0], output_type="pil")
+
+
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="PortOS Z-Image-Turbo runner")
p.add_argument("--model", required=True, help="model id (e.g. z-image-turbo-bf16)")
@@ -278,6 +317,10 @@ def main() -> None:
apply_memory_optimizations(pipe, width=args.width, height=args.height)
apply_loras(pipe, args.lora_paths or [], args.lora_scales or [])
+ qwen21_mps = args.pipeline_class == "QwenImage21Pipeline" and device == "mps"
+ if qwen21_mps:
+ pipe.vae.to(dtype=torch.float32)
+
seed = args.seed if args.seed is not None else int(torch.randint(0, 2**31 - 1, (1,)).item())
generator = make_generator(device, seed)
@@ -376,17 +419,29 @@ def main() -> None:
# unaffected).
if args.use_pe and "use_pe" in accepted:
pipe_kwargs["use_pe"] = True
+ if qwen21_mps:
+ if "output_type" not in accepted:
+ message = "Qwen Image 2.1 runtime cannot return latents; reinstall the local image runtime"
+ print("USER_ERROR:torch_runtime_broken", file=sys.stderr, flush=True)
+ print(f"❌ {message}", file=sys.stderr, flush=True)
+ raise RuntimeError(message)
+ pipe_kwargs["output_type"] = "latent"
print("STAGE:inference", file=sys.stderr, flush=True)
print(
- f"🎨 z-image generate seed={seed} {args.width}x{args.height} steps={args.steps} "
- f"guidance={args.guidance} device={device}",
+ f"🎨 {args.model} generate seed={seed} {args.width}x{args.height} steps={args.steps} "
+ f"guidance={args.guidance} device={device} references={len(args.reference_images)}",
file=sys.stderr,
)
with torch.inference_mode():
result = pipe(**pipe_kwargs)
- image = result.images[0]
+ images = (
+ decode_qwen21_latents(pipe, result.images, int(args.height), int(args.width))
+ if qwen21_mps
+ else result.images
+ )
+ image = images[0]
image.save(args.output)
if callback is not None and hasattr(callback, "_stats"):
@@ -419,7 +474,7 @@ def main() -> None:
torch.cuda.empty_cache()
torch.cuda.synchronize()
- print(f"✅ z-image saved {args.output} (seed={seed})", file=sys.stderr)
+ print(f"✅ {args.model} saved {args.output} (seed={seed})", file=sys.stderr)
if __name__ == "__main__":
diff --git a/scripts/z_image_turbo.test.js b/scripts/z_image_turbo.test.js
new file mode 100644
index 0000000000..9fb00ba657
--- /dev/null
+++ b/scripts/z_image_turbo.test.js
@@ -0,0 +1,76 @@
+import { execFileSync, spawnSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { resolveTestPython } from '../server/lib/testHelper.js';
+
+const python = resolveTestPython();
+const commonScript = fileURLToPath(new URL('./_runner_common.py', import.meta.url));
+const qwenRunner = fileURLToPath(new URL('./z_image_turbo.py', import.meta.url));
+const runnerContract = fileURLToPath(new URL('./z_image_turbo_test.py', import.meta.url));
+const hasPillow = python && spawnSync(python, ['-c', 'import PIL'], { stdio: 'ignore' }).status === 0;
+
+const exerciseGuard = `
+import importlib.util, json, sys
+from types import SimpleNamespace
+spec = importlib.util.spec_from_file_location("runner_common", sys.argv[1])
+common = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(common)
+
+class Reduction:
+ def __init__(self, value):
+ self.value = value
+ def all(self):
+ return self
+ def item(self):
+ return self.value
+
+attempts = []
+def first():
+ attempts.append("first")
+ return "nan"
+def retry():
+ attempts.append("retry")
+ return "finite"
+def isfinite(value):
+ return Reduction(value == "finite")
+
+decoded, retried = common.decode_with_finite_retry(first, retry, isfinite)
+failed_closed = False
+try:
+ common.decode_with_finite_retry(lambda: "nan", lambda: "nan", isfinite)
+except FloatingPointError:
+ failed_closed = True
+print(json.dumps({"decoded": decoded, "retried": retried, "attempts": attempts, "failedClosed": failed_closed}))
+`;
+
+describe.skipIf(!python)('Qwen Image 2.1 MPS decode guard', () => {
+ it('retries non-finite output once and fails closed if float32 is still non-finite', () => {
+ const output = execFileSync(python, ['-c', exerciseGuard, commonScript], { encoding: 'utf8' });
+ expect(JSON.parse(output)).toEqual({
+ decoded: 'finite',
+ retried: true,
+ attempts: ['first', 'retry'],
+ failedClosed: true,
+ });
+ });
+
+});
+
+describe('Qwen Image 2.1 runner contract', () => {
+ it('owns the Qwen MPS latent decode and reports model/reference diagnostics', () => {
+ const source = readFileSync(qwenRunner, 'utf8');
+ expect(source).toContain('decode_with_finite_retry');
+ expect(source).toContain('pipe_kwargs["output_type"] = "latent"');
+ expect(source).toContain('USER_ERROR:qwen_mps_nan');
+ expect(source).toContain('references={len(args.reference_images)}');
+ });
+
+ it.skipIf(!hasPillow)('preserves generation/edit inputs and model-aware logs without model weights', () => {
+ expect(() => execFileSync(python, [runnerContract], {
+ encoding: 'utf8',
+ env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
+ stdio: 'pipe',
+ })).not.toThrow();
+ });
+});
diff --git a/scripts/z_image_turbo_test.py b/scripts/z_image_turbo_test.py
index 923713c37c..fea2958333 100644
--- a/scripts/z_image_turbo_test.py
+++ b/scripts/z_image_turbo_test.py
@@ -23,6 +23,72 @@ class Qwen21Pipeline:
return SimpleNamespace(images=[Image.new('RGBA', (32, 32), (10, 20, 30, 64))])
+class FakeReduction:
+ def __init__(self, value):
+ self.value = value
+
+ def all(self):
+ return self
+
+ def item(self):
+ return self.value
+
+
+class FakeTensor:
+ def __init__(self, *, finite=True, dtype='fp32'):
+ self.finite = finite
+ self.dtype = dtype
+ self.device = 'mps'
+
+ def to(self, *args, device=None, dtype=None):
+ if args:
+ self.device = args[0]
+ if device is not None:
+ self.device = device
+ if dtype is not None:
+ self.dtype = dtype
+ return self
+
+ def view(self, *_shape):
+ return self
+
+ def __mul__(self, _other):
+ return self
+
+ def __add__(self, _other):
+ return self
+
+ def __getitem__(self, _key):
+ return self
+
+
+class FakeVae:
+ def __init__(self, outcomes):
+ self.config = SimpleNamespace(latents_mean=[0.0], latents_std=[1.0], z_dim=1)
+ self.dtype = 'fp32'
+ self.outcomes = list(outcomes)
+ self.decode_dtypes = []
+
+ def to(self, *, dtype):
+ self.dtype = dtype
+ return self
+
+ def decode(self, _latents, return_dict=False):
+ self.decode_dtypes.append(self.dtype)
+ return (FakeTensor(finite=self.outcomes.pop(0), dtype=self.dtype),)
+
+
+class FakeQwenDecodePipeline:
+ vae_scale_factor = 8
+
+ def __init__(self, outcomes):
+ self.vae = FakeVae(outcomes)
+ self.image_processor = SimpleNamespace(postprocess=lambda decoded, output_type: [('image', decoded, output_type)])
+
+ def _unpack_latents(self, _latents, _height, _width, _scale_factor):
+ return FakeTensor(dtype='bf16')
+
+
class RunnerContract(unittest.TestCase):
def test_missing_pipeline_reports_runtime_remedy_before_exit_two(self):
with patch.dict(sys.modules, {'torch': SimpleNamespace()}):
@@ -38,6 +104,41 @@ class RunnerContract(unittest.TestCase):
self.assertIn('QwenImage21Pipeline', stderr.getvalue())
self.assertIn('FLUX2_FORCE_REINSTALL=1', stderr.getvalue())
+ def test_qwen21_decode_guard_accepts_finite_output_and_retries_once(self):
+ torch = SimpleNamespace(
+ float32='fp32',
+ tensor=lambda _values: FakeTensor(),
+ isfinite=lambda tensor: FakeReduction(tensor.finite),
+ )
+ with patch.dict(sys.modules, {'torch': torch}):
+ runner = importlib.import_module('z_image_turbo')
+ for outcomes, expected_calls, expect_retry_log in (
+ ([True], ['fp32'], False),
+ ([False, True], ['fp32', 'fp32'], True),
+ ):
+ with self.subTest(outcomes=outcomes), contextlib.redirect_stderr(io.StringIO()) as stderr:
+ pipe = FakeQwenDecodePipeline(outcomes)
+ images = runner.decode_qwen21_latents(pipe, FakeTensor(), 1216, 832)
+ self.assertEqual(images[0][0], 'image')
+ self.assertEqual(images[0][2], 'pil')
+ self.assertEqual(pipe.vae.decode_dtypes, expected_calls)
+ self.assertEqual('recovered after a float32 retry' in stderr.getvalue(), expect_retry_log)
+
+ def test_qwen21_decode_guard_fails_before_writing_non_finite_output(self):
+ torch = SimpleNamespace(
+ float32='fp32',
+ tensor=lambda _values: FakeTensor(),
+ isfinite=lambda tensor: FakeReduction(tensor.finite),
+ )
+ with patch.dict(sys.modules, {'torch': torch}):
+ runner = importlib.import_module('z_image_turbo')
+ pipe = FakeQwenDecodePipeline([False, False])
+ stderr = io.StringIO()
+ with contextlib.redirect_stderr(stderr), self.assertRaisesRegex(RuntimeError, 'produced NaNs'):
+ runner.decode_qwen21_latents(pipe, FakeTensor(), 1216, 832)
+ self.assertEqual(pipe.vae.decode_dtypes, ['fp32', 'fp32'])
+ self.assertIn('USER_ERROR:qwen_mps_nan', stderr.getvalue())
+
def test_qwen21_generation_and_edit_preserve_alpha(self):
torch = SimpleNamespace(
bfloat16='bf16', float32='fp32', inference_mode=contextlib.nullcontext,
@@ -59,6 +160,7 @@ class RunnerContract(unittest.TestCase):
if references:
argv += ['--reference-images'] + [str(source)] * references
pipe = Qwen21Pipeline()
+ stderr = io.StringIO()
with patch.object(sys, 'argv', argv), patch.multiple(
runner, pick_device=lambda _: 'cpu',
load_pipeline=lambda *a, **kw: (pipe, 'cpu'),
@@ -69,8 +171,11 @@ class RunnerContract(unittest.TestCase):
make_stepwise_callback=lambda *a, **kw: None,
set_vae_tiling=lambda *a: None,
to_i2i_pipeline=lambda _: self.fail('Unified pipeline must not be converted'),
- ):
+ ), contextlib.redirect_stderr(stderr):
runner.main()
+ self.assertIn('🎨 qwen-image-2.1 generate', stderr.getvalue())
+ self.assertIn(f'references={references}', stderr.getvalue())
+ self.assertNotIn('🎨 z-image generate', stderr.getvalue())
self.assertEqual(pipe.received['steps'], 40)
self.assertEqual(pipe.received['cfg'], 1)
if references:
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 54a8a2dd47..a11d8870a1 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -710,7 +710,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
}
if (memoryReport.unloaded.length) console.log(`🧹 Image generation [${jobId.slice(0, 8)}] freed ${memoryReport.unloaded.length} resident model(s)`);
- console.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps}`);
+ console.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps} references=${validReferenceImagePaths.length}`);
imageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });
activeJob = { ...meta, generationId: jobId, totalSteps: actualSteps, step: 0, progress: 0, currentImage: null, mode: IMAGE_GEN_MODE.LOCAL };