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
feat([flux2-multi-reference-python-runner]): wire diffusers KV multi-reference editing in flux2 runner
[._.]/ Adam Eivy3ec39dfc12da
diff --git a/data.reference/media-models.json b/data.reference/media-models.jsonindex c91be1c8b2..e2cbd075fc 100644--- a/data.reference/media-models.json+++ b/data.reference/media-models.json@@ -118,7 +118,7 @@"runner": "flux2","quantization": "sdnq","repo": "Disty0/FLUX.2-klein-9B-SDNQ-4bit-dynamic-svd-r32",- "tokenizerRepo": "black-forest-labs/FLUX.2-klein-9B",+ "tokenizerRepo": "black-forest-labs/FLUX.2-klein-9B-kv","steps": 8,"guidance": 3.5,"cfgDisabled": truediff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.pyindex c19349257b..e3ef11a366 100755--- a/scripts/flux2_macos.py+++ b/scripts/flux2_macos.py@@ -78,16 +78,24 @@ 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):+def _resolve_pipeline_cls(use_kv: bool):+ """Pick the diffusers pipeline class. `Flux2KleinKVPipeline` uses K/V-cached+ reference-token attention for multi-reference editing; both classes share+ the same component init signature (scheduler/vae/text_encoder/tokenizer/+ transformer/is_distilled), so any flux2-klein repo loads into either."""+ from diffusers import Flux2KleinKVPipeline, Flux2KleinPipeline++ return Flux2KleinKVPipeline if use_kv else Flux2KleinPipeline+++def load_pipeline_bf16(repo: str, device: str, dtype, pipeline_cls):"""Native bf16 load — no SDNQ, no Int8. Pipeline + tokenizer come fromthe gated base repo (e.g. black-forest-labs/FLUX.2-klein-9B). Practicalonly 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)+ print(f"🔧 bf16: pipeline ({pipeline_cls.__name__}) ← {repo}", file=sys.stderr)with heartbeat("loading-pipeline"):- pipe = Flux2KleinPipeline.from_pretrained(+ pipe = pipeline_cls.from_pretrained(repo,torch_dtype=dtype,low_cpu_mem_usage=True,@@ -98,13 +106,12 @@ def load_pipeline_bf16(repo: str, device: str, dtype):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+def load_pipeline_sdnq(repo: str, tokenizer_repo: str, device: str, dtype, pipeline_cls):+ # `sdnq` registers a custom config type at import-time. The pipeline# `from_pretrained` call below pulls a config that references it, so the# import has to happen first. Keep it inside the function so the runner# also works for the int8 branch on systems without sdnq installed.import sdnq # noqa: F401 (registration side-effect)- from diffusers import Flux2KleinPipelinefrom transformers import AutoTokenizer# STAGE markers are parsed by server/services/imageGen/local.js#handleLine@@ -117,9 +124,9 @@ def load_pipeline_sdnq(repo: str, tokenizer_repo: str, device: str, dtype):with heartbeat("loading-tokenizer"):tokenizer = AutoTokenizer.from_pretrained(tokenizer_repo, subfolder="tokenizer", use_fast=False)print(f"STAGE:download-pipeline:{repo}", file=sys.stderr, flush=True)- print(f"🔧 sdnq: pipeline ← {repo}", file=sys.stderr)+ print(f"🔧 sdnq: pipeline ({pipeline_cls.__name__}) ← {repo}", file=sys.stderr)with heartbeat("loading-pipeline"):- pipe = Flux2KleinPipeline.from_pretrained(+ pipe = pipeline_cls.from_pretrained(repo,tokenizer=tokenizer,torch_dtype=dtype,@@ -131,9 +138,8 @@ def load_pipeline_sdnq(repo: str, tokenizer_repo: str, device: str, dtype):return pipe-def load_pipeline_int8(repo: str, base_repo: str, device: str, dtype):+def load_pipeline_int8(repo: str, base_repo: str, device: str, dtype, pipeline_cls):from accelerate import init_empty_weights- from diffusers import Flux2KleinPipelinefrom huggingface_hub import snapshot_downloadfrom optimum.quanto import requantizefrom safetensors.torch import load_file@@ -143,7 +149,7 @@ def load_pipeline_int8(repo: str, base_repo: str, device: str, dtype):from flux2_quantized import QuantizedFlux2Transformer2DModelprint(f"STAGE:download-int8-snapshot:{repo}", file=sys.stderr, flush=True)- print(f"🔧 int8: snapshot ← {repo}", file=sys.stderr)+ print(f"🔧 int8: snapshot ({pipeline_cls.__name__}) ← {repo}", file=sys.stderr)with heartbeat("downloading-snapshot"):model_path = snapshot_download(repo)@@ -174,7 +180,7 @@ def load_pipeline_int8(repo: str, base_repo: str, device: str, dtype):print(f"🔧 int8: VAE/scheduler ← {base_repo}", file=sys.stderr)with heartbeat("loading-vae-scheduler"):- pipe = Flux2KleinPipeline.from_pretrained(+ pipe = pipeline_cls.from_pretrained(base_repo,transformer=None,text_encoder=None,@@ -233,14 +239,14 @@ 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")- # Multi-reference editing — accepted but currently ignored. The Node side- # already plumbs these end-to-end so the UI + server contract is shippable;- # the diffusers multi-reference pipeline wiring lands with the- # FLUX.2-klein-9B-kv model swap (see PLAN.md `flux2-multi-reference-python-runner`).- # Without these stubs argparse would reject the args with "unrecognized- # arguments" and break every single-init FLUX.2 render once the route is live.- p.add_argument("--reference-images", nargs="*", default=[], help="(reserved) absolute paths to reference images")- p.add_argument("--reference-strengths", nargs="*", default=[], help="(reserved) 0..1 strength per reference image, parallel to --reference-images")+ # Multi-reference editing. When at least one reference image is provided,+ # the runner loads `Flux2KleinKVPipeline` instead of `Flux2KleinPipeline`+ # and forwards the list of PIL refs as the pipeline's `image=` kwarg.+ # `--reference-strengths` is plumbed end-to-end but the KV pipeline doesn't+ # expose per-reference weighting today — non-1.0 values log a warning and+ # are otherwise treated as 1.0. Up to 4 references (route-side cap).+ p.add_argument("--reference-images", nargs="*", default=[], help="absolute paths to reference images (multi-reference KV editing)")+ p.add_argument("--reference-strengths", nargs="*", default=[], help="0..1 strength per reference image, parallel to --reference-images (reserved — not honored per-ref by the KV pipeline yet)")return p.parse_args()@@ -251,22 +257,44 @@ def main() -> None:device = pick_device(args.device)dtype = torch.bfloat16 if device in ("mps", "cuda") else torch.float32+ use_kv = bool(args.reference_images)+ pipeline_cls = _resolve_pipeline_cls(use_kv)+ if use_kv:+ # Warn — but don't fail — when the per-ref strength array carries+ # non-default values. The route always sends 1.0 for slots that+ # didn't ship an explicit weight; only a curl/test caller would land+ # here with a non-1.0 today.+ non_default = [(i, s) for i, s in enumerate(args.reference_strengths) if s and float(s) != 1.0]+ if non_default:+ entries = ", ".join(f"ref{i + 1}={s}" for i, s in non_default)+ print(+ f"⚠️ --reference-strengths {entries} — Flux2KleinKVPipeline does not expose "+ f"per-reference weighting; treating each as 1.0.",+ file=sys.stderr,+ )+ if args.image_path:+ print(+ "⚠️ --image-path supplied alongside --reference-images; the KV pipeline "+ "doesn't support i2i strength, so the init image will be ignored.",+ file=sys.stderr,+ )+if args.quantization == "sdnq":if not args.tokenizer_repo:print("❌ --tokenizer-repo is required for sdnq variants", file=sys.stderr)sys.exit(64)probe_hf_auth(args.tokenizer_repo)- pipe = load_pipeline_sdnq(args.repo, args.tokenizer_repo, device, dtype)+ pipe = load_pipeline_sdnq(args.repo, args.tokenizer_repo, device, dtype, pipeline_cls)elif args.quantization == "int8":if not args.base_pipeline_repo:print("❌ --base-pipeline-repo is required for int8 variants", file=sys.stderr)sys.exit(64)probe_hf_auth(args.base_pipeline_repo)- pipe = load_pipeline_int8(args.repo, args.base_pipeline_repo, device, dtype)+ pipe = load_pipeline_int8(args.repo, args.base_pipeline_repo, device, dtype, pipeline_cls)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)+ pipe = load_pipeline_bf16(args.repo, device, dtype, pipeline_cls)else:print(f"❌ unknown quantization: {args.quantization}", file=sys.stderr)sys.exit(64)@@ -279,11 +307,29 @@ def main() -> None:generator = make_generator(device, seed)init_image = None- if args.image_path:+ if args.image_path and not use_kv:init_image = Image.open(args.image_path).convert("RGB").resize((int(args.width), int(args.height)), Image.LANCZOS)+ # Multi-reference editing — load each reference at the output resolution.+ # The KV pipeline encodes refs through the VAE then caches their attention+ # K/V on step 0; mismatched aspect ratios get LANCZOS-resized so the+ # transformer sees a uniform patch grid across all references.+ reference_pils = None+ if use_kv:+ reference_pils = [+ Image.open(p).convert("RGB").resize(+ (int(args.width), int(args.height)), Image.LANCZOS+ )+ for p in args.reference_images+ ]+ print(+ f"🔗 multi-reference KV: {len(reference_pils)} reference image(s) at "+ f"{int(args.width)}x{int(args.height)}",+ file=sys.stderr,+ )+callback = make_stepwise_callback(args.stepwise_image_output_dir,pipe,@@ -311,7 +357,16 @@ def main() -> None:# only set when supported.if "callback_on_step_end_tensor_inputs" in accepted:pipe_kwargs["callback_on_step_end_tensor_inputs"] = ["latents"]- if init_image is not None and "image" in accepted:+ if reference_pils is not None and "image" in accepted:+ # Flux2KleinKVPipeline accepts `image` as a single PIL or List[PIL].+ # Pass the list verbatim so it routes through the multi-reference+ # 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()+ 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).@@ -338,24 +393,26 @@ def main() -> None:print(f"🖼️ stepwise summary: callback fired {s['count']} times, saved {s['saved']} previews", file=sys.stderr)if args.metadata:- write_sidecar(- args.output,- {- "id": Path(args.output).stem,- "prompt": args.prompt,- "negativePrompt": args.negative_prompt,- "modelId": args.model,- "seed": seed,- "width": int(args.width),- "height": int(args.height),- "steps": int(args.steps),- "guidance": float(args.guidance),- "quantization": args.quantization,- "filename": Path(args.output).name,- "initImageFilename": Path(args.image_path).name if args.image_path else None,- "initImageStrength": float(args.image_strength) if args.image_strength is not None else None,- },- )+ sidecar = {+ "id": Path(args.output).stem,+ "prompt": args.prompt,+ "negativePrompt": args.negative_prompt,+ "modelId": args.model,+ "seed": seed,+ "width": int(args.width),+ "height": int(args.height),+ "steps": int(args.steps),+ "guidance": float(args.guidance),+ "quantization": args.quantization,+ "filename": Path(args.output).name,+ "initImageFilename": Path(args.image_path).name if (args.image_path and not use_kv) else None,+ "initImageStrength": float(args.image_strength) if (args.image_strength is not None and not use_kv) else None,+ }+ if use_kv:+ sidecar["pipelineClass"] = pipeline_cls.__name__+ sidecar["referenceImageFilenames"] = [Path(p).name for p in args.reference_images]+ sidecar["referenceStrengths"] = [float(s) for s in (args.reference_strengths or [])]+ write_sidecar(args.output, sidecar)# Free VRAM eagerly so a back-to-back generation in the same process# doesn't OOM. The PortOS runner respawns per request right now, so thisdiff --git a/scripts/migrations/045-flux2-klein-9b-kv-tokenizer.js b/scripts/migrations/045-flux2-klein-9b-kv-tokenizer.jsnew file mode 100644index 0000000000..82281b553e--- /dev/null+++ b/scripts/migrations/045-flux2-klein-9b-kv-tokenizer.js@@ -0,0 +1,70 @@+/**+ * Pin flux2-klein-9b's tokenizerRepo to the KV repo so multi-reference editing+ * loads without an extra HF license step.+ *+ * scripts/flux2_macos.py now branches into `Flux2KleinKVPipeline` when the+ * route forwards reference images, and the runner probes HF auth against the+ * configured `tokenizerRepo`. Pinning the SDNQ 9B entry to+ * `black-forest-labs/FLUX.2-klein-9B-kv` (same Qwen3 tokenizer as the base 9B+ * repo) means a user who accepts that one license can use both single-image+ * and multi-reference renders on this model.+ *+ * `data.reference/media-models.json` ships the new value for fresh installs,+ * but `data/media-models.json` is in the gitignored data/ tree and is NOT in+ * JSON_MERGE_TARGETS, so existing installs keep the old tokenizerRepo. This+ * migration swaps the pinned value when (and only when) it still matches the+ * pre-change shipped string — a user who pointed at a fork keeps their pin.+ *+ * Idempotent: a second run finds the new value (or a custom one) and exits+ * without writing.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const REL_PATH = 'data/media-models.json';++const OLD_TOKENIZER_REPO = 'black-forest-labs/FLUX.2-klein-9B';+const NEW_TOKENIZER_REPO = 'black-forest-labs/FLUX.2-klein-9B-kv';++export default {+ async up({ rootDir }) {+ const path = join(rootDir, REL_PATH);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log(`📄 ${REL_PATH} not present — skipping (fresh install will copy from data.reference)`);+ return;+ }++ let config;+ try {+ config = JSON.parse(raw);+ } catch (err) {+ console.log(`⚠️ ${REL_PATH}: invalid JSON, skipping (${err.message})`);+ return;+ }++ const image = Array.isArray(config?.image) ? config.image : null;+ if (!image) {+ console.log(`⚠️ ${REL_PATH}: no image[] array — skipping`);+ return;+ }++ const entry = image.find((m) => m?.id === 'flux2-klein-9b');+ if (!entry) {+ console.log(`✅ ${REL_PATH}: no 'flux2-klein-9b' entry — user removed it, nothing to migrate`);+ return;+ }++ if (entry.tokenizerRepo === OLD_TOKENIZER_REPO) {+ entry.tokenizerRepo = NEW_TOKENIZER_REPO;+ await writeFile(path, `${JSON.stringify(config, null, 2)}\n`);+ console.log(`📝 ${REL_PATH}: pinned flux2-klein-9b tokenizerRepo → ${NEW_TOKENIZER_REPO} (enables multi-reference editing)`);+ } else {+ console.log(`✅ ${REL_PATH}: flux2-klein-9b tokenizerRepo is "${entry.tokenizerRepo}" (not the pre-change default) — leaving alone`);+ }+ },+};diff --git a/scripts/migrations/045-flux2-klein-9b-kv-tokenizer.test.js b/scripts/migrations/045-flux2-klein-9b-kv-tokenizer.test.jsnew file mode 100644index 0000000000..8301aeb6af--- /dev/null+++ b/scripts/migrations/045-flux2-klein-9b-kv-tokenizer.test.js@@ -0,0 +1,81 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './045-flux2-klein-9b-kv-tokenizer.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const OLD = 'black-forest-labs/FLUX.2-klein-9B';+const NEW = 'black-forest-labs/FLUX.2-klein-9B-kv';++const baseRegistry = (tokenizerRepo) => ({+ image: [+ { id: 'dev', name: 'Flux 1 Dev' },+ {+ id: 'flux2-klein-9b',+ name: 'Flux 2 Klein 9B',+ runner: 'flux2',+ quantization: 'sdnq',+ repo: 'Disty0/FLUX.2-klein-9B-SDNQ-4bit-dynamic-svd-r32',+ tokenizerRepo,+ },+ ],+});++describe('migration 045 — flux2-klein-9b kv tokenizerRepo', () => {+ let rootDir;+ let path;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-045-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ path = join(rootDir, 'data', 'media-models.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('swaps the pre-change tokenizerRepo to the kv repo', async () => {+ writeJson(path, baseRegistry(OLD));+ await migration.up({ rootDir });+ const got = readJson(path);+ const entry = got.image.find((e) => e.id === 'flux2-klein-9b');+ expect(entry.tokenizerRepo).toBe(NEW);+ });++ it('is idempotent — a second run leaves the new value alone', async () => {+ writeJson(path, baseRegistry(NEW));+ const beforeMtime = readFileSync(path, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(path, 'utf-8')).toBe(beforeMtime);+ });++ it('preserves a user-customized tokenizerRepo', async () => {+ writeJson(path, baseRegistry('my-fork/flux2-tokenizer'));+ await migration.up({ rootDir });+ const entry = readJson(path).image.find((e) => e.id === 'flux2-klein-9b');+ expect(entry.tokenizerRepo).toBe('my-fork/flux2-tokenizer');+ });++ it('skips silently when data/media-models.json is missing (fresh install)', async () => {+ await migration.up({ rootDir });+ expect(existsSync(path)).toBe(false);+ });++ it('skips when the flux2-klein-9b entry has been removed', async () => {+ writeJson(path, { image: [{ id: 'dev', name: 'Flux 1 Dev' }] });+ await migration.up({ rootDir });+ const got = readJson(path);+ expect(got.image.find((e) => e.id === 'flux2-klein-9b')).toBeUndefined();+ });++ it('skips when image[] is missing entirely', async () => {+ writeJson(path, { textEncoders: [] });+ await migration.up({ rootDir });+ expect(readJson(path)).toEqual({ textEncoders: [] });+ });+});diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 71c1b692dc..81b0aca385 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -125,7 +125,11 @@ const DEFAULT_REGISTRY = {runner: 'flux2',quantization: 'sdnq',repo: 'Disty0/FLUX.2-klein-9B-SDNQ-4bit-dynamic-svd-r32',- tokenizerRepo: 'black-forest-labs/FLUX.2-klein-9B',+ // KV repo's tokenizer is the same Qwen3 tokenizer as the base 9B repo,+ // but the multi-reference editing path in scripts/flux2_macos.py probes+ // HF auth against this value — pinning to the KV repo means accepting+ // its license once enables both single-ref + multi-ref renders.+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-9B-kv',steps: 8,guidance: 3.5,cfgDisabled: true,diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex f66c918d9d..acfe63288d 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -185,13 +185,12 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, heif (negativePrompt) args.push('--negative-prompt', negativePrompt);if (initImagePath) args.push('--image-path', initImagePath);if (initImagePath && initImageStrength != null) args.push('--image-strength', String(initImageStrength));- // Multi-reference editing for FLUX.2. The Python runner currently ignores- // these flags — they're plumbed end-to-end so the UI + server contract is- // in place, but the actual multi-reference diffusers wiring is gated on- // the FLUX.2-klein-9B-kv model swap (see PLAN.md) since the user-facing- // model that supports this hasn't been validated yet. Adding them here- // (rather than waiting) keeps the wiring testable + avoids a second PR- // that touches the same lines.+ // Multi-reference editing for FLUX.2. When the path list is non-empty,+ // scripts/flux2_macos.py loads Flux2KleinKVPipeline (instead of the+ // single-image Flux2KleinPipeline) and passes the refs as image=[PIL...].+ // The route always emits parallel referenceImageStrengths (defaulting to+ // 1.0 per ref); the runner warns on non-default values today because the+ // KV pipeline doesn't yet expose per-reference attention weighting.if (referenceImagePaths?.length) {args.push('--reference-images', ...referenceImagePaths);if (referenceImageStrengths?.length) {