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
make trained FLUX.2 LoRAs actually apply at render time
[._.]/ Adam Eivy5d2c147b7336
diff --git a/scripts/lora_utils.py b/scripts/lora_utils.pyindex ae34a932d2..7435e19d40 100644--- a/scripts/lora_utils.py+++ b/scripts/lora_utils.py@@ -5,9 +5,59 @@ Shared LoRA application helpers used by `flux2_macos.py` anddiffusers' LoRA API gains new knobs (e.g. fused-scale paths)."""+import reimport sysfrom pathlib import Path+# mflux trains FLUX.2 double-block attention `to_out` as a bare Linear and+# exports the key `...transformer_blocks.N.attn.to_out.lora_*`. But diffusers'+# Flux2Attention wraps that projection in `ModuleList([Linear, Dropout])`, so+# PEFT can only attach to the inner `.0` — loading the bare key fails with+# "Target module ModuleList(...) is not supported" and the whole adapter is+# dropped (silent base render). Insert the `.0`. The anchor `\.transformer_blocks`+# (leading dot) deliberately skips `single_transformer_blocks`, whose `to_out`+# IS a bare Linear in diffusers and is already correctly keyed. Every other+# mflux target (to_q/k/v, add_*_proj, to_add_out, ff.linear_in/out, ff_context,+# single to_qkv_mlp_proj/to_out) already matches diffusers Flux2 naming.+_TO_OUT_RE = re.compile(r"(\.transformer_blocks\.\d+\.attn\.to_out)(\.(?:lora_[AB]|alpha))")+++def _remap_mflux_flux2_keys(state_dict):+ """Return (remapped_dict, n_changed) with double-block to_out keys fixed."""+ out = {}+ changed = 0+ for k, v in state_dict.items():+ nk = _TO_OUT_RE.sub(lambda m: f"{m.group(1)}.0{m.group(2)}", k)+ if nk != k:+ changed += 1+ out[nk] = v+ return out, changed+++def _lora_needs_to_out_remap(path) -> bool:+ """Cheap header-only peek — true iff this is an mflux-style FLUX.2 adapter+ keying double-block to_out without the diffusers `.0`."""+ try:+ from safetensors import safe_open+ with safe_open(path, framework="pt") as f:+ return any(_TO_OUT_RE.search(k) for k in f.keys())+ except Exception:+ return False # not a safetensors / unreadable → let load_lora_weights handle it+++def _load_one_lora(pipe, path, adapter) -> None:+ """diffusers load_lora_weights, normalizing mflux double-block to_out keys+ to the diffusers `.0` form first when needed (passing a state_dict instead+ of the path). Non-mflux adapters load straight from the path, unchanged."""+ if _lora_needs_to_out_remap(path):+ from safetensors.torch import load_file+ sd, changed = _remap_mflux_flux2_keys(load_file(path))+ print(f"🔁 mflux adapter: remapped {changed} double-block to_out key(s) → diffusers .0 form",+ file=sys.stderr, flush=True)+ pipe.load_lora_weights(sd, adapter_name=adapter)+ else:+ pipe.load_lora_weights(path, adapter_name=adapter)+def apply_loras(pipe, lora_paths, lora_scales) -> None:"""Best-effort LoRA application. On per-LoRA failure (e.g. shape@@ -30,7 +80,7 @@ def apply_loras(pipe, lora_paths, lora_scales) -> None:adapter = f"lora_{i}"print(f"🎚️ loading LoRA: {Path(path).name} (adapter={adapter})", file=sys.stderr, flush=True)try:- pipe.load_lora_weights(path, adapter_name=adapter)+ _load_one_lora(pipe, path, adapter)raw = lora_scales[i] if i < len(lora_scales) else "1.0"try:scale = float(raw)diff --git a/server/lib/runners.js b/server/lib/runners.jsindex d9c48fd640..1a3c1e328e 100644--- a/server/lib/runners.js+++ b/server/lib/runners.js@@ -83,6 +83,22 @@ export const flux2VariantFromModel = (model) => {return null;};+// The gated bf16 base repo per FLUX.2 Klein size variant. This is BOTH what a+// trained LoRA is trained against AND the only runtime that can load a LoRA at+// render time: PEFT can't inject adapters into SDNQ/int8-quantized Linear+// layers, so a LoRA on a quantized klein pipeline silently no-ops into a base+// render (see scripts/lora_utils.apply_loras). The image runner routes LoRA+// renders off the quantized repo onto this. Single source of truth — LoRA+// training (FLUX2_TRAIN_REPOS) re-exports it so the two can't drift.+export const FLUX2_BF16_BASE_REPOS = Object.freeze({+ '4b': 'black-forest-labs/FLUX.2-klein-4B',+ '9b': 'black-forest-labs/FLUX.2-klein-9B',+});++// The bf16 base repo to render a LoRA against for a given (quantized or not)+// FLUX.2 model — resolved from its size variant. null when the size is unknown.+export const flux2Bf16BaseRepo = (model) => FLUX2_BF16_BASE_REPOS[flux2VariantFromModel(model)] || null;+// Encode a (runner family, size variant) pair into the single compat-key// string the LoRA picker matches on: FLUX.2 with a known size → `flux2-4b` /// `flux2-9b`; any family without a variant → the bare family. This is the ONEdiff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 277258c355..6d5f633a49 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -33,7 +33,7 @@ import { computePixelDelta } from './regen.js';const IS_WIN = process.platform === 'win32';import { getImageModels, isFlux2, isZImage, isErnie, isHiDream, isQwen } from '../../lib/mediaModels.js';-import { usesDiffusersRunner } from '../../lib/runners.js';+import { usesDiffusersRunner, flux2Bf16BaseRepo } from '../../lib/runners.js';// Read the registry lazily — callers below hit getImageModels() at request// time. A prior `IMAGE_MODELS = Object.fromEntries(getImageModels()...)`@@ -137,20 +137,42 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he{ status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },);}- const quantization = model.quantization || 'sdnq';+ let repo = model.repo;+ let quantization = model.quantization || 'sdnq';+ let { tokenizerRepo, basePipelineRepo, kvRepo } = model;+ // LoRA + quantized base is incompatible: PEFT can't inject an adapter into+ // SDNQ/int8-quantized Linear layers, and the runner swallows the failure+ // into a base render (lora_utils.apply_loras), so the LoRA silently does+ // nothing. The adapter was trained against the bf16 base anyway — route the+ // render onto it. (kvRepo dropped: multi-ref editing + LoRA isn't auto-routed.)+ if (loraPaths?.length && quantization !== 'none') {+ const bf16 = flux2Bf16BaseRepo(model);+ if (!bf16) {+ throw new ServerError(+ `Can't render a LoRA on "${modelId}" — a LoRA needs a bf16 FLUX.2 base and the size variant couldn't be resolved`,+ { status: 400, code: 'IMAGE_GEN_LORA_NEEDS_BF16' },+ );+ }+ console.log(`🎚️ flux2 LoRA render → routing ${modelId} (${quantization}) onto bf16 base ${bf16}`);+ repo = bf16;+ quantization = 'none';+ tokenizerRepo = null;+ basePipelineRepo = null;+ kvRepo = null;+ }if (quantization !== 'sdnq' && quantization !== 'int8' && quantization !== 'none') {throw new ServerError(`FLUX.2 model "${modelId}" has unsupported quantization "${quantization}" (supported: sdnq, int8, none)`,{ status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },);}- if (quantization === 'sdnq' && !model.tokenizerRepo) {+ if (quantization === 'sdnq' && !tokenizerRepo) {throw new ServerError(`FLUX.2 SDNQ model "${modelId}" requires 'tokenizerRepo' (the gated base repo for the tokenizer)`,{ status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },);}- if (quantization === 'int8' && !model.basePipelineRepo) {+ if (quantization === 'int8' && !basePipelineRepo) {throw new ServerError(`FLUX.2 Int8 model "${modelId}" requires 'basePipelineRepo' (the gated base repo for VAE/scheduler)`,{ status: 500, code: 'IMAGE_GEN_FLUX2_MISCONFIGURED' },@@ -174,7 +196,7 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, hescriptPath,'--model', modelId,'--quantization', quantization,- '--repo', model.repo,+ '--repo', repo,'--prompt', prompt,'--height', String(height),'--width', String(width),@@ -183,13 +205,13 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he'--seed', String(seed),'--output', outputPath,];- if (model.tokenizerRepo) args.push('--tokenizer-repo', model.tokenizerRepo);- if (model.basePipelineRepo) args.push('--base-pipeline-repo', model.basePipelineRepo);+ if (tokenizerRepo) args.push('--tokenizer-repo', tokenizerRepo);+ if (basePipelineRepo) args.push('--base-pipeline-repo', basePipelineRepo);// bf16 multi-reference editing loads the `-kv` sibling repo (whose- // transformer is tuned for reference editing) instead of `model.repo`.+ // transformer is tuned for reference editing) instead of `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 (kvRepo) args.push('--kv-repo', 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.jsindex 95d9b2df99..7eb1df556a 100644--- a/server/services/imageGen/local.test.js+++ b/server/services/imageGen/local.test.js@@ -114,6 +114,64 @@ describe('imageGen local.buildArgs flux2 dispatch', () => {expect(args).not.toContain('--tokenizer-repo');});+ it('routes a LoRA render off the SDNQ repo onto the bf16 base (PEFT can\'t load onto quantized weights)', () => {+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');+ const { args } = buildArgs({+ ...baseInput,+ loraPaths: ['/data/loras/lora-trained-adam-eivy-768ef285.safetensors'],+ loraScales: [1.0],+ 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',+ },+ });+ // Quantization forced to none + repo swapped to the gated bf16 base.+ expect(args[args.indexOf('--quantization') + 1]).toBe('none');+ expect(args[args.indexOf('--repo') + 1]).toBe('black-forest-labs/FLUX.2-klein-4B');+ // SDNQ tokenizer-repo flag dropped — bf16 reads the tokenizer from the base repo.+ expect(args).not.toContain('--tokenizer-repo');+ // The LoRA still threads through to the runner.+ expect(args).toContain('--lora-paths');+ expect(args[args.indexOf('--lora-paths') + 1]).toBe('/data/loras/lora-trained-adam-eivy-768ef285.safetensors');+ });++ it('leaves a LoRA render on a bf16 model untouched (already unquantized)', () => {+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');+ const { args } = buildArgs({+ ...baseInput,+ loraPaths: ['/data/loras/x.safetensors'],+ loraScales: [1.0],+ model: {+ id: 'flux2-klein-9b-bf16',+ runner: 'flux2',+ quantization: 'none',+ repo: 'black-forest-labs/FLUX.2-klein-9B',+ },+ });+ expect(args[args.indexOf('--quantization') + 1]).toBe('none');+ expect(args[args.indexOf('--repo') + 1]).toBe('black-forest-labs/FLUX.2-klein-9B');+ });++ it('keeps a no-LoRA SDNQ render on the quantized repo', () => {+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');+ const { args } = buildArgs({+ ...baseInput,+ loraPaths: [],+ 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[args.indexOf('--quantization') + 1]).toBe('sdnq');+ expect(args[args.indexOf('--repo') + 1]).toBe('Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic');+ });+it('throws a setup hint when the flux2 venv is missing', () => {mockResolveFlux2Python.mockReturnValue(null);expect(() => buildArgs({