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

feat([issue-732]): support multi-reference editing on flux2-klein-9b-bf16

[._.]/ Adam Eivyf937d35b1199
diff --git a/data.reference/media-models.json b/data.reference/media-models.json
index 312e5d4c83..8db6386754 100644
--- a/data.reference/media-models.json
+++ b/data.reference/media-models.json
@@ -140,6 +140,7 @@
"runner": "flux2",
"quantization": "none",
"repo": "black-forest-labs/FLUX.2-klein-9B",
+ "kvRepo": "black-forest-labs/FLUX.2-klein-9B-kv",
"steps": 20,
"guidance": 3.5,
"cfgDisabled": true,
diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.py
index 466a327b4e..c5495a7157 100755
--- a/scripts/flux2_macos.py
+++ b/scripts/flux2_macos.py
@@ -242,6 +242,12 @@ def parse_args() -> argparse.Namespace:
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)")
+ # Reference-editing repo for the bf16 (`quantization=none`) path. The base
+ # FLUX.2-klein-9B transformer wasn't tuned for the K/V reference-editing
+ # task, so when reference images are present we load the `-kv` sibling repo
+ # instead. Absent (or no reference images) → the plain bf16 path stays on
+ # `--repo`. See server/lib/mediaModels.js `kvRepo`.
+ p.add_argument("--kv-repo", default=None, help="HF repo to load for multi-reference editing on the bf16 path (FLUX.2-klein-9B-kv)")
p.add_argument("--prompt", required=True)
p.add_argument("--negative-prompt", default="")
p.add_argument("--width", type=int, default=1024)
@@ -364,20 +370,29 @@ def main() -> None:
dtype = torch.bfloat16 if device in ("mps", "cuda") else torch.float32
use_kv = bool(args.reference_images)
- # Multi-reference editing is gated to the SDNQ Disty0 quantization today.
- # The int8 path attaches a quanto-rehydrated transformer directly and the
- # KV pipeline's reference-token attention hooks don't compose through that
- # wrapper. The bf16 path loads from the gated base 9B repo (not the kv
- # variant) whose transformer wasn't tuned for the reference-editing task,
- # so the KV pipeline would run but produce off-task output. Both paths
- # should refuse early with a clear message rather than mislead. Lift this
- # gate per quantization once the corresponding KV pipeline is validated.
- if use_kv and args.quantization in ("int8", "none"):
+ # Multi-reference editing is gated to SDNQ + bf16 today. The int8 path
+ # attaches a quanto-rehydrated transformer directly and the KV pipeline's
+ # reference-token attention hooks don't compose through that wrapper, so it
+ # still refuses early with a clear message rather than mislead. Lift the
+ # int8 gate once its KV pipeline is validated.
+ if use_kv and args.quantization == "int8":
print(
- f"❌ Multi-reference editing (--reference-images) is not supported on "
- f"{args.quantization} quantization yet. Use the SDNQ variant "
- f"(flux2-klein-9b / flux2-klein-4b) for multi-reference renders; "
- f"PLAN tracks the bf16 + KV pin as a follow-up.",
+ "❌ Multi-reference editing (--reference-images) is not supported on "
+ "int8 quantization yet. Use an SDNQ variant (flux2-klein-9b / "
+ "flux2-klein-4b) or the bf16 variant (flux2-klein-9b-bf16) for "
+ "multi-reference renders.",
+ file=sys.stderr,
+ )
+ sys.exit(64)
+ # bf16 reference editing loads the `-kv` sibling repo (whose transformer is
+ # tuned for the reference-editing task) instead of the base 9B repo. The
+ # route always threads `--kv-repo` for this model, but guard the manual /
+ # curl path so we don't silently run off-task on the base transformer.
+ if use_kv and args.quantization == "none" and not args.kv_repo:
+ print(
+ "❌ Multi-reference editing on bf16 requires --kv-repo "
+ "(the FLUX.2-klein-9B-kv sibling repo); the base 9B transformer "
+ "is not tuned for reference editing.",
file=sys.stderr,
)
sys.exit(64)
@@ -403,9 +418,13 @@ def main() -> None:
probe_hf_auth(args.base_pipeline_repo)
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, pipeline_cls)
+ # Native bf16 — `repo` is the gated base repo itself. For multi-reference
+ # editing, load the `-kv` sibling repo instead (its transformer is tuned
+ # for the K/V reference-editing task); the plain text/i2i path stays on
+ # the base repo. Both share the same FLUX.2-klein license.
+ bf16_repo = args.kv_repo if (use_kv and args.kv_repo) else args.repo
+ probe_hf_auth(bf16_repo)
+ pipe = load_pipeline_bf16(bf16_repo, device, dtype, pipeline_cls)
else:
print(f"❌ unknown quantization: {args.quantization}", file=sys.stderr)
sys.exit(64)
diff --git a/scripts/migrations/064-flux2-klein-9b-bf16-kv-repo.js b/scripts/migrations/064-flux2-klein-9b-bf16-kv-repo.js
new file mode 100644
index 0000000000..f9a718d01f
--- /dev/null
+++ b/scripts/migrations/064-flux2-klein-9b-bf16-kv-repo.js
@@ -0,0 +1,79 @@
+/**
+ * Add `kvRepo` to the flux2-klein-9b-bf16 entry so bf16 multi-reference editing
+ * loads the `-kv` sibling repo (whose transformer is tuned for the reference-
+ * editing task) instead of the base FLUX.2-klein-9B.
+ *
+ * scripts/flux2_macos.py now lifts the multi-reference gate on the bf16
+ * (`quantization=none`) path and loads `--kv-repo` when reference images are
+ * present; server/services/imageGen/local.js threads `model.kvRepo` through as
+ * `--kv-repo`. Without this field the runner refuses bf16 reference renders.
+ *
+ * `data.reference/media-models.json` ships the new value for fresh installs,
+ * and server/lib/mediaModels.js `backfillKvRepo` fills it at load — but a
+ * migration makes the change durable in `data/media-models.json` (gitignored,
+ * NOT in JSON_MERGE_TARGETS) so it survives even if the load-time backfill is
+ * ever removed. This migration adds the field only when it's absent and the
+ * `repo` still matches the pre-change shipped base repo — a user who pointed
+ * the entry at a fork keeps their config untouched.
+ *
+ * Idempotent: a second run finds `kvRepo` already present and exits without
+ * writing.
+ */
+
+import { readFile } from 'fs/promises';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+import { join } from 'path';
+
+const REL_PATH = 'data/media-models.json';
+
+const ENTRY_ID = 'flux2-klein-9b-bf16';
+const SHIPPED_REPO = 'black-forest-labs/FLUX.2-klein-9B';
+const KV_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 === ENTRY_ID);
+ if (!entry) {
+ console.log(`✅ ${REL_PATH}: no '${ENTRY_ID}' entry — user removed it, nothing to migrate`);
+ return;
+ }
+
+ if ('kvRepo' in entry) {
+ console.log(`✅ ${REL_PATH}: ${ENTRY_ID} already has kvRepo="${entry.kvRepo}" — leaving alone`);
+ return;
+ }
+
+ if (entry.repo !== SHIPPED_REPO) {
+ console.log(`✅ ${REL_PATH}: ${ENTRY_ID} repo is "${entry.repo}" (not the pre-change default) — leaving alone`);
+ return;
+ }
+
+ entry.kvRepo = KV_REPO;
+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);
+ console.log(`📝 ${REL_PATH}: set ${ENTRY_ID} kvRepo → ${KV_REPO} (enables bf16 multi-reference editing)`);
+ },
+};
diff --git a/scripts/migrations/064-flux2-klein-9b-bf16-kv-repo.test.js b/scripts/migrations/064-flux2-klein-9b-bf16-kv-repo.test.js
new file mode 100644
index 0000000000..7a53965a80
--- /dev/null
+++ b/scripts/migrations/064-flux2-klein-9b-bf16-kv-repo.test.js
@@ -0,0 +1,87 @@
+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 './064-flux2-klein-9b-bf16-kv-repo.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+const SHIPPED_REPO = 'black-forest-labs/FLUX.2-klein-9B';
+const KV_REPO = 'black-forest-labs/FLUX.2-klein-9B-kv';
+
+const baseRegistry = (entry = {}) => ({
+ image: [
+ { id: 'dev', name: 'Flux 1 Dev' },
+ {
+ id: 'flux2-klein-9b-bf16',
+ name: 'Flux 2 Klein 9B (bf16)',
+ runner: 'flux2',
+ quantization: 'none',
+ repo: SHIPPED_REPO,
+ ...entry,
+ },
+ ],
+});
+
+describe('migration 064 — flux2-klein-9b-bf16 kvRepo', () => {
+ let rootDir;
+ let path;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-064-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ path = join(rootDir, 'data', 'media-models.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('adds kvRepo to the bf16 entry when absent and repo matches the shipped default', async () => {
+ writeJson(path, baseRegistry());
+ await migration.up({ rootDir });
+ const entry = readJson(path).image.find((e) => e.id === 'flux2-klein-9b-bf16');
+ expect(entry.kvRepo).toBe(KV_REPO);
+ });
+
+ it('is idempotent — a second run leaves an already-present kvRepo alone', async () => {
+ writeJson(path, baseRegistry({ kvRepo: KV_REPO }));
+ const before = readFileSync(path, 'utf-8');
+ await migration.up({ rootDir });
+ expect(readFileSync(path, 'utf-8')).toBe(before);
+ });
+
+ it('preserves a user-customized kvRepo (even empty-string clear)', async () => {
+ writeJson(path, baseRegistry({ kvRepo: '' }));
+ await migration.up({ rootDir });
+ const entry = readJson(path).image.find((e) => e.id === 'flux2-klein-9b-bf16');
+ expect(entry.kvRepo).toBe('');
+ });
+
+ it('leaves the entry alone when repo points at a fork (not the shipped default)', async () => {
+ writeJson(path, baseRegistry({ repo: 'my-fork/FLUX.2-klein-9B' }));
+ await migration.up({ rootDir });
+ const entry = readJson(path).image.find((e) => e.id === 'flux2-klein-9b-bf16');
+ expect('kvRepo' in entry).toBe(false);
+ });
+
+ 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-bf16 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-bf16')).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.js
index 57f949f55c..6a3af06a3a 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -155,6 +155,12 @@ const DEFAULT_REGISTRY = {
runner: 'flux2',
quantization: 'none',
repo: 'black-forest-labs/FLUX.2-klein-9B',
+ // Multi-reference editing loads this `-kv` sibling repo instead of the
+ // base 9B (its transformer is tuned for the K/V reference-editing task).
+ // The plain text/i2i bf16 path stays on `repo`. Same FLUX.2-klein
+ // license — accept once at huggingface.co. Threaded to the runner as
+ // `--kv-repo`; see scripts/flux2_macos.py.
+ kvRepo: 'black-forest-labs/FLUX.2-klein-9B-kv',
steps: 20,
guidance: 3.5,
cfgDisabled: true,
@@ -379,6 +385,28 @@ const backfillEditOnly = (list) => {
});
};
+// Multi-reference editing on the bf16 path loads the `-kv` sibling repo. Map
+// each id to the kv repo it should use. Existing installs stored their
+// `flux2-klein-9b-bf16` entry before `kvRepo` existed, so backfill it at load
+// (same pattern as cfgDisabled/editOnly) AND ship migration 064 for installs
+// that have already persisted the registry. Mirrored in
+// data.reference/media-models.json. A user-set `kvRepo` (any value, including
+// '') wins — `'kvRepo' in entry` is the override signal.
+const KV_REPO_BY_ID = {
+ 'flux2-klein-9b-bf16': 'black-forest-labs/FLUX.2-klein-9B-kv',
+};
+
+const backfillKvRepo = (list) => {
+ if (!Array.isArray(list)) return list;
+ return list.map((entry) => {
+ if (!isPlainObject(entry) || typeof entry.id !== 'string') return entry;
+ if ('kvRepo' in entry) return entry; // user override wins
+ const kvRepo = KV_REPO_BY_ID[entry.id];
+ if (!kvRepo) return entry;
+ return { ...entry, kvRepo };
+ });
+};
+
export const isFlux2 = (model) => model?.runner === RUNNER_FAMILIES.FLUX2;
export const isZImage = (model) => model?.runner === RUNNER_FAMILIES.Z_IMAGE;
export const isErnie = (model) => model?.runner === RUNNER_FAMILIES.ERNIE;
@@ -496,9 +524,9 @@ const normalizeRegistry = (parsed) => {
// (treat as fresh install — let the new entries land).
const shippedImage = isPlainObject(safe._shippedDefaults?.image) ? safe._shippedDefaults.image : null;
const isImageBootstrap = shippedImage === null;
- const upgradedImage = backfillEditOnly(backfillCfgDisabled(
+ const upgradedImage = backfillKvRepo(backfillEditOnly(backfillCfgDisabled(
upgradeImageEntries(arrayOrDefault(safe.image, DEFAULT_REGISTRY.image)),
- ));
+ )));
// Image bootstrap deliberately uses userIds ONLY (not union with defaults).
// Image is getting `_shippedDefaults` for the first time in this release, so
// there's no prior history of deletions to preserve via the union trick the
diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.js
index 354a973db0..09325d5208 100644
--- a/server/lib/mediaModels.test.js
+++ b/server/lib/mediaModels.test.js
@@ -451,6 +451,45 @@ describe('mediaModels registry', () => {
expect(qwenEdit.editOnly).toBe(false);
});
+ // kvRepo — bf16 multi-reference editing loads the `-kv` sibling repo. Backfilled
+ // at load like cfgDisabled/editOnly, plus a durable migration (064).
+
+ it('fresh install: flux2-klein-9b-bf16 ships with kvRepo set to the kv sibling repo', async () => {
+ const { loadMediaModels, getImageModels } = await import('./mediaModels.js');
+ loadMediaModels();
+ const bf16 = getImageModels().find((m) => m.id === 'flux2-klein-9b-bf16');
+ expect(bf16).toBeDefined();
+ expect(bf16.kvRepo).toBe('black-forest-labs/FLUX.2-klein-9B-kv');
+ });
+
+ it('backfills kvRepo onto a pre-flag flux2-klein-9b-bf16 entry (no migration needed)', async () => {
+ writeFileSync(registryFile, JSON.stringify({
+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },
+ image: [
+ { id: 'flux2-klein-9b-bf16', name: 'Flux 2 Klein 9B (bf16)', runner: 'flux2', quantization: 'none', repo: 'black-forest-labs/FLUX.2-klein-9B', steps: 20, guidance: 3.5 },
+ ],
+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],
+ selectedTextEncoder: 't',
+ }));
+ const { getImageModels } = await import('./mediaModels.js');
+ const bf16 = getImageModels().find((m) => m.id === 'flux2-klein-9b-bf16');
+ expect(bf16.kvRepo).toBe('black-forest-labs/FLUX.2-klein-9B-kv');
+ });
+
+ it('preserves an explicit kvRepo user override (including empty-string clear)', async () => {
+ writeFileSync(registryFile, JSON.stringify({
+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },
+ image: [
+ { id: 'flux2-klein-9b-bf16', name: 'Flux 2 Klein 9B (bf16)', runner: 'flux2', quantization: 'none', repo: 'black-forest-labs/FLUX.2-klein-9B', steps: 20, guidance: 3.5, kvRepo: '' },
+ ],
+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],
+ selectedTextEncoder: 't',
+ }));
+ const { getImageModels } = await import('./mediaModels.js');
+ const bf16 = getImageModels().find((m) => m.id === 'flux2-klein-9b-bf16');
+ expect(bf16.kvRepo).toBe('');
+ });
+
it('existing install without _shippedDefaults.image gains the new z-image entries on upgrade', async () => {
// Simulate a pre-z-image registry: only flux2 and Flux 1 entries, no
// _shippedDefaults.image at all.
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 648f48508d..12ee3b3f92 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -183,6 +183,11 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
];
if (model.tokenizerRepo) args.push('--tokenizer-repo', model.tokenizerRepo);
if (model.basePipelineRepo) args.push('--base-pipeline-repo', model.basePipelineRepo);
+ // bf16 multi-reference editing loads the `-kv` sibling repo (whose
+ // transformer is tuned for reference editing) instead of `model.repo`.
+ // The runner only uses --kv-repo when --reference-images is also present;
+ // the plain text/i2i bf16 path stays on the base repo.
+ if (model.kvRepo) args.push('--kv-repo', model.kvRepo);
if (negativePrompt) args.push('--negative-prompt', negativePrompt);
if (initImagePath) args.push('--image-path', initImagePath);
if (initImagePath && initImageStrength != null) args.push('--image-strength', String(initImageStrength));
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 79263e4ee7..990d175592 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -208,6 +208,43 @@ describe('imageGen local.buildArgs flux2 dispatch', () => {
expect(args[strIdx + 2]).toBe('0.5');
});
+ it('threads --kv-repo for the bf16 model so reference editing loads the kv sibling repo', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args } = buildArgs({
+ ...baseInput,
+ referenceImagePaths: ['/safe/path/ref-a.png'],
+ referenceImageStrengths: [1.0],
+ model: {
+ id: 'flux2-klein-9b-bf16',
+ runner: 'flux2',
+ quantization: 'none',
+ repo: 'black-forest-labs/FLUX.2-klein-9B',
+ kvRepo: 'black-forest-labs/FLUX.2-klein-9B-kv',
+ },
+ });
+ // --repo stays the base bf16 repo; --kv-repo carries the kv sibling so the
+ // runner can swap only for the reference-editing path.
+ expect(args[args.indexOf('--repo') + 1]).toBe('black-forest-labs/FLUX.2-klein-9B');
+ expect(args).toContain('--kv-repo');
+ expect(args[args.indexOf('--kv-repo') + 1]).toBe('black-forest-labs/FLUX.2-klein-9B-kv');
+ expect(args).toContain('--reference-images');
+ });
+
+ it('omits --kv-repo when the model has no kvRepo field', () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ const { args } = buildArgs({
+ ...baseInput,
+ model: {
+ id: 'flux2-klein-4b',
+ runner: 'flux2',
+ quantization: 'sdnq',
+ repo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',
+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-4B',
+ },
+ });
+ expect(args).not.toContain('--kv-repo');
+ });
+
it('omits --reference-images entirely when no reference paths are supplied', () => {
mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
const { args } = buildArgs({