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

wire HiDream + Qwen runners and FLUX.2 native bf16 path

[._.]/ Adam Eivy12693059f63b
diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.py
index eacead4ea9..2444b043c0 100755
--- a/scripts/flux2_macos.py
+++ b/scripts/flux2_macos.py
@@ -77,6 +77,26 @@ def probe_hf_auth(repo: str) -> None:
print(f"⚠️ HF probe non-fatal error: {err}", file=sys.stderr)
+def load_pipeline_bf16(repo: str, device: str, dtype):
+ """Native bf16 load — no SDNQ, no Int8. Pipeline + tokenizer come from
+ the gated base repo (e.g. black-forest-labs/FLUX.2-klein-9B). Practical
+ only with ~64+ GB unified memory for the 9B variant."""
+ from diffusers import Flux2KleinPipeline
+
+ print(f"STAGE:download-pipeline:{repo}", file=sys.stderr, flush=True)
+ print(f"🔧 bf16: pipeline ← {repo}", file=sys.stderr)
+ with heartbeat("loading-pipeline"):
+ pipe = Flux2KleinPipeline.from_pretrained(
+ repo,
+ torch_dtype=dtype,
+ low_cpu_mem_usage=True,
+ )
+ print("STAGE:move-to-device", file=sys.stderr, flush=True)
+ with heartbeat("move-to-device"):
+ pipe.to(device)
+ return pipe
+
+
def load_pipeline_sdnq(repo: str, tokenizer_repo: str, device: str, dtype):
# `sdnq` registers a custom config type at import-time. The Flux2KleinPipeline
# `from_pretrained` call below pulls a config that references it, so the
@@ -193,7 +213,7 @@ def _unpack_flux2_latents(latents, height: int, width: int, vae_scale: int = 8,
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="PortOS FLUX.2-klein runner")
p.add_argument("--model", required=True, help="model id (e.g. flux2-klein-4b)")
- p.add_argument("--quantization", required=True, choices=["sdnq", "int8"])
+ p.add_argument("--quantization", required=True, choices=["sdnq", "int8", "none"])
p.add_argument("--repo", required=True, help="HF repo for the quantized weights")
p.add_argument("--tokenizer-repo", default=None, help="HF repo for tokenizer (sdnq variants)")
p.add_argument("--base-pipeline-repo", default=None, help="HF repo for VAE/scheduler (int8 variant)")
@@ -242,6 +262,10 @@ def main() -> None:
sys.exit(64)
probe_hf_auth(args.base_pipeline_repo)
pipe = load_pipeline_int8(args.repo, args.base_pipeline_repo, device, dtype)
+ elif args.quantization == "none":
+ # Native bf16 — `repo` is the gated base repo itself.
+ probe_hf_auth(args.repo)
+ pipe = load_pipeline_bf16(args.repo, device, dtype)
else:
print(f"❌ unknown quantization: {args.quantization}", file=sys.stderr)
sys.exit(64)
diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.py
index d62f12e62d..40b42ff5f4 100644
--- a/scripts/z_image_turbo.py
+++ b/scripts/z_image_turbo.py
@@ -37,13 +37,75 @@ from _runner_common import ( # noqa: E402
from lora_utils import apply_loras # noqa: E402
-def load_pipeline(repo: str, device: str, dtype, pipeline_class: str = ""):
+def load_external_text_encoder(repo: str, encoder_class: str, tokenizer_class: str, dtype):
+ """Load a separately-distributed text encoder + its tokenizer.
+
+ HiDream-I1 needs Llama-3.1-8B-Instruct as `text_encoder_4` / `tokenizer_4`,
+ passed to HiDreamImagePipeline.from_pretrained as kwargs. The base
+ HiDream-I1 repo doesn't ship Llama weights — they're loaded from a
+ separate (gated) repo. This helper resolves the encoder + tokenizer
+ classes by name from transformers and loads them. `encoder_class` is
+ required; `tokenizer_class` defaults to AutoTokenizer when unset.
+ """
+ import transformers
+
+ print(f"STAGE:download-text-encoder:{repo}", file=sys.stderr, flush=True)
+ print(f"🔧 diffusers runner: text encoder ← {repo} ({encoder_class})", file=sys.stderr)
+ enc_cls = getattr(transformers, encoder_class, None)
+ if enc_cls is None:
+ print(f"❌ Unknown transformers text-encoder class: {encoder_class}", file=sys.stderr)
+ sys.exit(2)
+ tok_cls = (
+ getattr(transformers, tokenizer_class, None) if tokenizer_class else transformers.AutoTokenizer
+ )
+ if tok_cls is None:
+ print(f"❌ Unknown transformers tokenizer class: {tokenizer_class}", file=sys.stderr)
+ sys.exit(2)
+ with heartbeat("loading-text-encoder"):
+ # output_hidden_states / output_attentions are required for HiDream
+ # (it reaches into Llama's hidden states for prompt conditioning).
+ # Harmless for other LMs that ignore the kwargs.
+ text_encoder = enc_cls.from_pretrained(
+ repo,
+ output_hidden_states=True,
+ output_attentions=True,
+ torch_dtype=dtype,
+ )
+ tokenizer = tok_cls.from_pretrained(repo)
+ return text_encoder, tokenizer
+
+
+def load_pipeline(
+ repo: str,
+ device: str,
+ dtype,
+ pipeline_class: str = "",
+ text_encoder_repo: str = "",
+ text_encoder_class: str = "",
+ tokenizer_class: str = "",
+):
# When the registry pins a pipeline class (e.g. ErnieImagePipeline,
- # which isn't yet in AutoPipelineForText2Image's registry) load it
- # directly. Falls back to AutoPipelineForText2Image so Z-Image-Turbo
- # and any future registered model continues to work without a flag.
+ # HiDreamImagePipeline, QwenImagePipeline) load it directly. Falls back
+ # to AutoPipelineForText2Image so Z-Image-Turbo and any future registered
+ # model continues to work without a flag.
import diffusers
+ # HiDream needs a 4th text encoder + tokenizer loaded externally and
+ # passed as kwargs. The text-encoder-repo flag is the trigger; if it's
+ # set, the loaded objects are passed as text_encoder_4 / tokenizer_4 to
+ # the pipeline constructor. Other diffusers-runner models leave this
+ # path untouched.
+ extra_kwargs = {}
+ if text_encoder_repo:
+ if not text_encoder_class:
+ print("❌ --text-encoder-repo set but --text-encoder-class missing", file=sys.stderr)
+ sys.exit(2)
+ text_encoder, tokenizer = load_external_text_encoder(
+ text_encoder_repo, text_encoder_class, tokenizer_class, dtype
+ )
+ extra_kwargs["text_encoder_4"] = text_encoder
+ extra_kwargs["tokenizer_4"] = tokenizer
+
print(f"STAGE:download-pipeline:{repo}", file=sys.stderr, flush=True)
print(f"🔧 diffusers runner: pipeline ← {repo} (class={pipeline_class or 'auto'})", file=sys.stderr)
with heartbeat("loading-pipeline"):
@@ -52,13 +114,16 @@ def load_pipeline(repo: str, device: str, dtype, pipeline_class: str = ""):
if cls is None:
print(f"❌ Unknown diffusers pipeline class: {pipeline_class}", file=sys.stderr)
sys.exit(2)
- pipe = cls.from_pretrained(repo, torch_dtype=dtype, low_cpu_mem_usage=True)
+ pipe = cls.from_pretrained(
+ repo, torch_dtype=dtype, low_cpu_mem_usage=True, **extra_kwargs
+ )
else:
from diffusers import AutoPipelineForText2Image
pipe = AutoPipelineForText2Image.from_pretrained(
repo,
torch_dtype=dtype,
low_cpu_mem_usage=True,
+ **extra_kwargs,
)
print("STAGE:move-to-device", file=sys.stderr, flush=True)
with heartbeat("move-to-device"):
@@ -93,8 +158,11 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--device", default="auto", choices=["auto", "mps", "cuda", "cpu"])
p.add_argument("--lora-paths", nargs="*", default=[], help="absolute paths to LoRA .safetensors files")
p.add_argument("--lora-scales", nargs="*", default=[], help="scale per LoRA, parallel to --lora-paths")
- p.add_argument("--pipeline-class", default="", help="optional explicit diffusers pipeline class (e.g. ErnieImagePipeline)")
+ p.add_argument("--pipeline-class", default="", help="optional explicit diffusers pipeline class (e.g. ErnieImagePipeline, HiDreamImagePipeline)")
p.add_argument("--use-pe", action="store_true", help="enable the prompt enhancer (ERNIE-Image's use_pe kwarg)")
+ p.add_argument("--text-encoder-repo", default="", help="HF repo for an external text encoder (HiDream → Llama-3.1-8B-Instruct)")
+ p.add_argument("--text-encoder-class", default="", help="transformers class name for the external text encoder (e.g. LlamaForCausalLM)")
+ p.add_argument("--tokenizer-class", default="", help="transformers class name for the external tokenizer (defaults to AutoTokenizer)")
return p.parse_args()
@@ -105,7 +173,15 @@ def main() -> None:
device = pick_device(args.device)
dtype = torch.bfloat16 if device in ("mps", "cuda") else torch.float32
- pipe = load_pipeline(args.repo, device, dtype, pipeline_class=args.pipeline_class)
+ pipe = load_pipeline(
+ args.repo,
+ device,
+ dtype,
+ pipeline_class=args.pipeline_class,
+ text_encoder_repo=args.text_encoder_repo,
+ text_encoder_class=args.text_encoder_class,
+ tokenizer_class=args.tokenizer_class,
+ )
init_image = None
if args.image_path:
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index c0c62c33c8..802b4bdb89 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -29,7 +29,8 @@ import { IMAGE_GEN_MODE } from './modes.js';
const IS_WIN = process.platform === 'win32';
-import { getImageModels, isFlux2, isZImage, isErnie } from '../../lib/mediaModels.js';
+import { getImageModels, isFlux2, isZImage, isErnie, isHiDream, isQwen } from '../../lib/mediaModels.js';
+import { usesDiffusersRunner } from '../../lib/runners.js';
// Read the registry lazily — callers below hit getImageModels() at request
// time. A prior `IMAGE_MODELS = Object.fromEntries(getImageModels()...)`
@@ -71,20 +72,28 @@ export const cancel = () => {
export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths = [], loraScales = [], stepwiseDir, initImagePath, initImageStrength, referenceImagePaths = [], referenceImageStrengths = [] }) => {
const modelId = model?.id;
- if (isZImage(model) || isErnie(model)) {
+ if (usesDiffusersRunner(model)) {
+ const runnerLabel = isErnie(model) ? 'ERNIE' : isHiDream(model) ? 'HiDream' : isQwen(model) ? 'Qwen' : 'Z-Image';
+ const errCode = isErnie(model)
+ ? 'IMAGE_GEN_ERNIE_MISCONFIGURED'
+ : isHiDream(model)
+ ? 'IMAGE_GEN_HIDREAM_MISCONFIGURED'
+ : isQwen(model)
+ ? 'IMAGE_GEN_QWEN_MISCONFIGURED'
+ : 'IMAGE_GEN_Z_IMAGE_MISCONFIGURED';
if (!model.repo) {
throw new ServerError(
- `${isErnie(model) ? 'ERNIE' : 'Z-Image'} model "${modelId}" is missing the 'repo' field in data/media-models.json`,
- { status: 500, code: isErnie(model) ? 'IMAGE_GEN_ERNIE_MISCONFIGURED' : 'IMAGE_GEN_Z_IMAGE_MISCONFIGURED' },
+ `${runnerLabel} model "${modelId}" is missing the 'repo' field in data/media-models.json`,
+ { status: 500, code: errCode },
);
}
- // Z-Image / ERNIE both reuse the FLUX.2 venv (same diffusers + torch
- // stack, no extra setup). Same not-installed error code so the UI's
- // existing "run setup" CTA fires for any of these runners.
+ // Z-Image / ERNIE / HiDream / Qwen all reuse the FLUX.2 venv (same
+ // diffusers + torch stack, no extra setup). Same not-installed error code
+ // so the UI's existing "run setup" CTA fires for any of these runners.
const torchPython = resolveFlux2Python();
if (!torchPython) {
throw new ServerError(
- `Image-gen torch venv not found. Run \`INSTALL_FLUX2=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected at ${FLUX2_VENV_DEFAULT}). FLUX.2, Z-Image, and ERNIE share this venv.`,
+ `Image-gen torch venv not found. Run \`INSTALL_FLUX2=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected at ${FLUX2_VENV_DEFAULT}). FLUX.2, Z-Image, ERNIE, HiDream, and Qwen share this venv.`,
{ status: 400, code: 'IMAGE_GEN_FLUX2_NOT_INSTALLED' },
);
}
@@ -109,6 +118,13 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
if (loraScales?.length) args.push('--lora-scales', ...loraScales.map(String));
if (model.pipelineClass) args.push('--pipeline-class', String(model.pipelineClass));
if (model.usePromptEnhancer) args.push('--use-pe');
+ // HiDream needs a 4th text encoder loaded separately (Llama-3.1-8B) —
+ // the Diffusers HiDreamImagePipeline expects `text_encoder_4` /
+ // `tokenizer_4` kwargs at from_pretrained() time. The runner script
+ // branches on these flags; Z-Image / ERNIE / Qwen leave them unset.
+ if (model.textEncoderRepo) args.push('--text-encoder-repo', String(model.textEncoderRepo));
+ if (model.textEncoderClass) args.push('--text-encoder-class', String(model.textEncoderClass));
+ if (model.tokenizerClass) args.push('--tokenizer-class', String(model.tokenizerClass));
return { bin: torchPython, args };
}
if (isFlux2(model)) {
@@ -119,9 +135,9 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
);
}
const quantization = model.quantization || 'sdnq';
- if (quantization !== 'sdnq' && quantization !== 'int8') {
+ if (quantization !== 'sdnq' && quantization !== 'int8' && quantization !== 'none') {
throw new ServerError(
- `FLUX.2 model "${modelId}" has unsupported quantization "${quantization}" (supported: sdnq, int8)`,
+ `FLUX.2 model "${modelId}" has unsupported quantization "${quantization}" (supported: sdnq, int8, none)`,
{ status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },
);
}
@@ -137,6 +153,8 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
{ status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },
);
}
+ // quantization=none uses model.repo directly (gated base repo). No
+ // sibling-repo flag required, but the repo must be the gated base.
const flux2Python = resolveFlux2Python();
if (!flux2Python) {
throw new ServerError(
@@ -232,7 +250,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
// Both flux2 and z-image runners resolve their own Python via the FLUX.2
// venv — only the legacy mflux/imagine_win path needs the user-configured
// Settings > Image Gen pythonPath.
- if (!isFlux2(model) && !isZImage(model) && !isErnie(model) && !pythonPath) {
+ if (!isFlux2(model) && !usesDiffusersRunner(model) && !pythonPath) {
throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });
}
// FLUX.2 and Z-Image runners now load LoRAs via diffusers'