Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
auto-render a preview when deploying a LoRA checkpoint that has none
[._.]/ Adam Eivye122352f5cb0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c7aa486a98..841e2dc3af 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,8 @@## Changed+- **Deploying a LoRA checkpoint with no preview now auto-renders one.** A training run only writes preview thumbnails at the `sampleEvery` cadence, so a checkpoint whose step doesn't land on it — most often the final step (e.g. step 1188 with sampleEvery 300) — showed "no preview" in the picker, including on the deployed card. Promoting such a checkpoint now renders a thumbnail in the background from the just-deployed LoRA (the run's neutral trigger prompt + seed, on the LoRA's own 9B/4B base) and joins it to the checkpoint by step, so the deployed option gets a real image instead of a blank. The render is fire-and-forget — promote stays responsive and a render failure (OOM, restart) never fails the deploy, since the LoRA is already registered. The picker backstop-polls after promoting a preview-less checkpoint to surface the thumbnail once it's ready (~minutes on 9B), unmount-guarded. (`server/services/loraTraining/index.js` `ensureCheckpointPreview`, `client/src/components/loraTraining/CheckpointPicker.jsx`)+- **LoRA training defaults now reflect what actually trains a clean character LoRA on Apple Silicon.** The Train LoRA form previously seeded weak/cautious values (4B base, 600 steps, rank 16, lr 5e-5) — the 4B-first and low-lr choices were leftovers from misdiagnosing an early "divergence" (the real cause was captions over-describing invariant identity, so it bound to words rather than the trigger token, not the learning rate). Validated end-to-end on a 44-image real-face dataset: the form now defaults to **9B base · 1200 steps · rank 32 · lr 1e-4 · 768px · checkpoint/sample every 300**, which binds identity cleanly and fast. The base-model picker prefers the 9B Klein id (it captures identity better than 4B and trains via the panic-safe 4-bit QLoRA tier the server forces) and avoids the heavy `*-bf16` variant. Per-run values remain fully editable in the form. (`server/services/loraTraining/runtimes.js` `TRAINING_DEFAULTS`, `client/src/components/loraTraining/TrainingPanel.jsx`)- **Share the `--user-loras` JSON parser between the two video LoRA runners.** `parse_user_loras` (the strict `[{path, strength}]` validator that surfaces a Node-side bug before any model load) was duplicated verbatim in `scripts/generate_ltx2.py` (dgrauet `ltx2` runtime) and `scripts/generate_av_lora.py` (mlx_video runtime); it now lives once in `scripts/_runner_common.py` (stdlib-only at import, so it's safe to import from either MLX venv — verified in both) and both runners import it, so a future fix to the validation contract can't drift between them. (`scripts/_runner_common.py`, `scripts/generate_ltx2.py`, `scripts/generate_av_lora.py`)diff --git a/client/src/components/loraTraining/CheckpointPicker.jsx b/client/src/components/loraTraining/CheckpointPicker.jsxindex e3c5d8740e..bd1b32b2a8 100644--- a/client/src/components/loraTraining/CheckpointPicker.jsx+++ b/client/src/components/loraTraining/CheckpointPicker.jsx@@ -10,7 +10,7 @@* overwrites the deployed LoRA in place.*/-import { useState, useCallback } from 'react';+import { useState, useCallback, useRef, useEffect } from 'react';import { Layers, Loader2, CheckCircle2, AlertTriangle } from 'lucide-react';import toast from '../ui/Toast';import {@@ -23,6 +23,11 @@ export default function CheckpointPicker({ run, onPromoted }) {const [checkpoints, setCheckpoints] = useState(null);const [loading, setLoading] = useState(false);const [promotingStep, setPromotingStep] = useState(null);+ // Guards the background preview-poll setTimeout chain from firing after the+ // component unmounts (deferred-work-respects-unmount rule). Not reset to true+ // so dev-mode double-mount can't re-arm a stale chain.+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);const load = useCallback(() => {setLoading(true);@@ -40,6 +45,11 @@ export default function CheckpointPicker({ run, onPromoted }) {const promote = async (step) => {setPromotingStep(step);+ // If the promoted checkpoint has no thumbnail, the server renders one in the+ // background (its step wasn't on the sample cadence — e.g. the final step).+ // That render takes minutes, so poll a few times to surface it once ready+ // without a full page reload. (No socket event for this; bounded polling.)+ const lacksPreview = !checkpoints?.find((c) => c.step === step)?.hasPreview;try {await promoteLoraTrainingCheckpoint(run.id, step, { silent: true });toast.success(`Promoted checkpoint @ step ${step}`);@@ -48,6 +58,25 @@ export default function CheckpointPicker({ run, onPromoted }) {setCheckpoints((prev) => prev?.map((c) => ({ ...c, deployed: c.step === step })) ?? prev);load();onPromoted?.();+ if (lacksPreview) {+ // Backstop poll for the background-rendered preview (~5 min on 9B).+ // Each tick re-lists; stop once the step has a preview or attempts run out.+ let attempts = 0;+ const tick = () => {+ if (!mountedRef.current) return;+ attempts += 1;+ listLoraTrainingCheckpoints(run.id)+ .then((res) => {+ if (!mountedRef.current) return;+ const list = Array.isArray(res?.checkpoints) ? res.checkpoints : [];+ setCheckpoints(list);+ const ready = list.find((c) => c.step === step)?.hasPreview;+ if (!ready && attempts < 12) setTimeout(tick, 30000);+ })+ .catch(() => { if (mountedRef.current && attempts < 12) setTimeout(tick, 30000); });+ };+ setTimeout(tick, 30000);+ }} catch (err) {toast.error(`Promote failed: ${err?.message || 'unknown error'}`);} finally {diff --git a/server/services/loraTraining/checkpoints.test.js b/server/services/loraTraining/checkpoints.test.jsindex ead5a5b6ae..1fd0ef0427 100644--- a/server/services/loraTraining/checkpoints.test.js+++ b/server/services/loraTraining/checkpoints.test.js@@ -120,6 +120,31 @@ describe('loraTraining/checkpoints', () => {expect(list[1].deployed).toBe(false);});+ it('a checkpoint whose step has no sample reports no preview, then joins one appended at its step', () => {+ // The final/odd-step checkpoint case the auto-preview-on-promote flow targets:+ // step 1188 isn't on the sampleEvery cadence, so it starts blank…+ const withFinal = buildRun({+ artifacts: {+ checkpoints: [{ step: 1188, path: '0001188_checkpoint.zip', loss: 0.4 }],+ samples: ['0000250_preview_image_preview_1.png'], // none at 1188+ },+ });+ const before = listRunCheckpoints(withFinal).find((c) => c.step === 1188);+ expect(before).toMatchObject({ hasPreview: false, previewUrl: null });++ // …after ensureCheckpointPreview appends the step-joined sample name+ // (`${pad7(step)}_preview_image_preview_1.png`), the join populates it.+ const withPreview = buildRun({+ artifacts: {+ checkpoints: [{ step: 1188, path: '0001188_checkpoint.zip', loss: 0.4 }],+ samples: ['0000250_preview_image_preview_1.png', '0001188_preview_image_preview_1.png'],+ },+ });+ const after = listRunCheckpoints(withPreview).find((c) => c.step === 1188);+ expect(after.hasPreview).toBe(true);+ expect(after.previewUrl).toContain('0001188_preview_image_preview_1.png');+ });+it('resolves the latest on-disk checkpoint zip as the mflux resume point', () => {const latest = resolveLatestCheckpointArtifact(buildRun());expect(latest).toMatchObject({ step: 500 });diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex d3b01a8047..bfbe2aec2c 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -836,9 +836,89 @@ export async function promoteCheckpoint(runId, step) {}));await flipDatasetAfterRun(run, { trained: true, loraFilename: filename });console.log(`📌 training [${shortId(runId)}] promoted checkpoint step ${step} → ${filename}`);+ // If the promoted checkpoint had no preview (its step didn't land on the+ // sampleEvery cadence — most often the final step, e.g. 1188 with sampleEvery+ // 300), render one in the BACKGROUND from the just-registered LoRA so the+ // deployed card isn't blank. Fire-and-forget: promote stays snappy, and a+ // render failure (OOM, missing venv, server restart) must never fail the+ // promote — the LoRA is already deployed; the thumbnail is cosmetic.+ if (!target.previewUrl) {+ ensureCheckpointPreview(run, step, filename).catch((err) => {+ console.error(`⚠️ training [${shortId(runId)}] preview render for step ${step} failed: ${err?.message}`);+ });+ }return { loraFilename: filename, step };}+// mflux preview filename for a step (matches stepFromSampleName's mflux regex in+// checkpoints.js, so listRunCheckpoints joins it to the checkpoint by step).+const previewSampleName = (step) => `${String(step).padStart(7, '0')}_preview_image_preview_1.png`;++/**+ * Render a neutral-prompt preview for a promoted checkpoint that has none, in the+ * background, and attach it to the run so the deployed-checkpoint card shows a+ * thumbnail. Best-effort by contract: every failure path logs and returns without+ * throwing (the caller already deployed the LoRA; this is purely cosmetic).+ *+ * Renders at the SAME neutral prompt + seed + dims the trainer uses for its+ * periodic samples (so it's visually comparable to the 600/900 thumbnails), via+ * the registered LoRA on its own 9b/4b base. Uses generateImage (writes into the+ * gallery dir + sidecar) then copies the PNG into the run's samples dir under the+ * step-joined name; the gallery copy is harmless and lets the user find it too.+ */+async function ensureCheckpointPreview(run, step, loraFilename) {+ const runId = run.id;+ const samplesDir = runSamplesDir(runId);+ const dest = join(samplesDir, previewSampleName(step));+ if (existsSync(dest)) return; // already has one (race / re-promote)++ // Resolve the inference model for this LoRA's variant. The registered base is+ // flux2-klein-<variant>; fall back to the run's baseModelId.+ const variant = run.fluxVariant || null;+ const models = getImageModels();+ const modelId = (variant && models.find((m) => m.id === `flux2-klein-${variant}`)?.id)+ || (models.find((m) => m.id === run.baseModelId)?.id)+ || run.baseModelId;+ if (!modelId) { console.error(`⚠️ training [${shortId(runId)}] no inference model for preview`); return; }++ const settings = await getSettings();+ const pythonPath = settings?.imageGen?.local?.pythonPath || null;+ const prompt = run.params?.samplePrompt || `${run.triggerWord} portrait, neutral background`;+ const seed = Number.isInteger(run.params?.seed) ? run.params.seed : 42;+ const res = run.params?.resolution || 768;++ const { generateImage } = await import('../imageGen/local.js');+ console.log(`🖼️ training [${shortId(runId)}] rendering preview for promoted step ${step} (${modelId})`);+ const result = await generateImage({+ pythonPath,+ prompt,+ modelId,+ width: res,+ height: res,+ steps: 20,+ seed,+ loraFilenames: [loraFilename],+ loraScales: [1.0],+ jobId: `lora-preview-${runId}-${step}`,+ });+ // generateImage writes PATHS.images/<filename> (filename = `${jobId}.png`).+ const renderedPath = join(PATHS.images, result?.filename || `lora-preview-${runId}-${step}.png`);+ if (!existsSync(renderedPath)) { console.error(`⚠️ training [${shortId(runId)}] preview render produced no file`); return; }++ await ensureDir(samplesDir);+ await copyFile(renderedPath, dest);+ // Join is by step, sourced from artifacts.samples — append so listRunCheckpoints+ // picks it up. updateRun's function form merges against the freshest record.+ await runsDb.updateRun(runId, (current) => {+ const samples = current.artifacts?.samples || [];+ const name = previewSampleName(step);+ if (samples.includes(name)) return current;+ return { ...current, artifacts: { ...current.artifacts, samples: [...samples, name] } };+ });+ trainingEvents.emit('checkpoint-preview', { generationId: run.jobId || runId, runId, step });+ console.log(`🖼️ training [${shortId(runId)}] preview attached for step ${step}`);+}+/*** Boot reconcile + terminal-state mirror. Called from server/index.js after* initMediaJobQueue(). Any run persisted as queued/running whose job isn't