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

fix: filter LoRA picker by FLUX.2 size variant (4B vs 9B)

[._.]/ Adam Eivyf6834be66963
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 511f27d88b..76b04845fa 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -39,6 +39,7 @@
## Fixed
+- **FLUX.2 LoRAs no longer silently do nothing on the wrong model size** — A LoRA trained for FLUX.2 Klein 9B has different tensor dimensions than Klein 4B, so loading a 9B LoRA onto a 4B render (or vice-versa) failed deep inside diffusers with a shape mismatch — which the runner swallowed and quietly fell back to a base render. The result: you'd select a LoRA, see it in the logs, and get the exact same image as with no LoRA. The LoRA picker now distinguishes FLUX.2 by size (4B vs 9B), not just "is it FLUX.2", and hides weights that don't match the selected model — determining a LoRA's size from its safetensors header (so self-trained LoRAs with no Civitai metadata are classified too) and falling back to the Civitai base-model tag. Switch to the matching model size and the LoRA reappears and actually applies. LoRAs whose size can't be determined are still shown (and surface a clear error if incompatible), and non-FLUX.2 runners (mflux / Z-Image / ERNIE / HiDream / Qwen) are unaffected.
- **[issue-737] Keyframe-interpolation video is smoother on high-memory Macs** — When you interpolate a video between two keyframes, the result no longer stutters on machines with plenty of memory. The clip-length cap that governs motion quality used to be pinned to a conservative 48 GB-safe value, which on any machine clamped interpolated clips so short that motion advanced in juddery near-duplicate pairs. That cap now scales with your Mac's unified memory — a 128 GB machine renders the longer clips needed for smooth motion out of the box, while machines with 64 GB or less behave exactly as before. You can still override it with the `FFLF_LTX2_PIXEL_BUDGET` setting.
- **[issue-915] Chief of Staff dry-run preview now matches what would really run** — In Dry-run autonomy mode, the "would spawn" preview for auto-run system tasks now lists only the tasks the Chief of Staff would actually start — accounting for free agent slots, retry limits, app cooldowns, and per-app caps — instead of every queued task regardless of whether it could run. The preview is now a faithful plan of the next pass.
- **Local image generation no longer thrashes VRAM on large diffusers models (Windows/CUDA)** — The shared diffusers runner behind Z-Image-Turbo, ERNIE, HiDream, and Qwen loaded a model's full weights onto the GPU at once. The big bf16 pipelines are ~19–20 GB, which on a 24 GB card leaves no room for the forward pass's activations — and on Windows the NVIDIA driver answers the overflow with silent "system memory fallback" (spilling to host RAM over PCIe) instead of an out-of-memory error, so every denoising step ran ~50× slower than the GPU is capable of. A single 1024px Z-Image-Turbo image took **35 minutes**. The runner now measures each pipeline's weight footprint and, when it would fill most of the card, switches to diffusers' model CPU offload — keeping only the active component resident (the transformer stays on the GPU across the whole denoising loop while the text encoder and VAE are paged in just for their one-shot pass). The same image now renders in **~1.5 minutes** with live step previews intact, and peak VRAM drops from ~21 GB to ~13 GB. Small models (SD-1.5, SDXL) keep the faster full-residency path. The stepwise live-preview decode is fixed to target the VAE's execution device so previews still render under offload. Override the heuristic with `PORTOS_IMAGE_OFFLOAD=1` (force offload) or `PORTOS_IMAGE_OFFLOAD=0` (force full residency).
diff --git a/client/src/components/imageGen/ImageGenSettingsForm.jsx b/client/src/components/imageGen/ImageGenSettingsForm.jsx
index 2b010e88f0..c3d05be67d 100644
--- a/client/src/components/imageGen/ImageGenSettingsForm.jsx
+++ b/client/src/components/imageGen/ImageGenSettingsForm.jsx
@@ -25,6 +25,7 @@ export default function ImageGenSettingsForm({
showLoras = false,
availableLoras = [],
currentRunnerFamily = null,
+ currentCompatKey = null,
onAppendTrigger = null,
// Style preset picker — sits above the extra-style textarea. `cfg.stylePreset`
// holds the full preset object (not just the id) so consumers can compose
@@ -95,6 +96,7 @@ export default function ImageGenSettingsForm({
selected={Array.isArray(cfg.loras) ? cfg.loras : []}
onChange={(loras) => merge({ loras })}
currentRunnerFamily={currentRunnerFamily}
+ currentCompatKey={currentCompatKey}
onAppendTrigger={onAppendTrigger}
disabled={disabled}
/>
diff --git a/client/src/components/imageGen/LoraPicker.jsx b/client/src/components/imageGen/LoraPicker.jsx
index f65de048de..65089fec09 100644
--- a/client/src/components/imageGen/LoraPicker.jsx
+++ b/client/src/components/imageGen/LoraPicker.jsx
@@ -18,16 +18,38 @@ import { Link } from 'react-router-dom';
// that the server would reject with a confusing 400.
const MAX_SELECTED_LORAS = 8;
+// Coarse family for a compat key — collapses `flux2-4b`/`flux2-9b` back to
+// `flux2` so a size-unknown LoRA still matches any flux2 model (and vice
+// versa). Non-flux2 keys are returned unchanged.
+const familyOf = (k) => (typeof k === 'string' && k.startsWith('flux2') ? 'flux2' : k);
+
export default function LoraPicker({
availableLoras = [],
selected = [],
onChange,
currentRunnerFamily,
+ // Fine-grained compat key for the selected model (e.g. 'flux2-4b'). When
+ // provided, it filters out off-size FLUX.2 LoRAs that would silently fail to
+ // load. Falls back to `currentRunnerFamily` for older callers.
+ currentCompatKey = null,
onAppendTrigger = null,
disabled = false,
}) {
if (!availableLoras.length) return null;
- const compatible = availableLoras.filter((l) => !l.runnerFamily || l.runnerFamily === currentRunnerFamily);
+ const modelKey = currentCompatKey || currentRunnerFamily;
+ // A LoRA is compatible when: it has no compat key (unknown — show it and let
+ // the runner surface any error), it matches the model exactly, or one side's
+ // size is unknown (coarse flux2 match). A `flux2-9b` LoRA is hidden from a
+ // `flux2-4b` model — the actual fix.
+ const isCompatible = (lora) => {
+ const loraKey = lora.loraCompatKey || lora.runnerFamily;
+ if (!loraKey) return true;
+ if (loraKey === modelKey) return true;
+ if (loraKey === familyOf(modelKey)) return true;
+ if (modelKey === familyOf(loraKey)) return true;
+ return false;
+ };
+ const compatible = availableLoras.filter(isCompatible);
const atCap = selected.length >= MAX_SELECTED_LORAS;
const toggle = (lora, on) => {
diff --git a/client/src/components/imageGen/LoraPicker.test.jsx b/client/src/components/imageGen/LoraPicker.test.jsx
new file mode 100644
index 0000000000..de6a43c5bc
--- /dev/null
+++ b/client/src/components/imageGen/LoraPicker.test.jsx
@@ -0,0 +1,47 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import LoraPicker from './LoraPicker';
+
+const renderPicker = (props) =>
+ render(
+ <MemoryRouter>
+ <LoraPicker onChange={vi.fn()} {...props} />
+ </MemoryRouter>,
+ );
+
+const LORAS = [
+ { filename: 'a.safetensors', name: 'Nine-B LoRA', loraCompatKey: 'flux2-9b', runnerFamily: 'flux2' },
+ { filename: 'b.safetensors', name: 'Four-B LoRA', loraCompatKey: 'flux2-4b', runnerFamily: 'flux2' },
+ { filename: 'c.safetensors', name: 'Unknown-size LoRA', loraCompatKey: 'flux2', runnerFamily: 'flux2' },
+ { filename: 'd.safetensors', name: 'MFlux LoRA', loraCompatKey: 'mflux', runnerFamily: 'mflux' },
+];
+
+describe('LoraPicker compat filtering', () => {
+ it('hides off-size FLUX.2 LoRAs but keeps the matching + unknown-size ones', () => {
+ // The bug this fixes: a flux2-9b LoRA offered for a flux2-4b model.
+ renderPicker({ availableLoras: LORAS, selected: [], currentCompatKey: 'flux2-4b', currentRunnerFamily: 'flux2' });
+ expect(screen.queryByText('Nine-B LoRA')).toBeNull(); // 9b hidden on a 4b model
+ expect(screen.getByText('Four-B LoRA')).toBeTruthy(); // exact match shown
+ expect(screen.getByText('Unknown-size LoRA')).toBeTruthy();// size unknown → still shown
+ expect(screen.queryByText('MFlux LoRA')).toBeNull(); // wrong family hidden
+ });
+
+ it('shows the 9B LoRA once the model switches to flux2-9b', () => {
+ renderPicker({ availableLoras: LORAS, selected: [], currentCompatKey: 'flux2-9b', currentRunnerFamily: 'flux2' });
+ expect(screen.getByText('Nine-B LoRA')).toBeTruthy();
+ expect(screen.queryByText('Four-B LoRA')).toBeNull();
+ });
+
+ it('falls back to currentRunnerFamily when no compat key is provided (older callers)', () => {
+ renderPicker({ availableLoras: LORAS, selected: [], currentRunnerFamily: 'mflux' });
+ expect(screen.getByText('MFlux LoRA')).toBeTruthy();
+ expect(screen.queryByText('Four-B LoRA')).toBeNull();
+ });
+
+ it('treats a LoRA with no compat key as compatible (surface error at run time)', () => {
+ const loras = [{ filename: 'legacy.safetensors', name: 'Legacy LoRA', loraCompatKey: null, runnerFamily: null }];
+ renderPicker({ availableLoras: loras, selected: [], currentCompatKey: 'flux2-4b', currentRunnerFamily: 'flux2' });
+ expect(screen.getByText('Legacy LoRA')).toBeTruthy();
+ });
+});
diff --git a/client/src/lib/runnerFamilies.js b/client/src/lib/runnerFamilies.js
index e36b3d1096..fd4bbb7396 100644
--- a/client/src/lib/runnerFamilies.js
+++ b/client/src/lib/runnerFamilies.js
@@ -11,3 +11,32 @@ export const RUNNER_FAMILIES = Object.freeze({
HIDREAM: 'hidream',
QWEN: 'qwen',
});
+
+// FLUX.2 Klein ships in two sizes with different transformer hidden dims (4B =
+// 3072, 9B = 4096), so a LoRA trained for one can't load on the other. The
+// size is encoded in the model id/repo. Returns '4b' | '9b' | null. Mirror of
+// the same helper in server/lib/runners.js.
+export const flux2VariantFromModel = (model) => {
+ for (const s of [model?.id, model?.repo]) {
+ if (typeof s !== 'string') continue;
+ const m = s.match(/(?:^|[-_/])(?:klein-?)?([49])b(?:[-_./]|$)/i);
+ if (m) return `${m[1]}b`;
+ }
+ return null;
+};
+
+// Encode a (runner family, size variant) pair into the compat-key string the
+// LoRA picker matches on. The ONE place the `<family>-<variant>` convention is
+// written client-side (LoraPicker.familyOf decodes it). Mirror of
+// server/lib/runners.js.
+export const composeCompatKey = (family, variant) =>
+ family === RUNNER_FAMILIES.FLUX2 && variant ? `${family}-${variant}` : family;
+
+// Fine-grained LoRA compatibility key for a model. FLUX.2 → `flux2-4b` /
+// `flux2-9b` (or bare `flux2` when size is unknown); every other family → its
+// runner id.
+export const loraCompatKey = (model) =>
+ composeCompatKey(
+ model?.runner || RUNNER_FAMILIES.MFLUX,
+ model?.runner === RUNNER_FAMILIES.FLUX2 ? flux2VariantFromModel(model) : null,
+ );
diff --git a/client/src/lib/runnerFamilies.test.js b/client/src/lib/runnerFamilies.test.js
new file mode 100644
index 0000000000..7dd6841c7d
--- /dev/null
+++ b/client/src/lib/runnerFamilies.test.js
@@ -0,0 +1,35 @@
+import { describe, it, expect } from 'vitest';
+import { RUNNER_FAMILIES, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runnerFamilies';
+
+// This is the client mirror of server/lib/runners.js. The server suite greps
+// this file for the helper *names*; these tests pin their *behavior* so the
+// two copies can't silently diverge.
+describe('runnerFamilies mirror', () => {
+ it('exports the canonical ids', () => {
+ expect(RUNNER_FAMILIES.FLUX2).toBe('flux2');
+ expect(RUNNER_FAMILIES.MFLUX).toBe('mflux');
+ });
+
+ it('flux2VariantFromModel reads the size from id then repo', () => {
+ expect(flux2VariantFromModel({ id: 'flux2-klein-4b' })).toBe('4b');
+ expect(flux2VariantFromModel({ id: 'flux2-klein-9b-bf16' })).toBe('9b');
+ expect(flux2VariantFromModel({ id: 'x', repo: 'Disty0/FLUX.2-klein-9B-SDNQ' })).toBe('9b');
+ expect(flux2VariantFromModel({ id: 'flux2-klein' })).toBe(null);
+ expect(flux2VariantFromModel(null)).toBe(null);
+ });
+
+ it('loraCompatKey refines flux2 and passes other families through', () => {
+ expect(loraCompatKey({ runner: 'flux2', id: 'flux2-klein-4b' })).toBe('flux2-4b');
+ expect(loraCompatKey({ runner: 'flux2', id: 'flux2-klein-9b' })).toBe('flux2-9b');
+ expect(loraCompatKey({ runner: 'flux2', id: 'flux2-klein' })).toBe('flux2');
+ expect(loraCompatKey({ runner: 'z-image', id: 'z-image-turbo-bf16' })).toBe('z-image');
+ expect(loraCompatKey({ id: 'dev' })).toBe('mflux');
+ });
+
+ it('composeCompatKey encodes a flux2 variant and leaves other cases bare', () => {
+ expect(composeCompatKey('flux2', '9b')).toBe('flux2-9b');
+ expect(composeCompatKey('flux2', null)).toBe('flux2');
+ expect(composeCompatKey('mflux', '4b')).toBe('mflux');
+ expect(composeCompatKey(null, null)).toBe(null);
+ });
+});
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 2b08ced675..affa19b931 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -18,7 +18,7 @@ import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
import StylePresetPicker from '../components/media/StylePresetPicker';
import BackendChipStrip from '../components/media/BackendChipStrip';
import { normalizeImage } from '../components/media/normalize';
-import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
+import { RUNNER_FAMILIES, loraCompatKey } from '../lib/runnerFamilies';
import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';
import HfTokenBanner from '../components/imageGen/HfTokenBanner';
import ImageGenControls from '../components/imageGen/ImageGenControls';
@@ -502,8 +502,11 @@ export default function ImageGen() {
const isEditOnlyModel = currentModel?.editOnly === true;
const editImageMissing = isLocalMode && isEditOnlyModel && initImage.source == null;
// mflux is the default runner for entries with no explicit `runner` field.
- // LoraPicker filters compatible weights itself; we just pass the family.
+ // LoraPicker filters compatible weights itself; we pass the family (for the
+ // "install one matching X" copy) and the fine-grained compat key (which
+ // distinguishes FLUX.2 4B vs 9B so off-size LoRAs are hidden).
const currentRunnerFamily = currentModel?.runner || RUNNER_FAMILIES.MFLUX;
+ const currentCompatKey = loraCompatKey(currentModel);
const refreshFlux2Status = useCallback((signal) => {
const qs = modelId ? `?modelId=${encodeURIComponent(modelId)}` : '';
@@ -1007,6 +1010,7 @@ export default function ImageGen() {
selected={selectedLoras}
onChange={setSelectedLoras}
currentRunnerFamily={currentRunnerFamily}
+ currentCompatKey={currentCompatKey}
onAppendTrigger={(words) => setPrompt((p) => appendTriggerWords(p, words))}
disabled={statusLoading}
/>
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index bf5fe5914e..fc3fcfc136 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -32,7 +32,7 @@ import { useUniverseNav } from '../hooks/useUniverseNav';
import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInput';
import ProviderModelSelector from '../components/ProviderModelSelector';
import ImageGenSettingsForm from '../components/imageGen/ImageGenSettingsForm';
-import { RUNNER_FAMILIES } from '../lib/runnerFamilies';
+import { RUNNER_FAMILIES, loraCompatKey } from '../lib/runnerFamilies';
import ShareToButton from '../components/sharing/ShareToButton';
import SyncToPeerButton from '../components/sharing/SyncToPeerButton';
import OriginBadge from '../components/sharing/OriginBadge';
@@ -3490,10 +3490,12 @@ function RenderTab({
availableBackends, defaultMode, imageModels, availableLoras = [],
handleRender, rendering, runs,
}) {
- const currentRunnerFamily = useMemo(() => {
- const currentModel = imageModels.find((m) => m.id === renderOpts.modelId);
- return currentModel?.runner || RUNNER_FAMILIES.MFLUX;
- }, [imageModels, renderOpts.modelId]);
+ const currentModel = useMemo(
+ () => imageModels.find((m) => m.id === renderOpts.modelId),
+ [imageModels, renderOpts.modelId],
+ );
+ const currentRunnerFamily = currentModel?.runner || RUNNER_FAMILIES.MFLUX;
+ const currentCompatKey = loraCompatKey(currentModel);
// Memoize the counts that drive button labels + disable states. Drafts can
// be large (full canon + variations + sheets) and ImageGenSettingsForm
// re-renders RenderTab on every keystroke into the per-batch fields.
@@ -3543,6 +3545,7 @@ function RenderTab({
showLoras
availableLoras={availableLoras}
currentRunnerFamily={currentRunnerFamily}
+ currentCompatKey={currentCompatKey}
showStylePreset
/>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
diff --git a/docs/plans/2026-06-05-lora-flux2-variant-filter.md b/docs/plans/2026-06-05-lora-flux2-variant-filter.md
new file mode 100644
index 0000000000..4757a78eb7
--- /dev/null
+++ b/docs/plans/2026-06-05-lora-flux2-variant-filter.md
@@ -0,0 +1,132 @@
+# Plan: Filter LoRA picker by FLUX.2 size variant (4B vs 9B)
+
+## Context
+
+When generating with a FLUX.2 model, selecting a LoRA had **no effect on the
+output** even though the LoRA showed up in the logs. Root cause: the user
+rendered with **Klein-4B** (transformer hidden dim **3072**) while the LoRA was
+trained for **Klein-9B** (hidden dim **4096**). The shapes don't fit, so
+diffusers' `pipe.load_lora_weights` throws a size-mismatch, and
+`scripts/lora_utils.py:40-44` catches it and continues with a base render — a
+silent fallback. Confirmed by the user's log:
+`copying a param with shape [32,16384]` (=4096×4, 9B) vs
+`current model is [32,12288]` (=3072×4, 4B).
+
+The LoRA picker's compatibility filter (`LoraPicker.jsx:30`) only matches on
+`runnerFamily`, which is `'flux2'` for **both** 4B and 9B — so it can't tell a
+9B LoRA apart from a 4B one and happily offered an incompatible weight.
+
+**Goal:** Give the picker a finer-grained "FLUX.2 variant" compatibility key so
+9B LoRAs are hidden when a 4B model is selected (and vice versa), while leaving
+all other runner families (mflux / z-image / ernie / hidream / qwen) behaving
+exactly as today.
+
+## Approach
+
+Introduce a `loraCompatKey` that refines `runnerFamily` for FLUX.2 only:
+`'flux2-4b'` / `'flux2-9b'` (and bare `'flux2'` when a variant can't be
+determined). Non-flux2 families keep using their plain `runnerFamily` string,
+so nothing else changes.
+
+- **Model side** — derive the variant from the existing `model.id` / `model.repo`
+ (e.g. `flux2-klein-4b`, `FLUX.2-klein-9B`). **No data migration needed** — the
+ strings already encode it.
+- **LoRA side** — determine the variant from (1) the safetensors **header tensor
+ shapes** (ground truth; works for self-trained LoRAs with no Civitai metadata,
+ which is exactly the user's case), falling back to (2) the Civitai
+ `baseModel` string (`"Flux.2 Klein 4B"` / `"9B"`). Persist the result to the
+ sidecar so the header is read at most once per LoRA.
+
+### Files & changes
+
+**1. `server/lib/safetensors.js` (NEW) + barrel + README + test**
+- `readSafetensorsHeader(path)` — open file handle, read the 8-byte LE u64
+ header length, read that many bytes, `JSON.parse`. Reads only the header
+ (~KB), never the multi-hundred-MB tensor payload. Uses `fs/promises` `open` +
+ partial `read`.
+- `detectFlux2VariantFromHeader(header)` — scan only tensor keys matching
+ `/transformer_blocks/` (skip text-encoder tensors so T5's own 4096 dim can't
+ cause a false `9b`). If any of those shapes contains `4096` or `16384` →
+ `'9b'`; else if `3072` or `12288` → `'4b'`; else `null`.
+- Add to `server/lib/index.js` barrel + a row in `server/lib/README.md`
+ (enforced by `server/lib/index.test.js`).
+- New `server/lib/safetensors.test.js` with a synthesized header buffer.
+
+**2. `server/lib/runners.js` + mirror `client/src/lib/runnerFamilies.js`**
+- Add two pure, string-only helpers (safe to mirror client-side):
+ - `flux2VariantFromModel(model)` → `'4b'` | `'9b'` | `null` from `id`/`repo`
+ via `/(?:^|[-_])([49])b(?:[-_]|$)/i` (id) then `/klein-?([49])b/i` (repo).
+ - `loraCompatKey(model)` → `isFlux2(model)` ? (`flux2-${variant}` or `'flux2'`)
+ : `model.runner`.
+- Extend `server/lib/runners.test.js` for both helpers across the four flux2
+ ids + a non-flux2 model.
+
+**3. `server/lib/civitai.js`**
+- Add `flux2VariantFromBaseModel(baseModel)` → `'4b'`/`'9b'`/`null` via
+ `/\b([49])b\b/i`. Cover in `civitai.test.js`.
+
+**4. `server/services/loras.js` (`listLoras`, `installFromCivitai`)**
+- In `listLoras` `mapEntry`, when `runnerFamily === 'flux2'`, resolve the
+ variant in order: sidecar `fluxVariant` → `flux2VariantFromBaseModel(civitai
+ .baseModel)` → `detectFlux2VariantFromHeader(readSafetensorsHeader(path))`.
+ Best-effort persist the resolved variant back to the sidecar
+ (`patchLoraSidecar`, `.catch` ignore) so the header is read once. Mirrors the
+ existing "re-derive `runnerFamily` on read" pattern (`loras.js:106-109`).
+- Compute and return `loraCompatKey` on each entry: `'flux2'` family →
+ `variant ? 'flux2-'+variant : 'flux2'`; otherwise the plain `runnerFamily`.
+ Keep returning `runnerFamily` too (used for display).
+- In `installFromCivitai`, stamp `fluxVariant` into the sidecar from the
+ Civitai baseModel (best-effort) so freshly-installed LoRAs are tagged without
+ a header read.
+- Extend `server/services/loras.test.js`.
+
+**5. `client/src/components/imageGen/LoraPicker.jsx`**
+- Accept a new `currentCompatKey` prop (alongside the existing
+ `currentRunnerFamily`, kept for the "install one matching X" copy).
+- Replace the filter with a variant-aware predicate:
+ ```js
+ const familyOf = (k) => (k?.startsWith('flux2') ? 'flux2' : k);
+ const isCompatible = (loraKey) =>
+ !loraKey || // unknown LoRA → still shown (current behavior)
+ loraKey === currentCompatKey || // exact variant match
+ loraKey === familyOf(currentCompatKey) ||// LoRA variant unknown → coarse flux2 match
+ currentCompatKey === familyOf(loraKey); // model variant unknown (defensive)
+ const compatible = availableLoras.filter((l) => isCompatible(l.loraCompatKey));
+ ```
+ This hides a `flux2-9b` LoRA from a `flux2-4b` model — the actual fix — while
+ unknown/coarse LoRAs stay visible (preserving the "surface a clear error
+ otherwise" philosophy in the file header).
+
+**6. Call sites — compute & pass `currentCompatKey` from the selected model**
+- `client/src/pages/ImageGen.jsx:506` — add
+ `const currentCompatKey = loraCompatKey(currentModel)` and pass to the
+ `<LoraPicker>` at ~1009 (and through `ImageGenSettingsForm` props at
+ `ImageGenSettingsForm.jsx:27,97`).
+- `client/src/pages/UniverseBuilder.jsx:3493-3545` — compute `currentCompatKey`
+ the same way next to its `currentRunnerFamily` `useMemo` and pass it down.
+
+### Out of scope (note in PLAN.md)
+- The background search surfaced a **separate** bug: the external SD-API backend
+ (`server/services/imageGen/external.js`) accepts `loraFilenames`/`loraScales`
+ but never forwards them to `/sdapi/v1/txt2img`. Unrelated to this local-FLUX.2
+ fix — capture as a follow-up.
+- Optionally surfacing a UI toast when `apply_loras` drops an off-variant LoRA
+ at render time (defense-in-depth for sidecar-replay/remix paths that bypass
+ the picker). Capture as a follow-up.
+
+## Verification
+
+1. **Unit tests:** `cd server && npm test` — new `safetensors.test.js`, extended
+ `runners.test.js`, `civitai.test.js`, `loras.test.js`; `cd client && npm test`.
+2. **End-to-end (the user's repro):**
+ - With the 9B-trained LoRA installed, select **flux2-klein-4b** in Image Gen →
+ the LoRA should now be **absent** from the picker (count shows
+ `N-1/N compatible`).
+ - Switch the model to **flux2-klein-9b** → the same LoRA **appears** and is
+ selectable.
+ - Render on 9B with the LoRA enabled and confirm logs show
+ `✅ active LoRA adapters: [('lora_0', <scale>)]` with **no** `size mismatch`
+ / `⚠️ LoRA load failed` lines, and the output visibly differs from a
+ base render.
+3. **Regression:** confirm z-image / mflux LoRAs still list unchanged (their
+ `loraCompatKey` equals `runnerFamily`).
diff --git a/server/lib/README.md b/server/lib/README.md
index 0b005ff670..c4f4db8ca1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -102,6 +102,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
| `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |
| `multipart.js` | Streaming multipart/form-data parser. |
+| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. |
| `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |
| `zipStream.js` | Streaming ZIP parser. |
| `assetHash.js` | Cross-transport SHA-256 cache for `data/images/*` — persists hashes in the asset's `.metadata.json` sidecar so the share-bucket exporter and the federated peer-sync push pipeline reuse the same value. `sidecarGenParamsHash` canonically hashes a sidecar's gen-params (excludes the machine-local `sha256` cache block) for cross-machine sidecar-convergence comparisons. |
diff --git a/server/lib/civitai.js b/server/lib/civitai.js
index 5c340720c4..4df60a348a 100644
--- a/server/lib/civitai.js
+++ b/server/lib/civitai.js
@@ -43,6 +43,17 @@ export const baseModelToRunner = (baseModel) => {
return null;
};
+// FLUX.2 Klein ships in two sizes (4B/9B) with incompatible transformer dims.
+// Civitai distinguishes them in the baseModel string ("Flux.2 Klein 4B" /
+// "Flux.2 Klein 9B"), so a Civitai-installed LoRA can be tagged without
+// reading its safetensors header. Returns '4b' | '9b' | null.
+export const flux2VariantFromBaseModel = (baseModel) => {
+ if (typeof baseModel !== 'string') return null;
+ if (baseModelToRunner(baseModel) !== RUNNER_FAMILIES.FLUX2) return null;
+ const m = baseModel.match(/\b([49])b\b/i);
+ return m ? `${m[1].toLowerCase()}b` : null;
+};
+
// Extracts model id and optional modelVersionId from any Civitai URL shape:
// https://civitai.com/models/123456
// https://civitai.com/models/123456/some-slug
@@ -287,6 +298,9 @@ export const buildSidecar = ({ model, version, file, filename }) => {
nsfw: !!model?.nsfw,
},
runnerFamily: baseModelToRunner(baseModel), // 'mflux' | 'flux2' | 'z-image' | null
+ // '4b' | '9b' | null — only meaningful for the flux2 family. Lets the LoRA
+ // picker tell a Klein-4B LoRA apart from a Klein-9B one (incompatible dims).
+ fluxVariant: flux2VariantFromBaseModel(baseModel),
triggerWords: Array.isArray(version?.trainedWords) ? version.trainedWords : [],
recommendedScale: Number.isFinite(version?.settings?.strength) ? version.settings.strength : 1.0,
file: {
diff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.js
index c307476c62..b3a19439bb 100644
--- a/server/lib/civitai.test.js
+++ b/server/lib/civitai.test.js
@@ -7,6 +7,7 @@ import {
buildSidecar,
detectEarlyAccess,
fetchCivitaiModel,
+ flux2VariantFromBaseModel,
normalizeCivitaiImageUrl,
parseCivitaiUrl,
pickPrimaryFile,
@@ -91,6 +92,22 @@ describe('baseModelToRunner', () => {
});
});
+describe('flux2VariantFromBaseModel', () => {
+ it('parses the Klein size from the Civitai baseModel string', () => {
+ expect(flux2VariantFromBaseModel('Flux.2 Klein 4B')).toBe('4b');
+ expect(flux2VariantFromBaseModel('Flux.2 Klein 9B')).toBe('9b');
+ });
+ it('returns null for a flux2 baseModel with no size', () => {
+ expect(flux2VariantFromBaseModel('Flux.2 Klein')).toBe(null);
+ });
+ it('returns null for non-flux2 families (so a "4b" elsewhere never leaks in)', () => {
+ expect(flux2VariantFromBaseModel('Flux.1 D')).toBe(null);
+ expect(flux2VariantFromBaseModel('SDXL 1.0')).toBe(null);
+ expect(flux2VariantFromBaseModel('')).toBe(null);
+ expect(flux2VariantFromBaseModel(null)).toBe(null);
+ });
+});
+
describe('pickVersion', () => {
const model = {
id: 1,
diff --git a/server/lib/index.js b/server/lib/index.js
index f12bca5497..e8f7e54eeb 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -93,6 +93,7 @@ export * from './fileWriteQueue.js';
export * from './schemaVersions.js';
export * from './imageClean.js';
export * from './multipart.js';
+export * from './safetensors.js';
export * from './assetHash.js';
export * from './pdfImageEmbed.js';
export * from './zipStream.js';
diff --git a/server/lib/runners.js b/server/lib/runners.js
index a2c1720401..09ea767569 100644
--- a/server/lib/runners.js
+++ b/server/lib/runners.js
@@ -44,3 +44,37 @@ export const isQwen = (model) => model?.runner === RUNNER_FAMILIES.QWEN;
// `server/services/imageGen/local.js`.
export const usesDiffusersRunner = (model) =>
isZImage(model) || isErnie(model) || isHiDream(model) || isQwen(model);
+
+// FLUX.2 Klein ships in two sizes with DIFFERENT transformer hidden dims —
+// 4B = 3072, 9B = 4096 — so a LoRA trained for one physically can't load on
+// the other (diffusers throws a tensor shape-mismatch, which the runner
+// swallows into a silent base render). `runner === 'flux2'` alone can't tell
+// them apart, so we refine it. The size is already encoded in the model id
+// (`flux2-klein-4b`, `flux2-klein-9b-bf16`) and repo (`FLUX.2-klein-9B`), so
+// no data migration is needed. Returns '4b' | '9b' | null.
+export const flux2VariantFromModel = (model) => {
+ for (const s of [model?.id, model?.repo]) {
+ if (typeof s !== 'string') continue;
+ const m = s.match(/(?:^|[-_/])(?:klein-?)?([49])b(?:[-_./]|$)/i);
+ if (m) return `${m[1]}b`;
+ }
+ return 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 ONE
+// place the `<family>-<variant>` convention is written, so the model-side key
+// (loraCompatKey below) and the LoRA-side key (server/services/loras.js) can't
+// drift. `LoraPicker.familyOf` is the decode side.
+export const composeCompatKey = (family, variant) =>
+ family === RUNNER_FAMILIES.FLUX2 && variant ? `${family}-${variant}` : family;
+
+// Fine-grained LoRA compatibility key for a model. For FLUX.2 it refines the
+// runner family into a size-specific key (or bare `flux2` when the size can't
+// be determined); for every other family it's just the runner id.
+export const loraCompatKey = (model) =>
+ composeCompatKey(
+ model?.runner || RUNNER_FAMILIES.MFLUX,
+ isFlux2(model) ? flux2VariantFromModel(model) : null,
+ );
diff --git a/server/lib/runners.test.js b/server/lib/runners.test.js
index e24dfd3da9..8a672e6ff8 100644
--- a/server/lib/runners.test.js
+++ b/server/lib/runners.test.js
@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
-import { RUNNER_FAMILIES, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen } from './runners.js';
+import { RUNNER_FAMILIES, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';
const __dirname_self = dirname(fileURLToPath(import.meta.url));
const CLIENT_MIRROR_PATH = join(__dirname_self, '..', '..', 'client', 'src', 'lib', 'runnerFamilies.js');
@@ -48,3 +48,72 @@ describe('RUNNER_FAMILIES', () => {
expect(isFlux2(undefined)).toBe(false);
});
});
+
+describe('flux2VariantFromModel', () => {
+ it('reads the size from the model id across all four flux2 ids', () => {
+ expect(flux2VariantFromModel({ id: 'flux2-klein-4b' })).toBe('4b');
+ expect(flux2VariantFromModel({ id: 'flux2-klein-9b' })).toBe('9b');
+ expect(flux2VariantFromModel({ id: 'flux2-klein-4b-int8' })).toBe('4b');
+ expect(flux2VariantFromModel({ id: 'flux2-klein-9b-bf16' })).toBe('9b');
+ });
+
+ it('falls back to the repo string when the id is opaque', () => {
+ expect(flux2VariantFromModel({ id: 'my-custom-model', repo: 'Disty0/FLUX.2-klein-9B-SDNQ-4bit' })).toBe('9b');
+ expect(flux2VariantFromModel({ id: 'x', repo: 'aydin99/FLUX.2-klein-4B-int8' })).toBe('4b');
+ });
+
+ it('returns null when neither id nor repo encodes a size', () => {
+ expect(flux2VariantFromModel({ id: 'flux2-klein', repo: 'foo/bar' })).toBe(null);
+ expect(flux2VariantFromModel({})).toBe(null);
+ expect(flux2VariantFromModel(null)).toBe(null);
+ });
+
+ it('does not mistake unrelated "4b"/"9b" substrings for the size token', () => {
+ // No delimiter boundary around the digits → not a size token.
+ expect(flux2VariantFromModel({ id: 'model94bit', repo: '' })).toBe(null);
+ });
+});
+
+describe('loraCompatKey', () => {
+ it('refines flux2 into size-specific keys', () => {
+ expect(loraCompatKey({ runner: 'flux2', id: 'flux2-klein-4b' })).toBe('flux2-4b');
+ expect(loraCompatKey({ runner: 'flux2', id: 'flux2-klein-9b-bf16' })).toBe('flux2-9b');
+ });
+
+ it('falls back to bare flux2 when the size is unknown', () => {
+ expect(loraCompatKey({ runner: 'flux2', id: 'flux2-klein', repo: 'foo/bar' })).toBe('flux2');
+ });
+
+ it('passes other families through as their runner id', () => {
+ expect(loraCompatKey({ runner: 'z-image', id: 'z-image-turbo-bf16' })).toBe('z-image');
+ expect(loraCompatKey({ runner: 'mflux', id: 'dev' })).toBe('mflux');
+ });
+
+ it('defaults a runner-less model to mflux (matches the picker default)', () => {
+ expect(loraCompatKey({ id: 'dev' })).toBe('mflux');
+ });
+
+ it('client mirror carries the same helpers', () => {
+ const text = readFileSync(CLIENT_MIRROR_PATH, 'utf-8');
+ expect(text).toMatch(/export const flux2VariantFromModel/);
+ expect(text).toMatch(/export const loraCompatKey/);
+ expect(text).toMatch(/export const composeCompatKey/);
+ });
+});
+
+describe('composeCompatKey', () => {
+ it('encodes a flux2 size variant, leaves other cases as the bare family', () => {
+ expect(composeCompatKey('flux2', '4b')).toBe('flux2-4b');
+ expect(composeCompatKey('flux2', '9b')).toBe('flux2-9b');
+ expect(composeCompatKey('flux2', null)).toBe('flux2'); // size unknown
+ expect(composeCompatKey('mflux', '4b')).toBe('mflux'); // non-flux2 never carries a variant
+ expect(composeCompatKey('z-image', null)).toBe('z-image');
+ expect(composeCompatKey(null, null)).toBe(null); // legacy LoRA, family unknown
+ });
+
+ it('is the single encoder behind both model-side and LoRA-side keys', () => {
+ // loraCompatKey(model) must agree with composeCompatKey on the same pair.
+ expect(loraCompatKey({ runner: 'flux2', id: 'flux2-klein-9b' }))
+ .toBe(composeCompatKey('flux2', '9b'));
+ });
+});
diff --git a/server/lib/safetensors.js b/server/lib/safetensors.js
new file mode 100644
index 0000000000..1121bbc644
--- /dev/null
+++ b/server/lib/safetensors.js
@@ -0,0 +1,97 @@
+/**
+ * Minimal safetensors header reader + FLUX.2 size-variant detector.
+ *
+ * Used by the LoRA service to tell a Klein-4B LoRA (transformer hidden dim
+ * 3072) apart from a Klein-9B LoRA (hidden dim 4096) so the picker can hide
+ * weights that diffusers would reject at load time with a tensor-shape
+ * mismatch (which `scripts/lora_utils.py` swallows, producing a silent
+ * base render). The Civitai `baseModel` string distinguishes the two too,
+ * but self-trained / hand-dropped LoRAs have no sidecar — the file header is
+ * the only ground truth there.
+ *
+ * Safetensors layout: bytes[0..8) = little-endian u64 header length N, then
+ * bytes[8..8+N) = a UTF-8 JSON object mapping tensor name → { dtype, shape,
+ * data_offsets } (plus an optional `__metadata__` key). We read ONLY that
+ * header — never the multi-hundred-MB tensor payload that follows.
+ */
+
+import { open } from 'fs/promises';
+
+// Sanity bound: a real safetensors header is a few KB to low-MB. Anything
+// past this is a corrupt/garbage length we refuse to allocate for.
+const MAX_HEADER_BYTES = 100 * 1024 * 1024; // 100 MB
+
+/**
+ * Read and parse the JSON header of a safetensors file. Returns the parsed
+ * object (tensor-name → descriptor) or `null` if the file is missing,
+ * truncated, or doesn't look like safetensors. Never throws.
+ */
+export const readSafetensorsHeader = async (path) => {
+ let handle = null;
+ try {
+ handle = await open(path, 'r');
+ const lenBuf = Buffer.alloc(8);
+ const { bytesRead } = await handle.read(lenBuf, 0, 8, 0);
+ if (bytesRead < 8) return null;
+ // readBigUInt64LE → Number is safe for any realistic header length (well
+ // under 2^53); the MAX_HEADER_BYTES guard rejects anything absurd.
+ const headerLen = Number(lenBuf.readBigUInt64LE(0));
+ if (!Number.isFinite(headerLen) || headerLen <= 0 || headerLen > MAX_HEADER_BYTES) return null;
+ const jsonBuf = Buffer.alloc(headerLen);
+ const { bytesRead: jsonRead } = await handle.read(jsonBuf, 0, headerLen, 8);
+ if (jsonRead < headerLen) return null;
+ const parsed = JSON.parse(jsonBuf.toString('utf-8'));
+ return parsed && typeof parsed === 'object' ? parsed : null;
+ } catch {
+ // Missing file, partial write, non-safetensors blob, malformed JSON —
+ // all map to "can't determine" so callers fall back gracefully.
+ return null;
+ } finally {
+ if (handle) await handle.close().catch(() => {});
+ }
+};
+
+// FLUX.2 denoiser hidden dims. Klein-4B = 3072, Klein-9B = 4096. LoRA tensors
+// project off those dims, so the values surface both directly (e.g. img_in)
+// and ×4 in the fused MLP/attention-out linears (12288 / 16384) — match both.
+const DIMS_9B = new Set([4096, 16384]);
+const DIMS_4B = new Set([3072, 12288]);
+
+/**
+ * Inspect a parsed safetensors header and classify it as a FLUX.2 Klein
+ * `'4b'` / `'9b'` LoRA, or `null` when it can't be determined.
+ *
+ * Only transformer-block tensors are considered. Text-encoder tensors are
+ * skipped on purpose: T5-XXL's own hidden dim is 4096, so a 4B LoRA that also
+ * trains the text encoder would otherwise be mis-flagged as 9B.
+ */
+export const detectFlux2VariantFromHeader = (header) => {
+ if (!header || typeof header !== 'object') return null;
+ let saw9b = false;
+ let saw4b = false;
+ for (const [name, desc] of Object.entries(header)) {
+ if (name === '__metadata__') continue;
+ // FLUX denoiser blocks are named `*single_transformer_blocks*` /
+ // `*transformer_blocks*` (diffusers) — the discriminating tensors. Skip
+ // everything else (VAE, text encoders, misc).
+ if (!/transformer_blocks/.test(name)) continue;
+ const shape = desc?.shape;
+ if (!Array.isArray(shape)) continue;
+ for (const dim of shape) {
+ if (DIMS_9B.has(dim)) saw9b = true;
+ else if (DIMS_4B.has(dim)) saw4b = true;
+ }
+ }
+ // A well-formed LoRA is one variant or the other, never both. If a malformed
+ // file somehow shows both, refuse to guess.
+ if (saw9b && !saw4b) return '9b';
+ if (saw4b && !saw9b) return '4b';
+ return null;
+};
+
+/**
+ * Convenience: read a file and classify it in one call. Returns `'4b'` /
+ * `'9b'` / `null`.
+ */
+export const detectFlux2Variant = async (path) =>
+ detectFlux2VariantFromHeader(await readSafetensorsHeader(path));
diff --git a/server/lib/safetensors.test.js b/server/lib/safetensors.test.js
new file mode 100644
index 0000000000..1b77fd99f0
--- /dev/null
+++ b/server/lib/safetensors.test.js
@@ -0,0 +1,115 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import {
+ readSafetensorsHeader,
+ detectFlux2VariantFromHeader,
+ detectFlux2Variant,
+} from './safetensors.js';
+
+// Build a valid safetensors file buffer from a header object: 8-byte LE u64
+// header length + UTF-8 JSON + a tiny fake payload byte.
+const makeFile = (header) => {
+ const json = Buffer.from(JSON.stringify(header), 'utf-8');
+ const len = Buffer.alloc(8);
+ len.writeBigUInt64LE(BigInt(json.length), 0);
+ return Buffer.concat([len, json, Buffer.from([0])]);
+};
+
+let tmpRoot;
+const writeTmp = (name, buf) => {
+ if (!tmpRoot) tmpRoot = mkdtempSync(join(tmpdir(), 'portos-safetensors-'));
+ const p = join(tmpRoot, name);
+ writeFileSync(p, buf);
+ return p;
+};
+
+afterEach(() => {
+ if (tmpRoot) { rmSync(tmpRoot, { recursive: true, force: true }); tmpRoot = null; }
+});
+
+describe('readSafetensorsHeader', () => {
+ it('parses a well-formed header', async () => {
+ const header = { 'foo.weight': { dtype: 'F16', shape: [3072, 32], data_offsets: [0, 1] } };
+ const p = writeTmp('ok.safetensors', makeFile(header));
+ expect(await readSafetensorsHeader(p)).toEqual(header);
+ });
+
+ it('returns null for a missing file', async () => {
+ expect(await readSafetensorsHeader(join(tmpdir(), 'does-not-exist.safetensors'))).toBeNull();
+ });
+
+ it('returns null for a truncated / non-safetensors blob', async () => {
+ const p = writeTmp('junk.safetensors', Buffer.from('not safetensors'));
+ expect(await readSafetensorsHeader(p)).toBeNull();
+ });
+
+ it('returns null when the declared header length is absurd', async () => {
+ const len = Buffer.alloc(8);
+ len.writeBigUInt64LE(BigInt(500 * 1024 * 1024), 0); // > MAX_HEADER_BYTES
+ const p = writeTmp('huge.safetensors', Buffer.concat([len, Buffer.from('{}')]));
+ expect(await readSafetensorsHeader(p)).toBeNull();
+ });
+});
+
+describe('detectFlux2VariantFromHeader', () => {
+ it('detects 9B from a 4096/16384-dim transformer tensor', () => {
+ const header = {
+ 'transformer.single_transformer_blocks.19.attn.to_out.lora_A.weight': { shape: [32, 16384] },
+ 'transformer.single_transformer_blocks.19.attn.to_out.lora_B.weight': { shape: [4096, 32] },
+ };
+ expect(detectFlux2VariantFromHeader(header)).toBe('9b');
+ });
+
+ it('detects 4B from a 3072/12288-dim transformer tensor', () => {
+ const header = {
+ 'transformer.single_transformer_blocks.0.attn.to_out.lora_A.weight': { shape: [32, 12288] },
+ 'transformer.single_transformer_blocks.0.attn.to_out.lora_B.weight': { shape: [3072, 32] },
+ };
+ expect(detectFlux2VariantFromHeader(header)).toBe('4b');
+ });
+
+ it('ignores text-encoder tensors so T5\'s 4096 dim does not false-positive 9B', () => {
+ // A 4B LoRA that also trains the T5 text encoder (hidden dim 4096). Only
+ // the transformer_blocks tensors should decide the variant.
+ const header = {
+ 'text_encoder_2.encoder.block.0.layer.0.SelfAttention.q.lora_A.weight': { shape: [16, 4096] },
+ 'transformer.single_transformer_blocks.0.attn.to_q.lora_B.weight': { shape: [3072, 16] },
+ };
+ expect(detectFlux2VariantFromHeader(header)).toBe('4b');
+ });
+
+ it('returns null when no transformer-block tensor identifies a dim', () => {
+ expect(detectFlux2VariantFromHeader({ 'vae.weight': { shape: [8, 8] } })).toBeNull();
+ expect(detectFlux2VariantFromHeader({ __metadata__: { foo: 'bar' } })).toBeNull();
+ });
+
+ it('returns null for malformed input', () => {
+ expect(detectFlux2VariantFromHeader(null)).toBeNull();
+ expect(detectFlux2VariantFromHeader('nope')).toBeNull();
+ });
+
+ it('refuses to guess when both variants appear', () => {
+ const header = {
+ 'transformer.single_transformer_blocks.0.attn.to_out.lora_A.weight': { shape: [32, 16384] },
+ 'transformer.single_transformer_blocks.1.attn.to_out.lora_A.weight': { shape: [32, 12288] },
+ };
+ expect(detectFlux2VariantFromHeader(header)).toBeNull();
+ });
+});
+
+describe('detectFlux2Variant (file)', () => {
+ it('reads + classifies in one call', async () => {
+ const p = writeTmp('9b.safetensors', makeFile({
+ 'transformer.single_transformer_blocks.0.attn.to_out.lora_A.weight': { shape: [32, 16384] },
+ }));
+ expect(await detectFlux2Variant(p)).toBe('9b');
+ });
+
+ it('returns null for a non-safetensors file', async () => {
+ const p = writeTmp('bad.safetensors', Buffer.from('garbage'));
+ expect(await detectFlux2Variant(p)).toBeNull();
+ });
+});
diff --git a/server/services/loras.js b/server/services/loras.js
index 9997f7d04a..b59c23a208 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -33,12 +33,15 @@ import {
buildSidecar,
detectEarlyAccess,
fetchCivitaiModel,
+ flux2VariantFromBaseModel,
normalizeCivitaiImageUrl,
parseCivitaiUrl,
pickPrimaryFile,
pickVersion,
slugifyForFilename,
} from '../lib/civitai.js';
+import { RUNNER_FAMILIES, composeCompatKey } from '../lib/runners.js';
+import { detectFlux2Variant } from '../lib/safetensors.js';
import { getSettings } from './settings.js';
const SIDECAR_SUFFIX = '.metadata.json';
@@ -107,6 +110,27 @@ export const listLoras = async () => {
const runnerFamily = baseModel
? baseModelToRunner(baseModel)
: (sidecar?.runnerFamily || null);
+ // Fine-grained FLUX.2 size variant ('4b'/'9b'). Resolve in order:
+ // stored sidecar value → Civitai baseModel string → the safetensors
+ // header (ground truth for self-trained / hand-dropped LoRAs with no
+ // Civitai metadata). Persist a header-detected value back so the header
+ // is read at most once per LoRA. Mirrors the "re-derive runnerFamily on
+ // read" healing above.
+ let fluxVariant = null;
+ if (runnerFamily === RUNNER_FAMILIES.FLUX2) {
+ fluxVariant = sidecar?.fluxVariant || flux2VariantFromBaseModel(baseModel);
+ if (!fluxVariant) {
+ fluxVariant = await detectFlux2Variant(_fullPath);
+ if (fluxVariant) {
+ // Best-effort cache — never block or fail the list on a write error.
+ patchLoraSidecar(filename, { fluxVariant }).catch(() => {});
+ }
+ }
+ }
+ // The picker matches this against the selected model's `loraCompatKey`.
+ // FLUX.2 → size-specific (or bare 'flux2' when size is unknown, so it
+ // still shows for both sizes); every other family → its runner id.
+ const loraCompatKey = composeCompatKey(runnerFamily, fluxVariant);
return {
filename,
name: sidecar?.name || fallbackName,
@@ -115,6 +139,8 @@ export const listLoras = async () => {
// sidecar fields surfaced for the picker / manager UI:
civitai: sidecar?.civitai || null,
runnerFamily,
+ fluxVariant,
+ loraCompatKey,
triggerWords: sidecar?.triggerWords || [],
// Coerce non-finite values (NaN, Infinity, missing/malformed sidecar
// fields) to the default — `?? 1.0` alone wouldn't catch NaN.
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index f8b82ef7e4..6f776d6bd7 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -63,13 +63,74 @@ describe('listLoras', () => {
const legacy = list.find((l) => l.filename === 'lora-legacy.safetensors');
expect(realstagram.name).toBe('RealStagram');
expect(realstagram.runnerFamily).toBe('mflux');
+ // Non-flux2 LoRAs: compat key is just the runner family.
+ expect(realstagram.loraCompatKey).toBe('mflux');
+ expect(realstagram.fluxVariant).toBe(null);
expect(realstagram.triggerWords).toEqual(['rstgrm']);
expect(realstagram.recommendedScale).toBe(0.85);
expect(legacy.name).toBe('legacy');
expect(legacy.runnerFamily).toBe(null);
+ expect(legacy.loraCompatKey).toBe(null);
expect(legacy.recommendedScale).toBe(1.0);
});
+ it('tags a flux2 LoRA size from the Civitai baseModel without reading the header', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ // Garbage file contents — must NOT be read since baseModel carries the size.
+ await fs.writeFile(join(tmpLoras, 'lora-f2-9b.safetensors'), 'not-a-real-safetensors');
+ await fs.writeFile(join(tmpLoras, 'lora-f2-9b.safetensors.metadata.json'), JSON.stringify({
+ filename: 'lora-f2-9b.safetensors',
+ name: 'Flux2 9B LoRA',
+ civitai: { baseModel: 'Flux.2 Klein 9B' },
+ }));
+ const list = await lorasService.listLoras();
+ const lora = list.find((l) => l.filename === 'lora-f2-9b.safetensors');
+ expect(lora.runnerFamily).toBe('flux2');
+ expect(lora.fluxVariant).toBe('9b');
+ expect(lora.loraCompatKey).toBe('flux2-9b');
+ });
+
+ it('detects a flux2 LoRA size from the safetensors header when baseModel lacks it', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ // Real header with a 9B-dim transformer tensor (16384 = 4096×4).
+ const header = {
+ 'transformer.single_transformer_blocks.0.attn.to_out.lora_A.weight': { dtype: 'F16', shape: [32, 16384], data_offsets: [0, 1] },
+ };
+ const json = Buffer.from(JSON.stringify(header), 'utf-8');
+ const len = Buffer.alloc(8);
+ len.writeBigUInt64LE(BigInt(json.length), 0);
+ await fs.writeFile(join(tmpLoras, 'lora-selftrained.safetensors'), Buffer.concat([len, json, Buffer.from([0])]));
+ // baseModel is the bare family — no size — forcing the header read.
+ await fs.writeFile(join(tmpLoras, 'lora-selftrained.safetensors.metadata.json'), JSON.stringify({
+ filename: 'lora-selftrained.safetensors',
+ name: 'Self-trained 9B',
+ civitai: { baseModel: 'Flux.2 Klein' },
+ }));
+ const list = await lorasService.listLoras();
+ const lora = list.find((l) => l.filename === 'lora-selftrained.safetensors');
+ expect(lora.runnerFamily).toBe('flux2');
+ expect(lora.fluxVariant).toBe('9b');
+ expect(lora.loraCompatKey).toBe('flux2-9b');
+ });
+
+ it('leaves loraCompatKey at bare flux2 when the size is indeterminate', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ // Unreadable header + no size in baseModel → can't determine the variant.
+ await fs.writeFile(join(tmpLoras, 'lora-f2-unknown.safetensors'), 'garbage');
+ await fs.writeFile(join(tmpLoras, 'lora-f2-unknown.safetensors.metadata.json'), JSON.stringify({
+ filename: 'lora-f2-unknown.safetensors',
+ civitai: { baseModel: 'Flux.2 Klein' },
+ }));
+ const list = await lorasService.listLoras();
+ const lora = list.find((l) => l.filename === 'lora-f2-unknown.safetensors');
+ expect(lora.runnerFamily).toBe('flux2');
+ expect(lora.fluxVariant).toBe(null);
+ expect(lora.loraCompatKey).toBe('flux2');
+ });
+
it('returns [] when PATHS.loras is a file, not a directory', async () => {
const fs = await import('fs/promises');
// Write a plain file at the loras path — stat will show isDirectory()=false.
@@ -237,6 +298,8 @@ describe('installFromCivitai', () => {
expect(sidecar.civitai.modelId).toBe(2600698);
expect(sidecar.civitai.versionId).toBe(7);
expect(sidecar.runnerFamily).toBe('mflux');
+ // Flux.1 D is not a flux2 family → no size variant.
+ expect(sidecar.fluxVariant).toBe(null);
expect(sidecar.triggerWords).toEqual(['rstgrm']);
expect(sidecar.recommendedScale).toBe(0.85);
// File on disk