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

add LoRA training checkpoint selection and tune defaults to avoid divergence

[._.]/ Adam Eivy475bfaa6b28a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 94bb2e9e5f..6a72049d6d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,10 @@
- **LoRA dataset workbench gains a "Re-caption all" button — re-run every caption through a new model** — "Caption all" already skips images that already have a caption (it only fills in the uncaptioned ones), so there was no one-click way to re-run a whole dataset through a freshly-picked vision model. A new **Re-caption all** button next to it sends `overwrite: true`, re-captioning every ready image with the model chosen in the caption-model picker (overwriting existing captions, including manual edits — the button's tooltip says so). The single-image "Re-caption" button already overwrote one image; this extends the same intent to the whole set. (`client/src/pages/LoraDatasetDetail.jsx`)
+- **LoRA training picks the best checkpoint instead of blindly deploying the final step — and you can promote any checkpoint by eye** — A FLUX.2 character LoRA could finish "successfully" yet render garbage: the trainer always handed back the FINAL step's adapter, but late training **divergence** (a recurring FLUX.2 failure — the loss keeps dropping while the sample image collapses to a near-black frame) made that final step the worst one. Loss is no guide here; on the run that motivated this it was *anti-correlated* with quality (the lowest-loss checkpoint was visually broken). Two changes close the gap: (1) a **collapse guard** at finalize analyzes each checkpoint's preview (sharp entropy + per-channel stdev) and, when the final preview is a degenerate near-black/near-uniform collapse, deploys the latest *healthy* checkpoint instead and flags the run for review — calibrated with a wide margin (a real frame measured entropy 5.5–7.1 vs the collapse's 2.8) so it never vetoes a legitimate image; (2) a new **checkpoint picker** under a completed run (`/media/training`) shows every saved checkpoint as a preview thumbnail with its step + loss, and a **"Use this"** button re-extracts that step's adapter and overwrites the deployed LoRA in place — the human override for subtler degradation the guard leaves alone. Per-checkpoint loss is now captured at checkpoint time, and `lib/zipStream` gains `extractZipEntryToBuffer` to crack one adapter out of an mflux checkpoint zip long after the trainer exited. The final debounced checkpoint/sample now flush to the run record before finalize reads it, so the guard always sees the last artifacts. (`server/services/loraTraining/checkpoints.js`, `server/services/loraTraining/index.js`, `server/lib/zipStream.js`, `server/routes/loraTraining.js`, `client/src/components/loraTraining/CheckpointPicker.jsx`)
+
+- **LoRA training defaults tuned down to avoid divergence** — The default training recipe drove the divergence above: at 1000 steps / learning-rate 1e-4 the sample collapsed by ~step 500 while the loss kept falling. Defaults are now **600 steps, lr 5e-5, 768px** (up from 512 — a 4K source crushed to 512 loses the face), with checkpoint/sample cadence tightened to every 150 steps so the picker has more healthy steps to choose from. Existing installs that pinned their own `settings.loraTraining.defaults` keep them. (`server/services/loraTraining/runtimes.js`)
+
- **CoS system jobs can now pin their own AI provider + model** — Each autonomous "System Task" (Chief of Staff → Jobs) gains an optional **AI Provider & Model** picker in its create and edit forms, so a heavy refactor job can run on Opus while a lightweight triage job runs on a cheaper/local model — independently, per job, instead of every job inheriting the single active provider. The override is forwarded into the generated task's metadata on both the scheduled and manual-trigger paths, where the agent runner already honors `metadata.provider`/`metadata.model`. Leaving the picker on its defaults preserves the prior behavior (active provider, per-task model selection). Only AI-agent jobs show the picker; shell/script jobs never reach the AI runner. A pinned provider is now resolved *before* the active-provider availability gate, so a job pinned to a healthy provider runs even when the globally active provider is down or unset. (`client/src/components/cos/tabs/JobsTab.jsx`, `server/services/autonomousJobs/crud.js`, `server/services/autonomousJobs/skillTemplates.js`, `server/services/agentProviderResolution.js`, `server/routes/cosJobRoutes.js`, `server/lib/validation.js`)
- **LoRA captioning now guarantees a vision model, lets you pick it, and can pull from your gallery** — Auto-captioning a training dataset used to silently send images to whatever model the local backend defaulted to; a text-only model would fail every image with a cryptic `Model does not support images` 400. The captioner now resolves (and validates) a **vision-capable** model up front: it auto-picks the first installed vision model across Ollama + LM Studio, and fails the whole run with one actionable message if none is installed — instead of N per-image errors. A new **caption-model picker** on the dataset workbench lists your installed vision models (each tagged with its backend) and persists the choice to `settings.loraTraining`, so "Caption all" and per-image re-caption both use it; "Auto" defers to the auto-pick. Vision capability is detected from explicit backend metadata when available (LM Studio's `type: 'vlm'`, Ollama's `vision` capability) and an id heuristic otherwise (`isVisionModel`, mirrored client-side). And a new **"From gallery"** button imports images you've already generated/saved straight into the dataset (multi-select, copied independently so deleting the gallery original won't strand the dataset). (`server/lib/localModelHeuristics.js`, `server/services/loraDatasetCaption.js`, `server/services/loraDatasets.js`, `server/services/localLlm.js`, `client/src/components/loraTraining/CaptionModelPicker.jsx`, `client/src/components/loraTraining/ImportGalleryDialog.jsx`)
@@ -26,6 +30,10 @@
## Fixed
+- **mflux-trained FLUX.2 LoRAs now load into diffusers (double-block `to_out` key mismatch)** — Even on the bf16 base, an mflux-trained adapter failed to load with `Target module ModuleList(...) is not supported`, so the whole LoRA was dropped and the render fell back to base. Cause: mflux targets a double transformer block's `attn.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])` — PEFT needs the inner `.0`. The shared LoRA loader (`scripts/lora_utils.py`) now normalizes mflux adapters on load: it inserts the `.0` for double-block `to_out` only (single-block `to_out` is a bare Linear in diffusers and is left alone), then hands diffusers the remapped state dict. Verified against the real diffusers Flux2 structure — all 100 of the adapter's target modules resolve to `nn.Linear` after the fix. Self-healing: existing trained LoRAs are fixed at load time with no re-training or migration. Every other mflux target already matched diffusers naming. (`scripts/lora_utils.py`)
+
+- **Trained character LoRAs now actually apply at render time (were silently ignored on quantized FLUX.2)** — A trained LoRA attached to a FLUX.2 Klein render did *nothing*: the default inference model is the **SDNQ 4-bit quantized** Klein, and PEFT can't inject an adapter into SDNQ-quantized `Linear` layers (`Target module SDNQLinear … is not supported`). The runner's LoRA loader is best-effort, so it logged the failure and rendered the **base model anyway** — every "LoRA" render was the plain base, which looked like a broken LoRA. Since a trained adapter is trained against the bf16 base, the image runner now **auto-routes any LoRA render off the quantized repo onto the gated bf16 base** (`black-forest-labs/FLUX.2-klein-{4B,9B}`, resolved from the model's size variant) with `quantization=none`; non-LoRA renders stay on the fast SDNQ/Int8 path. The bf16 base repos are now a single source of truth in `lib/runners.js` that LoRA training reuses, so the train-against and render-against repos can't drift. (`server/lib/runners.js`, `server/services/imageGen/local.js`, `server/services/loraTraining/runtimes.js`)
+
- **LoRA training that died with a bare "exited with code 2" now says what actually broke — and a stale mflux fails loudly instead** — A FLUX.2 LoRA training run could fail instantly with the useless message `Training exited with code 2 — ❌ mflux trainer exited with code 2`. The real cause was a stale **mflux 0.12.x** in the local image-gen venv: that version predates FLUX.2 LoRA training, so its `mflux-train` CLI rejected the wrapper's `--config` flag (it wants `--train-config`) and had no `flux2-klein-*` base models — argparse exited 2 before any work began. The actual argparse error was lost because the wrapper merges mflux's stderr into stdout, leaving the Node failure classifier's stderr window empty. Two fixes: (1) on a non-zero exit the wrapper now replays the trainer's last ~40 output lines to stderr (so tracebacks, argparse errors, and version-mismatch complaints reach the classifier instead of vanishing), and a new `CLI_MISMATCH` classification turns the argparse rejection into an actionable *"your mflux is too old for FLUX.2 LoRA training — `pip install -U 'mflux>=0.17'`"*; (2) `scripts/setup-image-video.sh` now pins **`mflux>=0.17`** (the first release with FLUX.2 training) and lets pip resolve mflux's declared runtime deps instead of a hand-kept list — mflux 0.17 imports packages the old list omitted (pillow, matplotlib, platformdirs, sentencepiece, …) and constrains `transformers>=5,<6` and `mlx<0.32`, so the stale list (which pinned `transformers<5` and an unbounded `mlx`) would have left `mflux-train` failing at import. (`scripts/train_mflux_lora.py`, `server/services/loraTraining/failure.js`, `scripts/setup-image-video.sh`)
- **Concurrent LoRA caption runs no longer fan out parallel requests at a single-GPU backend** — Within one run the captioner already processes images one at a time, but nothing stopped several runs from overlapping (captioning two datasets at once, re-captioning multiple single images, or a double-click). Each run is a detached loop, so concurrent runs fired N parallel `/chat/completions` requests at the same local Ollama/LM Studio — and on one GPU that's pure downside: every Ollama parallel slot reserves its own 32K-token KV cache, so concurrent vision requests multiply VRAM and risk an OOM or model reload, while parallel decoding gives no throughput win (it just time-slices the same compute and makes each request slower). A module-level mutex now serializes every caption vision call across all runs, holding backend load at concurrency 1 regardless of how many runs are in flight. One-shot vision calls (voice `ui_describe_visually`, the vision-test page) stay off the lock so a long batch run can't FIFO-starve an interactive describe. (`server/services/loraDatasetCaption.js`)
diff --git a/client/src/components/loraTraining/CheckpointPicker.jsx b/client/src/components/loraTraining/CheckpointPicker.jsx
new file mode 100644
index 0000000000..e3c5d8740e
--- /dev/null
+++ b/client/src/components/loraTraining/CheckpointPicker.jsx
@@ -0,0 +1,143 @@
+/**
+ * Manual checkpoint picker for a completed training run.
+ *
+ * A LoRA run keeps every periodic checkpoint, but only one is registered as
+ * the usable LoRA. The trainer's FINAL step is often NOT the best — late
+ * divergence (loss still dropping while the sample collapses to a black frame)
+ * is a recurring FLUX.2 failure, and loss is no guide (it was anti-correlated
+ * with quality on the run this was built for). So the user picks by eye from
+ * the preview thumbnails; the server re-extracts that step's adapter and
+ * overwrites the deployed LoRA in place.
+ */
+
+import { useState, useCallback } from 'react';
+import { Layers, Loader2, CheckCircle2, AlertTriangle } from 'lucide-react';
+import toast from '../ui/Toast';
+import {
+ listLoraTrainingCheckpoints,
+ promoteLoraTrainingCheckpoint,
+} from '../../services/api';
+
+export default function CheckpointPicker({ run, onPromoted }) {
+ const [expanded, setExpanded] = useState(false);
+ const [checkpoints, setCheckpoints] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [promotingStep, setPromotingStep] = useState(null);
+
+ const load = useCallback(() => {
+ setLoading(true);
+ listLoraTrainingCheckpoints(run.id)
+ .then((res) => setCheckpoints(Array.isArray(res?.checkpoints) ? res.checkpoints : []))
+ .catch(() => setCheckpoints([]))
+ .finally(() => setLoading(false));
+ }, [run.id]);
+
+ const toggle = () => {
+ const next = !expanded;
+ setExpanded(next);
+ if (next && checkpoints === null) load();
+ };
+
+ const promote = async (step) => {
+ setPromotingStep(step);
+ try {
+ await promoteLoraTrainingCheckpoint(run.id, step, { silent: true });
+ toast.success(`Promoted checkpoint @ step ${step}`);
+ // Reactive: mark the chosen step deployed locally, then refetch + bubble
+ // up so the parent's run record (loraFilename, selected step) refreshes.
+ setCheckpoints((prev) => prev?.map((c) => ({ ...c, deployed: c.step === step })) ?? prev);
+ load();
+ onPromoted?.();
+ } catch (err) {
+ toast.error(`Promote failed: ${err?.message || 'unknown error'}`);
+ } finally {
+ setPromotingStep(null);
+ }
+ };
+
+ const autoSelected = run.output?.autoSelectedCheckpoint;
+
+ return (
+ <div className="border-t border-port-border pt-2 mt-1">
+ <button
+ type="button"
+ onClick={toggle}
+ className="text-xs text-gray-300 hover:text-white flex items-center gap-1.5"
+ aria-expanded={expanded}
+ >
+ <Layers className="w-3.5 h-3.5 text-port-accent" />
+ Checkpoints{checkpoints ? ` (${checkpoints.length})` : ''}
+ <span className="text-gray-500">{expanded ? '▲' : '▼'}</span>
+ </button>
+
+ {autoSelected && (
+ <div className="mt-1.5 text-[11px] text-port-warning flex items-start gap-1">
+ <AlertTriangle className="w-3 h-3 mt-0.5 shrink-0" />
+ Final step diverged — auto-selected an earlier checkpoint. Review the previews and promote a better one if needed.
+ </div>
+ )}
+
+ {expanded && (
+ <div className="mt-2">
+ {loading && (
+ <div className="text-xs text-gray-400 flex items-center gap-1.5">
+ <Loader2 className="w-3.5 h-3.5 animate-spin" /> Loading checkpoints…
+ </div>
+ )}
+ {!loading && checkpoints?.length === 0 && (
+ <div className="text-xs text-gray-500">No checkpoints recorded for this run.</div>
+ )}
+ {!loading && !!checkpoints?.length && (
+ <>
+ <div className="text-[11px] text-gray-500 mb-1.5">
+ Pick by the preview — loss is shown but is not a quality ranking.
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
+ {checkpoints.map((c) => (
+ <div
+ key={c.step}
+ className={`rounded border p-1.5 flex flex-col gap-1 ${
+ c.deployed ? 'border-port-success bg-port-success/10' : 'border-port-border bg-port-bg'
+ }`}
+ >
+ {c.previewUrl ? (
+ <img
+ src={c.previewUrl}
+ alt={`step ${c.step} preview`}
+ className="w-full aspect-square object-cover rounded"
+ loading="lazy"
+ />
+ ) : (
+ <div className="w-full aspect-square rounded bg-port-card flex items-center justify-center text-[10px] text-gray-500">
+ no preview
+ </div>
+ )}
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="text-gray-300">step {c.step}</span>
+ {c.loss != null && <span className="text-gray-500" title="training loss (not a quality score)">L {c.loss.toFixed(3)}</span>}
+ </div>
+ {c.deployed ? (
+ <span className="text-[11px] text-port-success flex items-center gap-1">
+ <CheckCircle2 className="w-3 h-3" /> Deployed
+ </span>
+ ) : (
+ <button
+ type="button"
+ onClick={() => promote(c.step)}
+ disabled={promotingStep != null}
+ className="text-[11px] px-1.5 py-1 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 disabled:opacity-50 flex items-center justify-center gap-1"
+ >
+ {promotingStep === c.step ? <Loader2 className="w-3 h-3 animate-spin" /> : null}
+ Use this
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsx
index 7e05c5684b..830c2fdab5 100644
--- a/client/src/components/loraTraining/TrainingPanel.jsx
+++ b/client/src/components/loraTraining/TrainingPanel.jsx
@@ -12,6 +12,7 @@ import { Link } from 'react-router-dom';
import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles } from 'lucide-react';
import toast from '../ui/Toast';
import { useSseProgress } from '../../hooks/useSseProgress';
+import CheckpointPicker from './CheckpointPicker';
import {
getLoraTrainingStatus,
listLoraTrainingRuns,
@@ -154,6 +155,9 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
)}
</div>
)}
+ {lastRun?.status === 'completed' && (
+ <CheckpointPicker run={lastRun} onPromoted={refreshRuns} />
+ )}
<div className="grid grid-cols-2 gap-3">
<div className="col-span-2">
<label htmlFor="lt-base-model" className="block text-xs text-gray-400 mb-1">Base model</label>
diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.js
index e6df504750..b43942eb03 100644
--- a/client/src/services/apiLoraTraining.js
+++ b/client/src/services/apiLoraTraining.js
@@ -88,6 +88,18 @@ export const getLoraTrainingRun = (runId) => request(`/lora-training/runs/${runI
export const cancelLoraTrainingRun = (runId) =>
request(`/lora-training/runs/${runId}/cancel`, { method: 'POST' });
+// Checkpoints for a finished run — each with step, loss, preview thumbnail,
+// and which one is currently deployed. Drives the manual checkpoint picker.
+export const listLoraTrainingCheckpoints = (runId) =>
+ request(`/lora-training/runs/${runId}/checkpoints`);
+
+// Promote a checkpoint to be the deployed LoRA (re-extracts that step's
+// adapter and overwrites the run's registered .safetensors in place).
+export const promoteLoraTrainingCheckpoint = (runId, step, { silent = false } = {}) =>
+ request(`/lora-training/runs/${runId}/promote-checkpoint`, {
+ method: 'POST', body: JSON.stringify({ step }), silent,
+ });
+
export const deleteLoraTrainingRun = (runId, { deleteLora = false } = {}) =>
request(`/lora-training/runs/${runId}${deleteLora ? '?deleteLora=true' : ''}`, { method: 'DELETE' });
diff --git a/server/lib/README.md b/server/lib/README.md
index 5c81d10281..ce2c107f00 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -108,7 +108,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
+| `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. |
| `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. |
## Process execution
diff --git a/server/lib/zipStream.js b/server/lib/zipStream.js
index 68b3dde894..de676206a9 100644
--- a/server/lib/zipStream.js
+++ b/server/lib/zipStream.js
@@ -12,6 +12,7 @@
*/
import { createInflateRaw } from 'zlib';
+import { createReadStream } from 'fs';
import { EventEmitter } from 'events';
import { PassThrough, Writable } from 'stream';
@@ -181,3 +182,41 @@ export function parseZip() {
return sink;
}
+
+/**
+ * Extract the first entry whose path satisfies `match` (a predicate or a
+ * substring) from a zip on disk, resolving to its decompressed Buffer (or null
+ * if nothing matched). Convenience over parseZip() for the random-single-member
+ * case — e.g. cracking one `*_adapter.safetensors` out of a training
+ * checkpoint zip long after the trainer process is gone (loraTraining).
+ * Entries before the match are drained without inflation, so reaching a late
+ * member costs a sequential disk read but no needless decompression.
+ */
+export function extractZipEntryToBuffer(zipPath, match) {
+ const test = typeof match === 'function' ? match : (name) => name.includes(match);
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ let matched = false;
+ const done = (fn, val) => { if (!settled) { settled = true; fn(val); } };
+ const src = createReadStream(zipPath);
+ src.on('error', (err) => done(reject, err));
+ const parser = parseZip();
+ parser.on('error', (err) => done(reject, err));
+ parser.on('entry', (entry) => {
+ if (matched || !test(entry.path)) { entry.autodrain(); return; }
+ matched = true;
+ const chunks = [];
+ const sink = new Writable({
+ write(chunk, _enc, cb) { chunks.push(chunk); cb(); },
+ });
+ // The match's inflate→sink pipeline finishes asynchronously, so the
+ // parser's 'close' (source EOF) can fire first — only let 'close'
+ // resolve when nothing matched; otherwise the sink 'finish' resolves.
+ sink.on('finish', () => done(resolve, Buffer.concat(chunks)));
+ sink.on('error', (err) => done(reject, err));
+ entry.pipe(sink);
+ });
+ parser.on('close', () => { if (!matched) done(resolve, null); });
+ src.pipe(parser);
+ });
+}
diff --git a/server/lib/zipStream.test.js b/server/lib/zipStream.test.js
index 9919a5d3f5..b538f539dc 100644
--- a/server/lib/zipStream.test.js
+++ b/server/lib/zipStream.test.js
@@ -1,7 +1,10 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { Readable, Writable } from 'stream';
import { deflateRawSync } from 'zlib';
-import { parseZip } from './zipStream.js';
+import { writeFile, rm, mkdtemp } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { parseZip, extractZipEntryToBuffer } from './zipStream.js';
const LOCAL_SIG = 0x04034b50;
const CENTRAL_SIG = 0x02014b50;
@@ -139,3 +142,43 @@ describe('parseZip', () => {
expect(entries[0].data.toString()).toBe(data.toString());
});
});
+
+describe('extractZipEntryToBuffer', () => {
+ let dir;
+ let zipPath;
+ // A two-entry zip mirroring an mflux checkpoint: a big stored "optimizer"
+ // FIRST (must be skipped without inflation), then a deflated "adapter".
+ const adapterPayload = Buffer.from('adapter weights — round-trip me cleanly');
+
+ beforeAll(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'zipextract-'));
+ zipPath = join(dir, 'ckpt.zip');
+ const optimizer = buildEntry('0001_optimizer.safetensors', Buffer.alloc(4096, 7));
+ const adapter = buildEntry('0001_adapter.safetensors', deflateRawSync(adapterPayload), { method: 8 });
+ await writeFile(zipPath, Buffer.concat([optimizer, adapter, buildEocd()]));
+ });
+
+ afterAll(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ it('extracts a later deflated entry past an earlier one via predicate', async () => {
+ const out = await extractZipEntryToBuffer(
+ zipPath,
+ (name) => name.endsWith('_adapter.safetensors') && !name.includes('optimizer'),
+ );
+ expect(out).not.toBeNull();
+ expect(out.toString()).toBe(adapterPayload.toString());
+ });
+
+ it('matches by substring shorthand', async () => {
+ const out = await extractZipEntryToBuffer(zipPath, '_adapter.safetensors');
+ expect(out.toString()).toBe(adapterPayload.toString());
+ });
+
+ it('resolves null when nothing matches', async () => {
+ expect(await extractZipEntryToBuffer(zipPath, 'no-such-member.bin')).toBeNull();
+ });
+
+ it('rejects on a missing file', async () => {
+ await expect(extractZipEntryToBuffer(join(dir, 'nope.zip'), 'x')).rejects.toThrow();
+ });
+});
diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.js
index 219a2420b7..5254a08bc6 100644
--- a/server/routes/loraTraining.js
+++ b/server/routes/loraTraining.js
@@ -20,7 +20,9 @@ import {
deleteRun,
getRunRequired,
isMfluxTrainAvailable,
+ listCheckpoints,
listRuns,
+ promoteCheckpoint,
runDir,
runSamplesDir,
startTrainingRun,
@@ -108,6 +110,22 @@ router.delete('/runs/:id', asyncHandler(async (req, res) => {
res.json(await deleteRun(run.id));
}));
+// Checkpoint picker: list every saved checkpoint with its step, loss, and
+// preview thumbnail so the user can promote one by eye. Loss is shown but is
+// NOT a quality ranking — it was anti-correlated with quality on the
+// divergence run this feature was built for (see checkpoints.js).
+router.get('/runs/:id/checkpoints', asyncHandler(async (req, res) => {
+ await getRunRequired(req.params.id); // 404 if the run is unknown
+ res.json(await listCheckpoints(req.params.id));
+}));
+
+const promoteSchema = z.object({ step: z.coerce.number().int().min(0) });
+router.post('/runs/:id/promote-checkpoint', asyncHandler(async (req, res) => {
+ await getRunRequired(req.params.id);
+ const { step } = validateRequest(promoteSchema, req.body);
+ res.json(await promoteCheckpoint(req.params.id, step));
+}));
+
router.get('/runs/:id/samples/:filename', asyncHandler(async (req, res) => {
const run = await getRunRequired(req.params.id);
assertSafeFilename(req.params.filename, { extensions: ['.png'], subject: 'sample filename' });
diff --git a/server/services/loraTraining/checkpoints.js b/server/services/loraTraining/checkpoints.js
new file mode 100644
index 0000000000..37a20fa317
--- /dev/null
+++ b/server/services/loraTraining/checkpoints.js
@@ -0,0 +1,216 @@
+/**
+ * Checkpoint inspection + selection for trained LoRAs.
+ *
+ * A training run keeps every periodic checkpoint, but only one adapter is
+ * registered into `data/loras/` as the usable LoRA. mflux always hands back
+ * the FINAL step's adapter — which is exactly wrong when training diverges
+ * late (a recurring FLUX.2 failure: the loss keeps dropping while the sample
+ * image collapses to a near-black frame). Loss is therefore NOT a reliable
+ * "best checkpoint" signal — it was anti-correlated with quality on the run
+ * that motivated this module. So selection is two-pronged:
+ *
+ * 1. A cheap COLLAPSE GUARD at finalize that only vetoes the catastrophic
+ * case — a degenerate (near-black / near-uniform) final preview — and
+ * falls back to the latest non-degenerate checkpoint.
+ * 2. A MANUAL promote path (`promoteCheckpoint`) so the human can pick any
+ * checkpoint by eye from its preview thumbnail — the real safety net for
+ * subtler degradation the guard intentionally leaves alone.
+ *
+ * Runtime-aware: mflux checkpoints are `*_checkpoint.zip` bundles (the
+ * adapter is cracked out with lib/zipStream); the torch flux2 trainer writes
+ * `checkpoints/step-NNNNNN/pytorch_lora_weights.safetensors` directories.
+ */
+
+import { readFile } from 'fs/promises';
+import { existsSync, statSync, readdirSync } from 'fs';
+import { join, basename } from 'path';
+import sharp from 'sharp';
+import { PATHS } from '../../lib/fileUtils.js';
+import { extractZipEntryToBuffer } from '../../lib/zipStream.js';
+import { TRAINING_RUNTIMES } from './runtimes.js';
+
+// Collapse thresholds — calibrated against a real divergence run: the
+// black-frame final preview measured entropy 2.8 / max-channel-stdev 1.7,
+// while every legitimate (even ugly) frame sat at entropy 5.5–7.1 / stdev
+// 18–50. The wide gap means these vetoes never fire on a real image.
+export const COLLAPSE_ENTROPY_MAX = 4.0;
+export const COLLAPSE_STDEV_MAX = 6.0;
+
+const runDirFor = (runId) => join(PATHS.trainingRuns, runId);
+const samplesDirFor = (runId) => join(runDirFor(runId), 'samples');
+
+/**
+ * mflux appends `_YYYYMMDD_HHMMSS` to its output dir when the configured one
+ * already exists (mirrors resolve_mflux_output in train_mflux_lora.py) — pick
+ * the newest real directory among the base name and its timestamped siblings.
+ */
+function resolveMfluxOutputDir(runId) {
+ const base = join(runDirFor(runId), 'mflux');
+ const dir = runDirFor(runId);
+ const candidates = [base];
+ if (existsSync(dir)) {
+ for (const name of readdirSync(dir)) {
+ if (name.startsWith('mflux_2') && statSync(join(dir, name)).isDirectory()) {
+ candidates.push(join(dir, name));
+ }
+ }
+ }
+ const present = candidates.filter((p) => existsSync(p) && statSync(p).isDirectory());
+ if (!present.length) return base;
+ return present.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
+}
+
+/** Parse the step a sample basename was rendered at (both runtime namings). */
+function stepFromSampleName(name) {
+ // mflux: 0000250_preview_image_preview_1.png ; flux2: step-000250.png
+ const m = name.match(/^(\d+)_preview/) || name.match(/^step-(\d+)\.png$/);
+ return m ? Number(m[1]) : null;
+}
+
+/** Map step → sample basename from the run's recorded sample artifacts. */
+function sampleByStep(run) {
+ const map = new Map();
+ for (const s of run.artifacts?.samples || []) {
+ const step = stepFromSampleName(s);
+ if (step != null) map.set(step, s);
+ }
+ return map;
+}
+
+const sampleUrl = (runId, name) =>
+ name ? `/api/lora-training/runs/${runId}/samples/${name}` : null;
+
+/**
+ * Listable view of a run's checkpoints — step, loss (captured at checkpoint
+ * time), preview thumbnail URL, and which one is currently deployed. Drives
+ * the manual checkpoint picker in the run UI.
+ */
+export function listRunCheckpoints(run) {
+ const samples = sampleByStep(run);
+ const deployedStep = run.output?.selectedCheckpointStep ?? null;
+ const checkpoints = (run.artifacts?.checkpoints || [])
+ .map((c) => {
+ const preview = samples.get(c.step) || null;
+ return {
+ step: c.step,
+ loss: Number.isFinite(c.loss) ? c.loss : null,
+ previewUrl: sampleUrl(run.id, preview),
+ hasPreview: !!preview,
+ deployed: deployedStep != null && c.step === deployedStep,
+ };
+ })
+ .sort((a, b) => a.step - b.step);
+ return checkpoints;
+}
+
+/**
+ * Decide whether a preview image is a degenerate collapse (near-black /
+ * near-uniform). Conservative by design — only the catastrophic case. A
+ * missing/unreadable preview returns false (don't veto on analysis failure).
+ */
+export async function isPreviewCollapsed(previewPath) {
+ if (!previewPath || !existsSync(previewPath)) return false;
+ const stats = await sharp(previewPath).stats().catch(() => null);
+ if (!stats?.channels?.length) return false;
+ const rgb = stats.channels.slice(0, 3);
+ const maxStdev = Math.max(...rgb.map((c) => c.stdev));
+ const entropy = Number.isFinite(stats.entropy) ? stats.entropy : 0;
+ return entropy < COLLAPSE_ENTROPY_MAX || maxStdev < COLLAPSE_STDEV_MAX;
+}
+
+// Step zero-pad widths mirror each trainer's own naming: mflux writes
+// NNNNNNN_checkpoint.zip (7 digits); the flux2 diffusers wrapper writes
+// step-NNNNNN/ (6 digits). Used only as a fallback when the run record
+// didn't capture the artifact's basename.
+const pad7 = (n) => String(n).padStart(7, '0');
+const pad6 = (n) => String(n).padStart(6, '0');
+
+/**
+ * Resolve a checkpoint's adapter weights to a Buffer, runtime-aware:
+ * - mflux: crack `*_adapter.safetensors` out of the step's checkpoint zip.
+ * - flux2: read `checkpoints/step-NNNNNN/pytorch_lora_weights.safetensors`.
+ * Throws a clear error if the checkpoint artifact is missing.
+ */
+export async function resolveCheckpointAdapterBuffer(run, step) {
+ if (run.runtime === TRAINING_RUNTIMES.MFLUX) {
+ const recorded = (run.artifacts?.checkpoints || []).find((c) => c.step === step);
+ const zipName = recorded?.path || `${pad7(step)}_checkpoint.zip`;
+ const zipPath = join(resolveMfluxOutputDir(run.id), 'checkpoints', basename(zipName));
+ if (!existsSync(zipPath)) {
+ throw new Error(`checkpoint zip missing for step ${step} (${zipPath})`);
+ }
+ const adapter = await extractZipEntryToBuffer(
+ zipPath,
+ (name) => name.endsWith('_adapter.safetensors') && !name.includes('optimizer'),
+ );
+ if (!adapter) throw new Error(`no adapter found inside checkpoint zip for step ${step}`);
+ return adapter;
+ }
+ // flux2 torch runtime — diffusers save_lora_weights dir. Prefer the recorded
+ // checkpoint basename (symmetric with the mflux path) so a trainer naming
+ // change can't silently break resolution; fall back to the derived name.
+ const recorded = (run.artifacts?.checkpoints || []).find((c) => c.step === step);
+ const dirName = recorded?.path ? basename(recorded.path) : `step-${pad6(step)}`;
+ const file = join(runDirFor(run.id), 'checkpoints', dirName, 'pytorch_lora_weights.safetensors');
+ if (!existsSync(file)) {
+ throw new Error(`checkpoint adapter missing for step ${step} (${file})`);
+ }
+ return readFile(file);
+}
+
+/**
+ * Collapse guard for finalize: given the final adapter PortOS already
+ * extracted and the run's checkpoints, deploy the final unless its preview is
+ * a degenerate collapse — in which case walk back to the latest checkpoint
+ * with a healthy preview. Returns the adapter Buffer to register plus the
+ * selection metadata (which step, its preview, whether the guard overrode).
+ *
+ * `finalAdapterPath` is the wrapper-extracted adapter on disk (the final
+ * step). `finalStep` is its step. Falls back silently to the final adapter
+ * when there are no previews to judge (sampling disabled).
+ */
+export async function selectDeployableCheckpoint(run, finalAdapterPath, finalStep) {
+ const samples = sampleByStep(run);
+ const withPreview = listRunCheckpoints(run).filter((c) => c.hasPreview);
+ // Health proxy for the final adapter: its own preview, or — since mflux
+ // saves the final checkpoint a few steps PAST the last sampled step, so the
+ // final usually has no preview of its own — the most recent preview.
+ const latest = withPreview.length ? withPreview[withPreview.length - 1] : null;
+ const finalPreviewName = samples.get(finalStep) || (latest ? samples.get(latest.step) : null);
+
+ const readFinal = async (reason = null) => ({
+ buffer: await readFile(finalAdapterPath),
+ step: finalStep,
+ previewUrl: sampleUrl(run.id, finalPreviewName),
+ autoSelected: false,
+ reason,
+ });
+
+ // Nothing to judge (sampling disabled) → trust the trainer's final adapter.
+ if (!finalPreviewName) return readFinal();
+
+ const finalCollapsed = await isPreviewCollapsed(join(samplesDirFor(run.id), finalPreviewName));
+ if (!finalCollapsed) return readFinal();
+
+ // Final diverged. Walk earlier checkpoints newest→oldest for a healthy one.
+ const earlier = withPreview
+ .filter((c) => c.step < finalStep)
+ .sort((a, b) => b.step - a.step);
+ for (const cand of earlier) {
+ const previewName = samples.get(cand.step);
+ const collapsed = await isPreviewCollapsed(join(samplesDirFor(run.id), previewName));
+ if (collapsed) continue;
+ const buffer = await resolveCheckpointAdapterBuffer(run, cand.step).catch(() => null);
+ if (!buffer) continue;
+ return {
+ buffer,
+ step: cand.step,
+ previewUrl: sampleUrl(run.id, previewName),
+ autoSelected: true,
+ reason: `final preview collapsed — auto-selected step ${cand.step}`,
+ };
+ }
+ // Every preview collapsed (or no earlier adapter recoverable) — keep final
+ // so the run still registers a (flawed) LoRA the user can inspect/replace.
+ return readFinal(`all previews collapsed — kept final step ${finalStep}`);
+}
diff --git a/server/services/loraTraining/checkpoints.test.js b/server/services/loraTraining/checkpoints.test.js
new file mode 100644
index 0000000000..046afa40de
--- /dev/null
+++ b/server/services/loraTraining/checkpoints.test.js
@@ -0,0 +1,160 @@
+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { deflateRawSync } from 'zlib';
+import sharp from 'sharp';
+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+let dataRoot = tmpdir();
+
+// Point PATHS.trainingRuns/loras at a per-suite temp root so the
+// filesystem-touching helpers (preview analysis, zip extraction) operate on
+// fixtures instead of real run data.
+vi.mock('../../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), {
+ dataRoot: () => dataRoot,
+ extraOverrides: (root) => ({
+ trainingRuns: join(root, 'training-runs'),
+ loras: join(root, 'loras'),
+ }),
+ }));
+
+const {
+ listRunCheckpoints,
+ isPreviewCollapsed,
+ resolveCheckpointAdapterBuffer,
+ selectDeployableCheckpoint,
+ COLLAPSE_ENTROPY_MAX,
+} = await import('./checkpoints.js');
+
+const LOCAL_SIG = 0x04034b50;
+const CENTRAL_SIG = 0x02014b50;
+
+function zipEntry(name, payload, method) {
+ const nameBuf = Buffer.from(name, 'utf-8');
+ const h = Buffer.alloc(30);
+ h.writeUInt32LE(LOCAL_SIG, 0);
+ h.writeUInt16LE(20, 4);
+ h.writeUInt16LE(0, 6);
+ h.writeUInt16LE(method, 8);
+ h.writeUInt32LE(payload.length, 18);
+ h.writeUInt32LE(payload.length, 22);
+ h.writeUInt16LE(nameBuf.length, 26);
+ return Buffer.concat([h, nameBuf, payload]);
+}
+function eocd() { const b = Buffer.alloc(4); b.writeUInt32LE(CENTRAL_SIG, 0); return b; }
+
+/** A checkpoint zip: optimizer (stored) then the deflated adapter. */
+function checkpointZip(step, adapterBytes) {
+ const pad = String(step).padStart(7, '0');
+ return Buffer.concat([
+ zipEntry(`${pad}_optimizer.safetensors`, Buffer.alloc(256, 9), 0),
+ zipEntry(`${pad}_adapter.safetensors`, deflateRawSync(adapterBytes), 8),
+ eocd(),
+ ]);
+}
+
+// A high-variance gradient PNG (entropy well above the collapse floor).
+const noisyPng = () => {
+ const w = 64; const h = 64; const raw = Buffer.alloc(w * h * 3);
+ for (let i = 0; i < raw.length; i += 1) raw[i] = (i * 73) % 256;
+ return sharp(raw, { raw: { width: w, height: h, channels: 3 } }).png().toBuffer();
+};
+// A flat black PNG — the degenerate-collapse case.
+const blackPng = () =>
+ sharp({ create: { width: 64, height: 64, channels: 3, background: { r: 0, g: 0, b: 0 } } }).png().toBuffer();
+
+const RUN_ID = 'run-fixture';
+const ADAPTER_250 = Buffer.from('ADAPTER-AT-STEP-250');
+const ADAPTER_500 = Buffer.from('ADAPTER-AT-STEP-500');
+
+function buildRun(overrides = {}) {
+ return {
+ id: RUN_ID,
+ runtime: 'mflux',
+ progress: { step: 500 },
+ output: { selectedCheckpointStep: 250, loraFilename: 'lora-x.safetensors' },
+ artifacts: {
+ checkpoints: [
+ { step: 250, path: '0000250_checkpoint.zip', loss: 0.64 },
+ { step: 500, path: '0000500_checkpoint.zip', loss: 0.53 },
+ ],
+ samples: [
+ '0000250_preview_image_preview_1.png',
+ '0000500_preview_image_preview_1.png',
+ ],
+ },
+ ...overrides,
+ };
+}
+
+describe('loraTraining/checkpoints', () => {
+ let runDir;
+ let finalAdapterPath;
+
+ beforeAll(async () => {
+ dataRoot = mkdtempSync(join(tmpdir(), 'ckpt-test-'));
+ runDir = join(dataRoot, 'training-runs', RUN_ID);
+ mkdirSync(join(runDir, 'mflux', 'checkpoints'), { recursive: true });
+ mkdirSync(join(runDir, 'samples'), { recursive: true });
+ await writeFile(join(runDir, 'mflux', 'checkpoints', '0000250_checkpoint.zip'), checkpointZip(250, ADAPTER_250));
+ await writeFile(join(runDir, 'mflux', 'checkpoints', '0000500_checkpoint.zip'), checkpointZip(500, ADAPTER_500));
+ await writeFile(join(runDir, 'samples', '0000250_preview_image_preview_1.png'), await noisyPng());
+ await writeFile(join(runDir, 'samples', '0000500_preview_image_preview_1.png'), await blackPng());
+ // Stand-in for the wrapper-extracted final adapter on disk (step 500).
+ finalAdapterPath = join(runDir, 'adapter.safetensors');
+ await writeFile(finalAdapterPath, ADAPTER_500);
+ });
+
+ afterAll(() => { rmSync(dataRoot, { recursive: true, force: true }); });
+
+ it('lists checkpoints with loss, preview, and deployed flag (sorted by step)', () => {
+ const list = listRunCheckpoints(buildRun());
+ expect(list.map((c) => c.step)).toEqual([250, 500]);
+ expect(list[0]).toMatchObject({ step: 250, loss: 0.64, hasPreview: true, deployed: true });
+ expect(list[0].previewUrl).toContain('0000250_preview');
+ expect(list[1].deployed).toBe(false);
+ });
+
+ it('flags a black preview as collapsed and a noisy one as healthy', async () => {
+ expect(await isPreviewCollapsed(join(runDir, 'samples', '0000500_preview_image_preview_1.png'))).toBe(true);
+ expect(await isPreviewCollapsed(join(runDir, 'samples', '0000250_preview_image_preview_1.png'))).toBe(false);
+ // Analysis failure (missing file) must not falsely veto.
+ expect(await isPreviewCollapsed(join(runDir, 'samples', 'nope.png'))).toBe(false);
+ expect(COLLAPSE_ENTROPY_MAX).toBeGreaterThan(0);
+ });
+
+ it('cracks the right adapter out of a checkpoint zip', async () => {
+ expect((await resolveCheckpointAdapterBuffer(buildRun(), 250)).toString()).toBe(ADAPTER_250.toString());
+ expect((await resolveCheckpointAdapterBuffer(buildRun(), 500)).toString()).toBe(ADAPTER_500.toString());
+ });
+
+ it('throws for a step with no checkpoint artifact', async () => {
+ await expect(resolveCheckpointAdapterBuffer(buildRun(), 999)).rejects.toThrow(/checkpoint zip missing/);
+ });
+
+ it('guard: falls back to the latest healthy checkpoint when the final preview collapsed', async () => {
+ const sel = await selectDeployableCheckpoint(buildRun(), finalAdapterPath, 500);
+ expect(sel.autoSelected).toBe(true);
+ expect(sel.step).toBe(250);
+ expect(sel.buffer.toString()).toBe(ADAPTER_250.toString());
+ expect(sel.reason).toMatch(/collapsed/);
+ });
+
+ it('guard: keeps the final adapter when its preview is healthy', async () => {
+ // finalStep 250 has the noisy (healthy) preview → no override.
+ const sel = await selectDeployableCheckpoint(buildRun(), finalAdapterPath, 250);
+ expect(sel.autoSelected).toBe(false);
+ expect(sel.step).toBe(250);
+ expect(sel.buffer.toString()).toBe(ADAPTER_500.toString()); // returns the on-disk final adapter as-is
+ });
+
+ it('guard: trusts the final adapter when there are no previews to judge', async () => {
+ const run = buildRun({ artifacts: { checkpoints: [{ step: 500, path: '0000500_checkpoint.zip', loss: 0.5 }], samples: [] } });
+ const sel = await selectDeployableCheckpoint(run, finalAdapterPath, 500);
+ expect(sel.autoSelected).toBe(false);
+ expect(sel.step).toBe(500);
+ });
+});
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index d3142ee87d..6efc8d9444 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -15,7 +15,7 @@
import { spawn } from 'child_process';
import { existsSync } from 'fs';
-import { copyFile, mkdir, stat, writeFile } from 'fs/promises';
+import { copyFile, mkdir, writeFile } from 'fs/promises';
import { join, basename, dirname } from 'path';
import { platform, totalmem } from 'os';
import { PATHS, ensureDir, atomicWrite, shortId } from '../../lib/fileUtils.js';
@@ -41,6 +41,11 @@ import { makeTrainingLineHandler } from './progress.js';
import { classifyTrainingFailure } from './failure.js';
import { buildTrainedSidecar, trainedLoraFilename } from './sidecar.js';
import { validateDatasetReady } from './dataset.js';
+import {
+ listRunCheckpoints,
+ resolveCheckpointAdapterBuffer,
+ selectDeployableCheckpoint,
+} from './checkpoints.js';
import * as runsDb from './db.js';
export { listRuns, getRun, getRunRequired, deleteRun } from './db.js';
@@ -326,23 +331,36 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {
// channel, the row is the durable snapshot.
let progressDirty = null;
let progressTimer = null;
+ // Persist whatever progress/artifacts are pending. Returns the write promise
+ // so the close handler can AWAIT a final flush before finalize reads the run
+ // record — otherwise the final checkpoint + last sample (which the collapse
+ // guard and previewImageUrl both read from run.artifacts) can still be in the
+ // debounce buffer, not on disk.
+ const flushProgress = () => {
+ if (progressTimer) { clearTimeout(progressTimer); progressTimer = null; }
+ if (!progressDirty) return Promise.resolve();
+ const flushing = progressDirty;
+ progressDirty = null;
+ return runsDb.updateRun(runId, (current) => ({
+ ...current,
+ progress: { ...current.progress, ...flushing.progress },
+ artifacts: {
+ ...current.artifacts,
+ ...(flushing.checkpoints ? { checkpoints: [...current.artifacts.checkpoints, ...flushing.checkpoints] } : {}),
+ ...(flushing.samples ? { samples: [...current.artifacts.samples, ...flushing.samples] } : {}),
+ },
+ })).catch((err) => console.error(`❌ training [${shortId(jobId)}] progress persist failed: ${err?.message}`));
+ };
+ // Checkpoints/samples accumulate as arrays so two that land in one debounce
+ // window (common in the final post-exit scan) both survive — a single-value
+ // patch would let the later one clobber the earlier.
const scheduleProgressPersist = (patch) => {
- progressDirty = { ...progressDirty, ...patch };
+ progressDirty = progressDirty || {};
+ if (patch.progress) progressDirty.progress = { ...progressDirty.progress, ...patch.progress };
+ if (patch.checkpoint) (progressDirty.checkpoints ||= []).push(patch.checkpoint);
+ if (patch.sample) (progressDirty.samples ||= []).push(patch.sample);
if (progressTimer) return;
- progressTimer = setTimeout(() => {
- progressTimer = null;
- const flushing = progressDirty;
- progressDirty = null;
- runsDb.updateRun(runId, (current) => ({
- ...current,
- progress: { ...current.progress, ...flushing.progress },
- artifacts: {
- ...current.artifacts,
- ...(flushing.checkpoint ? { checkpoints: [...current.artifacts.checkpoints, flushing.checkpoint] } : {}),
- ...(flushing.sample ? { samples: [...current.artifacts.samples, flushing.sample] } : {}),
- },
- })).catch((err) => console.error(`❌ training [${shortId(jobId)}] progress persist failed: ${err?.message}`));
- }, 2000);
+ progressTimer = setTimeout(() => { flushProgress(); }, 2000);
progressTimer.unref?.();
};
@@ -355,8 +373,8 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {
scheduleProgressPersist({ progress: { step: payload.step, totalSteps: payload.totalSteps } });
}
},
- onCheckpoint: (path, step) => scheduleProgressPersist({
- checkpoint: { step, path: basename(path) },
+ onCheckpoint: (path, step, loss) => scheduleProgressPersist({
+ checkpoint: { step, path: basename(path), loss: Number.isFinite(loss) ? loss : null },
progress: { lastCheckpointStep: step },
}),
onSample: (path) => scheduleProgressPersist({ sample: basename(path) }),
@@ -402,13 +420,16 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {
proc.on('close', (code, signal) => {
if (activeProcess === proc) { activeProcess = null; activeJobId = null; }
- if (progressTimer) { clearTimeout(progressTimer); progressTimer = null; }
- // Async finalize wrapped so a rejection can't escape the event handler
- // (unhandled rejection kills the process on Node ≥15).
- finalizeTraining({ jobId, runId, code, signal, state: getState() }).catch((err) => {
- console.error(`❌ training [${shortId(jobId)}] finalize failed: ${err?.message}`);
- fail(`finalize failed: ${err?.message}`);
- });
+ // Flush the debounced progress (final checkpoint + last sample) BEFORE
+ // finalize reads the run record — the collapse guard and previewImageUrl
+ // both read run.artifacts. Async finalize wrapped so a rejection can't
+ // escape the event handler (unhandled rejection kills the process on Node ≥15).
+ Promise.resolve(flushProgress())
+ .then(() => finalizeTraining({ jobId, runId, code, signal, state: getState() }))
+ .catch((err) => {
+ console.error(`❌ training [${shortId(jobId)}] finalize failed: ${err?.message}`);
+ fail(`finalize failed: ${err?.message}`);
+ });
});
}
@@ -429,29 +450,37 @@ async function finalizeTraining({ jobId, runId, code, signal, state }) {
}
if (code === 0 && state.result?.adapter_path) {
+ const finalStep = Number.isInteger(state.result.steps) ? state.result.steps : (run.progress?.step ?? null);
+ // Collapse guard: deploy the final adapter unless its preview diverged
+ // (near-black/uniform), in which case fall back to the latest healthy
+ // checkpoint. Loss is NOT used to pick — it was anti-correlated with
+ // quality on the divergence run that motivated this (see checkpoints.js).
+ const selection = await selectDeployableCheckpoint(run, state.result.adapter_path, finalStep);
const filename = trainedLoraFilename({
name: run?.name, characterName: run?.character?.name, runId,
});
- await ensureDir(PATHS.loras);
- await copyFile(state.result.adapter_path, join(PATHS.loras, filename));
- const sizeBytes = await stat(join(PATHS.loras, filename)).then((s) => s.size).catch(() => null);
- const lastSample = run?.artifacts?.samples?.length
- ? `/api/lora-training/runs/${runId}/samples/${run.artifacts.samples[run.artifacts.samples.length - 1]}`
- : null;
- const sidecar = buildTrainedSidecar({
- run, result: state.result, filename, previewImageUrl: lastSample, sizeBytes,
+ const { sizeBytes } = await registerTrainedLora({
+ run,
+ buffer: selection.buffer,
+ filename,
+ result: state.result,
+ previewImageUrl: selection.previewUrl,
+ selectedStep: selection.step,
+ autoSelected: selection.autoSelected,
});
- await writeFile(join(PATHS.loras, `${filename}.metadata.json`), JSON.stringify(sidecar, null, 2) + '\n');
await runsDb.updateRun(runId, {
status: 'completed',
completedAt: new Date().toISOString(),
output: {
loraFilename: filename,
finalLoss: Number.isFinite(state.result.final_loss) ? state.result.final_loss : null,
+ selectedCheckpointStep: selection.step,
+ autoSelectedCheckpoint: selection.autoSelected,
},
});
await flipDatasetAfterRun(run.datasetId, { trained: true, loraFilename: filename });
- console.log(`✅ training [${shortId(jobId)}] complete — registered ${filename}`);
+ if (selection.autoSelected) console.log(`⚠️ training [${shortId(jobId)}] ${selection.reason} (size ${sizeBytes ?? '?'}B)`);
+ console.log(`✅ training [${shortId(jobId)}] complete — registered ${filename} @ step ${selection.step}`);
trainingEvents.emit('completed', {
generationId: jobId, runId, loraFilename: filename, filename,
});
@@ -496,6 +525,83 @@ async function finalizeTraining({ jobId, runId, code, signal, state }) {
trainingEvents.emit('failed', { generationId: jobId, error: message });
}
+/**
+ * Write an adapter Buffer into data/loras/ as the registered trained LoRA and
+ * emit its sidecar. Shared by finalize (collapse-guarded final) and manual
+ * checkpoint promotion — both deploy a chosen adapter under one filename, so
+ * promoting overwrites in place and the LoRA's identity in the picker is
+ * stable across re-promotes.
+ */
+async function registerTrainedLora({
+ run, buffer, filename, result = {}, previewImageUrl = null, selectedStep = null, autoSelected = false,
+}) {
+ await ensureDir(PATHS.loras);
+ const dest = join(PATHS.loras, filename);
+ await writeFile(dest, buffer);
+ const sizeBytes = buffer.length; // bytes written === on-disk size; no stat round-trip
+ const sidecar = buildTrainedSidecar({
+ run, result, filename, previewImageUrl, sizeBytes, selectedStep, autoSelected,
+ });
+ await writeFile(`${dest}.metadata.json`, JSON.stringify(sidecar, null, 2) + '\n');
+ return { sizeBytes, sidecar };
+}
+
+/** Listable checkpoints (step, loss, preview, deployed flag) for a run. */
+export async function listCheckpoints(runId) {
+ const run = await runsDb.getRunRequired(runId);
+ return { runId, runtime: run.runtime, checkpoints: listRunCheckpoints(run) };
+}
+
+/**
+ * Manually promote a checkpoint to be the deployed LoRA. Re-extracts that
+ * checkpoint's adapter, registers it under the run's existing LoRA filename
+ * (in place), and records the selected step on the run. Lets the user pick by
+ * eye when the collapse guard's near-black veto wasn't enough (subtler
+ * degradation — see the loss-is-misleading note in checkpoints.js).
+ */
+export async function promoteCheckpoint(runId, step) {
+ const run = await runsDb.getRunRequired(runId);
+ if (!['completed', 'failed', 'canceled'].includes(run.status)) {
+ throw new ServerError('Cannot promote a checkpoint while the run is active', {
+ status: 409, code: 'RUN_ACTIVE',
+ });
+ }
+ const listed = listRunCheckpoints(run);
+ const target = listed.find((c) => c.step === step);
+ if (!target) {
+ throw new ServerError(`No checkpoint at step ${step} for run ${runId}`, {
+ status: 404, code: 'CHECKPOINT_NOT_FOUND',
+ });
+ }
+ const buffer = await resolveCheckpointAdapterBuffer(run, step);
+ const filename = run.output?.loraFilename
+ || trainedLoraFilename({ name: run.name, characterName: run.character?.name, runId });
+ // Keep trainedSteps pointing at the run's final step so the sidecar can note
+ // "checkpoint @ step N" whenever the promoted step isn't the final one.
+ const finalStep = Math.max(0, ...listed.map((c) => c.step), run.progress?.step || 0) || null;
+ await registerTrainedLora({
+ run,
+ buffer,
+ filename,
+ result: { steps: finalStep, final_loss: target.loss },
+ previewImageUrl: target.previewUrl,
+ selectedStep: step,
+ autoSelected: false,
+ });
+ await runsDb.updateRun(runId, (current) => ({
+ ...current,
+ output: {
+ ...current.output,
+ loraFilename: filename,
+ selectedCheckpointStep: step,
+ autoSelectedCheckpoint: false,
+ },
+ }));
+ await flipDatasetAfterRun(run.datasetId, { trained: true, loraFilename: filename });
+ console.log(`📌 training [${shortId(runId)}] promoted checkpoint step ${step} → ${filename}`);
+ return { loraFilename: filename, step };
+}
+
/**
* Boot reconcile + terminal-state mirror. Called from server/index.js after
* initMediaJobQueue(). Any run persisted as queued/running whose job isn't
diff --git a/server/services/loraTraining/progress.js b/server/services/loraTraining/progress.js
index 9c47662ca3..21b1c51da3 100644
--- a/server/services/loraTraining/progress.js
+++ b/server/services/loraTraining/progress.js
@@ -74,7 +74,9 @@ export function makeTrainingLineHandler({
const checkpoint = line.match(/^CHECKPOINT:(.+):(\d+)$/);
if (checkpoint) {
- onCheckpoint?.(checkpoint[1], Number(checkpoint[2]));
+ // Pass the most-recent step loss so the run record can show a
+ // per-checkpoint loss in the picker (mflux/flux2 both lack it inline).
+ onCheckpoint?.(checkpoint[1], Number(checkpoint[2]), state.lastLoss);
emit('status', { generationId: jobId, message: `Checkpoint saved @ step ${checkpoint[2]}` });
return;
}
diff --git a/server/services/loraTraining/progress.test.js b/server/services/loraTraining/progress.test.js
index 28eb634728..f02463c80c 100644
--- a/server/services/loraTraining/progress.test.js
+++ b/server/services/loraTraining/progress.test.js
@@ -38,8 +38,11 @@ describe('makeTrainingLineHandler', () => {
it('routes CHECKPOINT and SAMPLE lines to callbacks', () => {
const { handleLine, emit, onCheckpoint, onSample } = setup();
+ // A preceding STEP line sets lastLoss, which CHECKPOINT forwards so the
+ // run record can show a per-checkpoint loss in the picker.
+ handleLine('STEP:250:1000:0.42');
handleLine('CHECKPOINT:/runs/r1/checkpoints/step-000250:250');
- expect(onCheckpoint).toHaveBeenCalledWith('/runs/r1/checkpoints/step-000250', 250);
+ expect(onCheckpoint).toHaveBeenCalledWith('/runs/r1/checkpoints/step-000250', 250, 0.42);
handleLine('SAMPLE:/runs/r1/samples/step-000250.png:250');
expect(onSample).toHaveBeenCalled();
const preview = emit.mock.calls.find(([e, p]) => e === 'progress' && p.currentImage)[1];
diff --git a/server/services/loraTraining/runtimes.js b/server/services/loraTraining/runtimes.js
index 05b523df29..74f3c95a0d 100644
--- a/server/services/loraTraining/runtimes.js
+++ b/server/services/loraTraining/runtimes.js
@@ -22,26 +22,31 @@
*/
import { ServerError } from '../../lib/errorHandler.js';
-import { isFlux2, flux2VariantFromModel } from '../../lib/runners.js';
+import { isFlux2, flux2VariantFromModel, FLUX2_BF16_BASE_REPOS } from '../../lib/runners.js';
export const TRAINING_RUNTIMES = Object.freeze({ MFLUX: 'mflux', FLUX2: 'flux2' });
+// Defaults tuned down after a FLUX.2 Klein face LoRA diverged: at the old
+// 1000 steps / lr 1e-4, the sample collapsed to a black frame by ~step 500
+// while the loss kept dropping. Halving the LR and shortening the run keeps
+// it in the useful window; 768 captures more facial detail than 512 (a 4K
+// source crushed to 512 loses the face) and the memory-derived quantize/low_ram
+// still covers smaller machines. Tighter checkpoint/sample cadence gives the
+// checkpoint picker more healthy steps to choose from.
export const TRAINING_DEFAULTS = Object.freeze({
- steps: 1000,
+ steps: 600,
rank: 16,
- learningRate: 0.0001,
- resolution: 512,
- checkpointEvery: 250,
- sampleEvery: 250,
+ learningRate: 0.00005,
+ resolution: 768,
+ checkpointEvery: 150,
+ sampleEvery: 150,
});
-// bf16 training bases per FLUX.2 size variant (torch runtime). Inference
-// may run quantized repos; training resolves to these regardless of which
-// flux2-* model id the user picked.
-export const FLUX2_TRAIN_REPOS = Object.freeze({
- '4b': 'black-forest-labs/FLUX.2-klein-4B',
- '9b': 'black-forest-labs/FLUX.2-klein-9B',
-});
+// bf16 training bases per FLUX.2 size variant (torch runtime). Inference may
+// run quantized repos; training resolves to these regardless of which flux2-*
+// model id the user picked. Same repos the image runner renders a LoRA against
+// (PEFT can't load onto quantized weights) — one source of truth in runners.js.
+export const FLUX2_TRAIN_REPOS = FLUX2_BF16_BASE_REPOS;
// mflux model ids per size variant. mflux's flux2 README recommends the
// non-distilled base models for training; the resulting adapter applies to
diff --git a/server/services/loraTraining/sidecar.js b/server/services/loraTraining/sidecar.js
index 5a25d0cf51..e30be6014c 100644
--- a/server/services/loraTraining/sidecar.js
+++ b/server/services/loraTraining/sidecar.js
@@ -14,13 +14,30 @@ export function trainedLoraFilename({ name, characterName, runId }) {
return `lora-trained-${slug}-${String(runId).replace(/-/g, '').slice(0, 8)}.safetensors`;
}
-export function buildTrainedSidecar({ run, result = {}, filename, previewImageUrl = null, sizeBytes = null }) {
+export function buildTrainedSidecar({
+ run,
+ result = {},
+ filename,
+ previewImageUrl = null,
+ sizeBytes = null,
+ // The checkpoint actually deployed (collapse-guard or manual promote may
+ // pick an earlier step than the final). null → the final step was used.
+ selectedStep = null,
+ autoSelected = false,
+}) {
const runtime = run.runtime;
const params = run.params || {};
+ const finalStep = Number.isInteger(result.steps) ? result.steps : null;
+ // Note the checkpoint in the human description only when it differs from the
+ // final step (i.e. the guard/promote actually moved it) — keeps the common
+ // case clean.
+ const ckptNote = selectedStep != null && selectedStep !== finalStep
+ ? ` · checkpoint @ step ${selectedStep}${autoSelected ? ' (auto-selected; final diverged)' : ''}`
+ : '';
return {
filename,
name: run.name || `${run.character?.name || 'Character'} (trained)`,
- description: `Trained in PortOS · ${params.steps ?? '?'} steps · rank ${params.rank ?? '?'} · dataset ${run.datasetId}`,
+ description: `Trained in PortOS · ${params.steps ?? '?'} steps · rank ${params.rank ?? '?'}${ckptNote} · dataset ${run.datasetId}`,
source: 'trained',
character: run.character || null,
datasetId: run.datasetId || null,
@@ -42,7 +59,11 @@ export function buildTrainedSidecar({ run, result = {}, filename, previewImageUr
resolution: params.resolution ?? null,
seed: params.seed ?? null,
finalLoss: Number.isFinite(result.final_loss) ? result.final_loss : null,
- trainedSteps: Number.isInteger(result.steps) ? result.steps : null,
+ trainedSteps: finalStep,
+ // The checkpoint deployed as the LoRA — distinct from trainedSteps when
+ // the collapse guard or a manual promote selected an earlier step.
+ selectedCheckpointStep: selectedStep ?? finalStep,
+ autoSelectedCheckpoint: !!autoSelected,
},
file: { sizeKB: Number.isFinite(sizeBytes) ? Math.round(sizeBytes / 1024) : null, hashes: {}, downloadUrl: null },
previewImageUrl,
diff --git a/server/services/loraTraining/sidecar.test.js b/server/services/loraTraining/sidecar.test.js
index 999501945f..51e5e1b65f 100644
--- a/server/services/loraTraining/sidecar.test.js
+++ b/server/services/loraTraining/sidecar.test.js
@@ -48,6 +48,42 @@ describe('buildTrainedSidecar', () => {
expect(sidecar.file.sizeKB).toBe(51200);
});
+ it('records the deployed checkpoint and notes it when it differs from the final step', () => {
+ const sidecar = buildTrainedSidecar({
+ run: baseRun,
+ result: { steps: 1008, final_loss: 0.05 },
+ filename: 'x.safetensors',
+ selectedStep: 250,
+ autoSelected: true,
+ });
+ expect(sidecar.training.trainedSteps).toBe(1008);
+ expect(sidecar.training.selectedCheckpointStep).toBe(250);
+ expect(sidecar.training.autoSelectedCheckpoint).toBe(true);
+ expect(sidecar.description).toContain('checkpoint @ step 250');
+ expect(sidecar.description).toContain('auto-selected');
+ });
+
+ it('omits the checkpoint note when the final step was deployed', () => {
+ const sidecar = buildTrainedSidecar({
+ run: baseRun,
+ result: { steps: 1008 },
+ filename: 'x.safetensors',
+ selectedStep: 1008,
+ });
+ expect(sidecar.training.selectedCheckpointStep).toBe(1008);
+ expect(sidecar.training.autoSelectedCheckpoint).toBe(false);
+ expect(sidecar.description).not.toContain('checkpoint @ step');
+ });
+
+ it('defaults the deployed checkpoint to the final step when unspecified', () => {
+ const sidecar = buildTrainedSidecar({
+ run: baseRun,
+ result: { steps: 1008 },
+ filename: 'x.safetensors',
+ });
+ expect(sidecar.training.selectedCheckpointStep).toBe(1008);
+ });
+
it('stamps the size variant for the torch runtime too', () => {
const sidecar = buildTrainedSidecar({
run: { ...baseRun, runtime: 'flux2', baseModelId: 'flux2-klein-9b-bf16', fluxVariant: '9b' },