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: honor per-reference strengths on FLUX.2 multi-reference renders

[._.]/ Adam Eivy8a18d783a49f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e2892f79e0..7b7d15e4cb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,8 @@ TBD
- **[flux2-multi-reference-python-runner] FLUX.2 multi-reference editing on Apple Silicon.** Uploading 2–4 reference images alongside a prompt on a FLUX.2 Klein 9B render now actually conditions the output on those references instead of silently ignoring them — Image Gen routes the request through the diffusers KV-cache multi-reference pipeline. The first time you run a multi-reference render after this update, you'll be asked to accept the FLUX.2-klein-9B-kv license on Hugging Face (one click; the runner surfaces a direct link if the license is missing).
+- **FLUX.2 multi-reference: per-reference strengths are now honored end-to-end.** Each reference image's strength slider (0.0–1.0) actually controls that reference's contribution instead of being advisory — `scripts/flux2_macos.py` installs a runtime patch on diffusers' `Flux2KVLayerCache.store` (steps 1+) and `_flux2_kv_causal_attention` (step 0 extract path) that scales the per-reference V slice by its strength while leaving K and the softmax allocation intact, matching IP-Adapter-style "ref scale" semantics. 1.0 reproduces the upstream baseline, 0.0 fully ignores that reference, intermediate values attenuate proportionally. The misleading "Per-reference strengths not honored yet" warning in the Image Gen UI is gone, and the sidecar field renamed from `referenceImageStrengthsRequested` → `referenceImageStrengths` (Python sidecar `referenceStrengthsRequested` → `referenceStrengths`) since the values reflect what was actually applied. SDNQ-gate on `flux2-klein-4b` / `flux2-klein-9b` unchanged; the bf16/int8 multi-reference gate (PLAN `[flux2-bf16-kv-multi-reference-support]`) is orthogonal.
+
- **[test-route-suites-peer-fanout-mock-noise] Quieter test logs.** Two heavily-mocked route test suites stop printing ~128 misleading warnings per run that suggested peer-sync was failing.
- **Image Gen: hi-res presets opened to HiDream + Qwen-Image, plus a Qwen comic-page draft preset.** `client/src/lib/imageGenResolutions.js`'s `compatibilityKey` previously fell through to `flux1` for HIDREAM/QWEN, silently denying their natural `1024×1536` / `1536×1024` / `1536²` hi-res variants. Both runners now return their own keys, the three hi-res entries advertise compatibility for FLUX2 + QWEN + HIDREAM, and the Flux portrait/landscape entries (`832×1216`, `1216×832`) also open to them. Added a Qwen-only `1328×2048 (Qwen comic draft — experimental)` preset for US-comic-trim-aspect draft renders — past Qwen's documented ~1664 long-edge support window but coherent in practice on the 20B MMDiT; pair with a 1.5× upscale for final 1988×3056 output. Partial fix for `[hidream-qwen-client-runner-consumers]`; LoRA-picker side still pending.
diff --git a/PLAN.md b/PLAN.md
index 5d8f3d2310..93025b14ff 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -231,7 +231,7 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr
- [ ] [qwen-image-edit-init-image-required] **Qwen-Image-Edit dispatches without its required init image.** `qwen-image-edit` (registry `mediaModels.js:202`) loads `QwenImageEditPipeline` which requires an `image` arg; the entry is exposed in the normal image-gen model picker which permits text-only submission. Today the user picks the model, submits a text prompt, and the runner crashes deep inside the diffusers pipeline after loading the 20B-param model from disk. Options: (a) add an `editOnly: true` flag to the model + validate at `routes/imageGen.js` POST; (b) filter the model from the picker when no source image is uploaded; (c) reroute through a future `/api/image-gen/edit` endpoint. Touches the image route schema + UI gating — defer to a focused PR. Surfaced by codex review of PR #516 (2026-05-28).
- [ ] [hidream-requires-hf-token-fail-fast] **Probe HF token upfront for HiDream gated-encoder downloads.** `data.reference/media-models.json`'s HiDream entries carry `requiresHfToken: true` + a `licenseUrl` pointing at `meta-llama/Meta-Llama-3.1-8B-Instruct`, but `scripts/z_image_turbo.py` `load_external_text_encoder()` does NOT call `probe_hf_auth()` the way `flux2_macos.py:265` does for the base FLUX repo. A user without a valid HF token currently sees a multi-GB download attempt that fails with a 401 deep inside transformers instead of a clean upfront error. Mirror the FLUX.2 probe before invoking `transformers.from_pretrained()` on the gated encoder repo. Surfaced by /do:review of PR #516 (2026-05-28).
- [ ] [flux2-bf16-kv-multi-reference-support] **Lift the multi-reference gate on `flux2-klein-9b-bf16`.** `scripts/flux2_macos.py` (~line 280) refuses `--reference-images` on `quantization='none'` because the bf16 entry's `repo` is `black-forest-labs/FLUX.2-klein-9B` (the base 9B, not kv) — `Flux2KleinKVPipeline` would load fine (component init signatures match) but run K/V-cached reference attention against a transformer not tuned for the reference-editing task, producing off-task output. Either swap the bf16 entry's `repo` to `black-forest-labs/FLUX.2-klein-9B-kv` (which carries `flux-2-klein-9b-kv.safetensors` for the reference-tuned transformer) and ship a migration for existing installs, or thread an explicit `kvRepo` field through the runner so single-image and multi-reference renders can pull from different repos for the same logical model. Quality validation requires a 64+ GB machine to host the bf16 weights. Surfaced by gemini review of `[flux2-multi-reference-python-runner]` PR #524 (2026-05-28).
-- [ ] [flux2-runner-sidecar-tests] **Test coverage for `generateImage`'s sidecar `meta` payload.** `server/services/imageGen/local.test.js` exercises `buildArgs` (CLI emission) but never asserts on the sidecar `meta` object built inside `generateImage` — including the new `referenceImageFilenames` + `referenceImageStrengthsRequested` fields added by `[flux2-multi-reference-python-runner]`. A focused test would need to either factor the meta-builder out of `generateImage` so it's callable without spawning Python, or stub the spawn + assert on the persisted sidecar JSON. Surfaced by gemini review of PR #524 (2026-05-28).
+- [ ] [flux2-runner-sidecar-tests] **Test coverage for `generateImage`'s sidecar `meta` payload.** `server/services/imageGen/local.test.js` exercises `buildArgs` (CLI emission) but never asserts on the sidecar `meta` object built inside `generateImage` — including the `referenceImageFilenames` + `referenceImageStrengths` fields added by `[flux2-multi-reference-python-runner]` (the field was `referenceImageStrengthsRequested` before per-ref weighting was honored end-to-end on 2026-05-29). A focused test would need to either factor the meta-builder out of `generateImage` so it's callable without spawning Python, or stub the spawn + assert on the persisted sidecar JSON. Surfaced by gemini review of PR #524 (2026-05-28).
- [ ] [reference-watch-default-prompt-version-bump-check] **Re-audit `DEFAULT_TASK_INTERVALS['reference-watch'].taskMetadata` whenever `PROMPT_VERSIONS['reference-watch']` changes.** The schedule default was flipped from `readOnly: true` → `false` on 2026-05-28 because the v2 prompt instructs the agent to append `[ref-watch-…]` items to PLAN.md and commit them — the read-only guard silently defeated that on every weekly cron firing (the on-commit `triggerReferenceAnalysis` path was already correct). A future v3 of the prompt that returns to a propose-only flow would need to flip the default back. Pin: `server/services/taskSchedule.js#DEFAULT_TASK_INTERVALS` reference-watch entry must stay in sync with the prompt's behavior; tests in `taskSchedule.test.js` and `referenceRepos.test.js` pin the current contract.
## Future Ideas
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 7b33df7c57..0dd73cc7c0 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -1070,20 +1070,15 @@ export default function ImageGen() {
Reference images <span className="text-gray-500 font-normal">(up to 4 images for FLUX.2 multi-reference edit)</span>
</label>
{/*
- FLUX.2 multi-reference editing — references are now conditioned
- via diffusers' Flux2KleinKVPipeline (K/V-cache reference-token
+ FLUX.2 multi-reference editing — references are conditioned via
+ diffusers' Flux2KleinKVPipeline (K/V-cache reference-token
attention). First-time use prompts the user to accept the
FLUX.2-klein-9B-kv license on Hugging Face. Per-reference
- strengths are submitted but not honored — the KV pipeline
- doesn't expose per-ref attention weighting today, so any
- non-1.0 value logs a warning and is treated as 1.0.
+ strengths are honored end-to-end: scripts/flux2_macos.py
+ patches Flux2KVLayerCache.store + _flux2_kv_causal_attention
+ so each reference's V slice is scaled by its strength
+ (1.0 = full influence, 0.0 = ignored).
*/}
- <div className="mb-2 px-2 py-1.5 text-[11px] text-port-warning/90 bg-port-warning/10 border border-port-warning/30 rounded">
- <strong className="font-semibold">Per-reference strengths not honored yet:</strong> uploads
- condition the output via diffusers' KV-cache multi-reference pipeline, but the strength sliders
- are advisory — the pipeline doesn't expose per-reference attention weighting in its current
- release, so all references are applied at full influence.
- </div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
{referenceImages.map((slot, i) => {
const slotId = `ref-image-${i}`;
diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.py
index 2340cc87f6..466a327b4e 100755
--- a/scripts/flux2_macos.py
+++ b/scripts/flux2_macos.py
@@ -260,14 +260,102 @@ def parse_args() -> argparse.Namespace:
# 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).
+ # `--reference-strengths` is honored per-reference via a runtime patch on
+ # Flux2KVLayerCache.store + the extract-mode causal-attention helper — see
+ # `_install_per_ref_strength_patch` below. 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)")
+ p.add_argument("--reference-strengths", nargs="*", default=[], help="0..1 strength per reference image, parallel to --reference-images (1.0 = full influence, 0.0 = ignore)")
return p.parse_args()
+# Per-call config consumed by the monkey-patched KV-cache + attention helper.
+# Populated immediately before `pipe(...)` and cleared in `finally` so that a
+# subsequent generation without reference strengths runs unscaled. The patch
+# itself is installed once per process (idempotent).
+_PORTOS_KV_REF_STRENGTHS: list[float] = []
+
+
+def _install_per_ref_strength_patch() -> None:
+ """Monkey-patch diffusers' Flux2 KV path to honor per-reference strengths.
+
+ The upstream `Flux2KleinKVPipeline` concatenates all reference latents into
+ a single token sequence and caches their attention K/V on step 0; subsequent
+ steps reuse the cached tensors. Upstream does not expose per-reference
+ weighting, so this patch scales each reference's V slice by its strength —
+ in both (a) the step-0 extract-mode attention (`_flux2_kv_causal_attention`,
+ txt/img → ref path) and (b) the cache that feeds steps 1+
+ (`Flux2KVLayerCache.store`). K is left unscaled so softmax still allocates
+ attention budget across all reference tokens; only the per-token V
+ contribution is attenuated. This matches the IP-Adapter-style "ref scale"
+ convention: 1.0 reproduces upstream behavior, 0.0 zeros that reference's
+ contribution.
+ """
+ from diffusers.models.transformers import transformer_flux2 as _t2
+
+ if getattr(_t2.Flux2KVLayerCache, "_portos_per_ref_patched", False):
+ return
+
+ # One-shot warning gate — divisibility mismatch is a misuse signal
+ # (the route always sends a parallel array; only a curl caller would
+ # land here), so log once instead of spamming per-layer per-step.
+ _warned = {"divisibility": False}
+
+ def _scale_v_inplace(v_tensor, num_ref_tokens: int, offset: int):
+ """Scale `v_tensor[:, offset:offset+num_ref_tokens]` in-place per ref.
+
+ Caller is responsible for owning the tensor (either fresh via `.clone()`
+ or an already-cloned view from upstream). All-1.0 strengths short-
+ circuit before touching the tensor.
+ """
+ strengths = _PORTOS_KV_REF_STRENGTHS
+ num_refs = len(strengths)
+ if num_ref_tokens % num_refs != 0:
+ if not _warned["divisibility"]:
+ print(
+ f"⚠️ --reference-strengths count ({num_refs}) doesn't divide "
+ f"ref-token count ({num_ref_tokens}); applying full influence.",
+ file=sys.stderr,
+ )
+ _warned["divisibility"] = True
+ return
+ if all(float(s) == 1.0 for s in strengths):
+ return
+ tokens_per_ref = num_ref_tokens // num_refs
+ for i, s in enumerate(strengths):
+ sf = float(s)
+ if sf == 1.0:
+ continue
+ start = offset + i * tokens_per_ref
+ end = start + tokens_per_ref
+ v_tensor[:, start:end].mul_(sf)
+
+ # Cache patch — upstream already passes a fresh clone (see
+ # `Flux2KVAttnProcessor` / `Flux2KVParallelSelfAttnProcessor`), so we
+ # mutate it directly instead of cloning a second time per layer.
+ _original_store = _t2.Flux2KVLayerCache.store
+
+ def _store_scaled(self, k_ref, v_ref):
+ if _PORTOS_KV_REF_STRENGTHS and v_ref.shape[1] > 0:
+ _scale_v_inplace(v_ref, v_ref.shape[1], offset=0)
+ _original_store(self, k_ref, v_ref)
+
+ _t2.Flux2KVLayerCache.store = _store_scaled
+
+ # Attention patch — extract mode only (cached mode reuses the already-
+ # scaled cache). `value` here is the live combined sequence used by
+ # other tokens' attention downstream, so clone before mutating.
+ _original_attn = _t2._flux2_kv_causal_attention
+
+ def _attn_scaled(query, key, value, num_txt_tokens, num_ref_tokens, kv_cache=None, backend=None):
+ if num_ref_tokens > 0 and kv_cache is None and _PORTOS_KV_REF_STRENGTHS:
+ value = value.clone()
+ _scale_v_inplace(value, num_ref_tokens, offset=num_txt_tokens)
+ return _original_attn(query, key, value, num_txt_tokens, num_ref_tokens, kv_cache=kv_cache, backend=backend)
+
+ _t2._flux2_kv_causal_attention = _attn_scaled
+ _t2.Flux2KVLayerCache._portos_per_ref_patched = True
+
+
@install_hf_error_handler
def main() -> None:
args = parse_args()
@@ -295,18 +383,6 @@ def main() -> None:
sys.exit(64)
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 "
@@ -426,8 +502,25 @@ def main() -> None:
file=sys.stderr,
)
- with torch.inference_mode():
- result = pipe(**pipe_kwargs)
+ # Activate per-reference V-scaling for the duration of this pipe call.
+ # Padded to len(reference_pils) with 1.0 (the route always sends a full
+ # parallel array, but a curl/test caller might omit trailing slots).
+ honored_strengths: list[float] = []
+ if use_kv and reference_pils:
+ _install_per_ref_strength_patch()
+ honored_strengths = [float(s) for s in (args.reference_strengths or [])][: len(reference_pils)]
+ while len(honored_strengths) < len(reference_pils):
+ honored_strengths.append(1.0)
+ if any(s != 1.0 for s in honored_strengths):
+ entries = ", ".join(f"ref{i + 1}={s:.2f}" for i, s in enumerate(honored_strengths))
+ print(f"🎚️ per-ref strengths honored: {entries}", file=sys.stderr)
+ _PORTOS_KV_REF_STRENGTHS[:] = honored_strengths
+
+ try:
+ with torch.inference_mode():
+ result = pipe(**pipe_kwargs)
+ finally:
+ _PORTOS_KV_REF_STRENGTHS.clear()
image = result.images[0]
image.save(args.output)
@@ -454,11 +547,10 @@ def main() -> None:
if use_kv:
sidecar["pipelineClass"] = pipeline_cls.__name__
sidecar["referenceImageFilenames"] = [Path(p).name for p in args.reference_images]
- # "Requested" — the KV pipeline doesn't expose per-reference attention
- # weighting today (a non-1.0 entry only logs a warning), so the
- # sidecar must not pretend these strengths were applied. Rename when
- # diffusers exposes a real per-ref weighting knob.
- sidecar["referenceStrengthsRequested"] = [float(s) for s in (args.reference_strengths or [])]
+ # Honored end-to-end: the runtime patch on Flux2KVLayerCache.store +
+ # _flux2_kv_causal_attention scales each reference's V slice by the
+ # corresponding strength (1.0 = upstream baseline, 0.0 = ignored).
+ sidecar["referenceStrengths"] = honored_strengths
write_sidecar(args.output, sidecar)
# Free VRAM eagerly so a back-to-back generation in the same process
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 9b45b9994e..13dc596715 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -189,8 +189,8 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
// 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.
+ // 1.0 per ref); the runner honors them per-reference via a runtime patch
+ // on Flux2KVLayerCache.store + _flux2_kv_causal_attention.
if (referenceImagePaths?.length) {
args.push('--reference-images', ...referenceImagePaths);
if (referenceImageStrengths?.length) {
@@ -339,13 +339,11 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
.filter(Boolean);
const validReferenceImagePaths = validReferences.map((r) => r.path);
const validReferenceImageStrengths = validReferences.map((r) => r.strength);
- // `referenceImageStrengthsRequested` (not `…Strengths`) because the KV
- // pipeline doesn't yet expose per-reference attention weighting — non-1.0
- // values come through the route but the runner only warns, so the sidecar
- // must not claim they were applied. Mirror with the Python sidecar's
- // `referenceStrengthsRequested` field. Rename to `…Strengths` when
- // diffusers exposes a real per-ref knob.
- const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, referenceImageFilenames: validReferenceImagePaths.map((p) => basename(p)), referenceImageStrengthsRequested: validReferenceImageStrengths, createdAt: new Date().toISOString() };
+ // `referenceImageStrengths` is honored end-to-end: the FLUX.2 runner installs
+ // a Flux2KVLayerCache.store + _flux2_kv_causal_attention patch that scales
+ // each reference's V slice by the corresponding strength (1.0 = upstream
+ // baseline, 0.0 = ignored). Mirrors the Python sidecar's `referenceStrengths`.
+ const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, referenceImageFilenames: validReferenceImagePaths.map((p) => basename(p)), referenceImageStrengths: validReferenceImageStrengths, createdAt: new Date().toISOString() };
const job = { ...meta, clients: [], status: 'running' };
jobs.set(jobId, job);