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: stop a tiny LoRA underflowing into a false "no effect" refusal (#4872)

[._.]/ Adam Eivy4b6d2a014888
diff --git a/scripts/lora_effect_probe.py b/scripts/lora_effect_probe.py
index ffcec7bfa5..57ce27c548 100644
--- a/scripts/lora_effect_probe.py
+++ b/scripts/lora_effect_probe.py
@@ -243,11 +243,20 @@ def _module_rms(np, down, up, scale: float) -> float:
"""
out_features, rank = up.shape
_, in_features = down.shape
+ # float64 for the products, whatever the storage dtype. The Gram form squares
+ # the weights TWICE over (||BA||_F^2 is a product of two Gram matrices), so a
+ # legitimately tiny adapter — 1e-20 weights are unusual but real — reaches
+ # 1e-80, far below float32's ~1e-38 floor. In float32 that underflows to
+ # exactly 0.0 and the adapter is reported `zero`, which REFUSES the render.
+ # A false refusal is the worst outcome this probe can produce, and the cast
+ # costs one transient copy of two rank-sized matrices.
+ up64 = up.astype(np.float64)
+ down64 = down.astype(np.float64)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
with np.errstate(over="ignore", invalid="ignore", divide="ignore", under="ignore"):
- gram_up = up.T @ up # (rank, rank), symmetric
- gram_down = down @ down.T # (rank, rank), symmetric
+ gram_up = up64.T @ up64 # (rank, rank), symmetric
+ gram_down = down64 @ down64.T # (rank, rank), symmetric
# trace(X @ Y) for symmetric X, Y is the elementwise sum of X * Y.
total = float(np.sum(gram_up * gram_down))
if not math.isfinite(total):
diff --git a/scripts/lora_effect_probe_test.py b/scripts/lora_effect_probe_test.py
index d5ed0bc215..11307e2d98 100644
--- a/scripts/lora_effect_probe_test.py
+++ b/scripts/lora_effect_probe_test.py
@@ -252,6 +252,20 @@ def run(tmp):
check("a zero module alongside a NON-FINITE one does not refuse",
report["status"] == "ok" and report["skippedNonFinite"] == 1)
+ # A legitimately tiny adapter must not be refused. The Gram form squares the
+ # weights twice over, so 1e-20 inputs reach 1e-80 — below float32's floor.
+ # Accumulated in float32 this underflows to exactly 0.0 and the adapter is
+ # reported `zero`, which BLOCKS the render.
+ tiny = tmp / "tiny.safetensors"
+ write_safetensors(tiny, bare_pair(
+ "m",
+ np.full((1, 16), 1e-20, np.float32),
+ np.full((16, 1), 1e-20, np.float32),
+ ))
+ report = measure_lora_effect(tiny)
+ check("a tiny-but-real adapter is ok, never underflowed into a zero refusal",
+ report["status"] == "ok" and report["maxRms"] > 0)
+
# --- kohya alpha edge cases ---------------------------------------------
neg_alpha = tmp / "kohya_negative_alpha.safetensors"
write_safetensors(neg_alpha, {
diff --git a/server/lib/loraEffect.js b/server/lib/loraEffect.js
index 3bea3ee4c1..e3b6b47612 100644
--- a/server/lib/loraEffect.js
+++ b/server/lib/loraEffect.js
@@ -78,12 +78,21 @@ export const normalizeLoraEffectReport = (raw, { sizeBytes = null, mtimeMs = nul
const declared = isKnownLoraEffectStatus(raw.status) ? raw.status : LORA_EFFECT_STATUSES.UNMEASURABLE;
const measured = nonNegativeInt(raw.measured);
const zeroModules = nonNegativeInt(raw.zeroModules);
+ const skippedNonFinite = nonNegativeInt(raw.skippedNonFinite);
+ const skippedUnsupported = nonNegativeInt(raw.skippedUnsupported);
// `zero` is the only status that refuses a render, so it is the only one whose
- // internal consistency is worth checking: it must be backed by at least one
- // measurement, and by EVERY measurement being zero. A payload claiming `zero`
- // with nothing measured (a hand-edited sidecar, a future probe that redefines
- // the word) would otherwise block a render on no evidence at all.
- const status = declared === LORA_EFFECT_STATUSES.ZERO && !(measured > 0 && zeroModules === measured)
+ // internal consistency is worth checking. It must mean the WHOLE adapter is
+ // provably inert: at least one measurement, every measurement zero, and
+ // nothing skipped — a module we could not read may carry all of the effect.
+ // This mirrors the same rule in scripts/lora_effect_probe.py; it is restated
+ // here because a sidecar is untrusted input (hand-edited, or written by a
+ // future probe that redefines the word) and this is the last check before a
+ // render is refused.
+ const zeroIsBacked = measured > 0
+ && zeroModules === measured
+ && skippedNonFinite === 0
+ && skippedUnsupported === 0;
+ const status = declared === LORA_EFFECT_STATUSES.ZERO && !zeroIsBacked
? LORA_EFFECT_STATUSES.UNMEASURABLE
: declared;
// Statistics only exist alongside a measurement. Dropping them when
@@ -96,8 +105,8 @@ export const normalizeLoraEffectReport = (raw, { sizeBytes = null, mtimeMs = nul
status,
modules: nonNegativeInt(raw.modules),
measured,
- skippedNonFinite: nonNegativeInt(raw.skippedNonFinite),
- skippedUnsupported: nonNegativeInt(raw.skippedUnsupported),
+ skippedNonFinite,
+ skippedUnsupported,
zeroModules,
medianRms: stat(raw.medianRms),
maxRms: stat(raw.maxRms),
diff --git a/server/lib/loraEffect.test.js b/server/lib/loraEffect.test.js
index 741f1f2373..5ff8d4c7a9 100644
--- a/server/lib/loraEffect.test.js
+++ b/server/lib/loraEffect.test.js
@@ -140,6 +140,7 @@ describe('loraEffectIssue', () => {
it('refuses a measured entirely-zero adapter, carrying the probe reason', () => {
const report = normalizeLoraEffectReport({
...okPayload, status: 'zero', measured: 4, zeroModules: 4,
+ skippedNonFinite: 0, skippedUnsupported: 0,
medianRms: 0, maxRms: 0, reason: 'all 4 measurable LoRA module(s) have exactly zero effect',
});
expect(loraEffectIssue(report)).toMatch(/zero effect/);
@@ -157,6 +158,10 @@ describe('loraEffectIssue', () => {
{ ...okPayload, status: 'zero', measured: 0, zeroModules: 0 },
{ ...okPayload, status: 'zero', measured: 0, zeroModules: 4 },
{ ...okPayload, status: 'zero', measured: 6, zeroModules: 3 },
+ // Skipped modules mean the adapter is not PROVABLY inert — one we could
+ // not read may carry all of its effect. Mirrors the probe's own rule.
+ { ...okPayload, status: 'zero', measured: 1, zeroModules: 1, skippedUnsupported: 1, skippedNonFinite: 0 },
+ { ...okPayload, status: 'zero', measured: 1, zeroModules: 1, skippedUnsupported: 0, skippedNonFinite: 2 },
]) {
const report = normalizeLoraEffectReport(bogus);
expect(report.status).toBe('unmeasurable');
@@ -167,6 +172,7 @@ describe('loraEffectIssue', () => {
it('keeps a zero verdict that every measurement backs', () => {
const report = normalizeLoraEffectReport({
...okPayload, status: 'zero', measured: 4, zeroModules: 4, medianRms: 0, maxRms: 0,
+ skippedNonFinite: 0, skippedUnsupported: 0,
});
expect(report.status).toBe('zero');
expect(loraEffectIssue(report)).not.toBeNull();
diff --git a/server/services/loras.js b/server/services/loras.js
index 8e58545212..87960cf6f3 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -29,6 +29,7 @@ import { atomicWrite, assertSafeFilename, ensureDir, listDirectoryByExtension, s
import { verifySafetensorsStructure } from '../lib/hfCache.js';
import { isPlainObject } from '../lib/objects.js';
import { readCachedLoraEffectReport } from '../lib/loraEffect.js';
+import { createKeyedFileWriteQueue } from '../lib/fileWriteQueue.js';
import {
applyDownloadToken,
baseModelToRunner,
@@ -278,6 +279,14 @@ export const deleteLora = async (filename) => {
// Patch the sidecar with user-editable fields (name, recommendedScale, notes).
// Civitai-derived fields are passed through but the route layer scopes the
// patch so callers can't trample those.
+// One sidecar patch at a time per LoRA. Every patch is a read-modify-write of a
+// whole JSON document, and there are now several writers: the user renaming a
+// LoRA in the manager, listLoras() healing keyLayout/fluxVariant on read, and
+// the effect probe caching its measurement when it finishes. Interleaved, the
+// last write wins the whole file and silently drops the other's field. Keyed, so
+// patches to different LoRAs still run in parallel.
+const queueSidecarWrite = createKeyedFileWriteQueue();
+
export const patchLoraSidecar = async (filename, patch) => {
assertSafeLoraFilename(filename);
const filePath = join(PATHS.loras, filename);
@@ -294,10 +303,14 @@ export const patchLoraSidecar = async (filename, patch) => {
{ status: 400, code: 'INVALID_LORA_FILE' },
);
}
- const current = (await readSidecar(filename)) || { filename };
- const next = { ...current, ...patch, filename };
- await atomicWrite(sidecarPath(filename), JSON.stringify(next, null, 2) + '\n');
- return next;
+ // The read has to be INSIDE the queued cycle — reading before joining the
+ // queue would merge against a snapshot the previous write already superseded.
+ return queueSidecarWrite(filename, async () => {
+ const current = (await readSidecar(filename)) || { filename };
+ const next = { ...current, ...patch, filename };
+ await atomicWrite(sidecarPath(filename), JSON.stringify(next, null, 2) + '\n');
+ return next;
+ });
};
// Stamp the classified safetensors key layout onto a freshly-built sidecar so
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index aa249db9d2..4567aa6fb6 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -336,6 +336,45 @@ describe('patchLoraSidecar', () => {
});
});
+// The sidecar is one JSON document with several writers — the manager renaming a
+// LoRA, listLoras() healing keyLayout on read, and the effect probe caching its
+// measurement. Each patch is a read-modify-write of the WHOLE file, so
+// interleaved cycles let the last writer silently drop the other's field.
+describe('patchLoraSidecar — concurrent patches', () => {
+ it('merges every field when two patches race, rather than last-write-wins', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'shared.safetensors'), 'weights');
+ await fs.writeFile(join(tmpLoras, 'shared.safetensors.metadata.json'), JSON.stringify({
+ filename: 'shared.safetensors', name: 'Original',
+ }));
+
+ await Promise.all([
+ lorasService.patchLoraSidecar('shared.safetensors', { name: 'Renamed' }),
+ lorasService.patchLoraSidecar('shared.safetensors', { effectReport: { status: 'ok', measured: 4 } }),
+ lorasService.patchLoraSidecar('shared.safetensors', { keyLayout: 'comfyui' }),
+ ]);
+
+ const written = JSON.parse(await fs.readFile(join(tmpLoras, 'shared.safetensors.metadata.json'), 'utf-8'));
+ expect(written.name).toBe('Renamed');
+ expect(written.keyLayout).toBe('comfyui');
+ expect(written.effectReport).toMatchObject({ status: 'ok', measured: 4 });
+ });
+
+ it('does not serialize patches to DIFFERENT LoRAs behind each other', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ for (const name of ['a.safetensors', 'b.safetensors']) {
+ await fs.writeFile(join(tmpLoras, name), 'weights');
+ }
+ const [a, b] = await Promise.all([
+ lorasService.patchLoraSidecar('a.safetensors', { name: 'A' }),
+ lorasService.patchLoraSidecar('b.safetensors', { name: 'B' }),
+ ]);
+ expect([a.name, b.name]).toEqual(['A', 'B']);
+ });
+});
+
describe('installFromCivitai', () => {
// Build a fake Civitai model JSON we can hand to the fetchImpl.
const FAKE_MODEL = {