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
Resume a killed LoRA training run from its last checkpoint
[._.]/ Adam Eivy148b001823c2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 567f5a90de..3989b220db 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -28,6 +28,8 @@- **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`)+- **Resume a killed LoRA training run from its last checkpoint — and see a failed run's samples** — A training run that got interrupted (an app restart, a manual cancel, a crash partway through) was a total loss: the panel showed only the error, hid the checkpoint picker (it rendered for *completed* runs only), and the only path forward was to start over from step 0 — re-spending all the GPU time the run had already banked. Two changes recover that work. (1) The Train panel now surfaces the **checkpoint picker for any run that saved a checkpoint**, not just completed ones — so you can scrub the failed run's sample previews to judge how far it got, and **"Use this"** still salvages a partial checkpoint into a usable LoRA. (2) A **Resume training** button re-launches a failed/canceled run from its newest checkpoint via the new `POST /api/lora-training/runs/:id/resume` — it re-enqueues a job against the *same* run id (mflux bakes the output path into its checkpoint zip and restores the optimizer + adapter state and step counter from `--resume <zip>`, so the resumed trainer must write back into the original run dir; a fresh dir would strand its artifacts where the watcher can't see them). New checkpoints and samples append to the existing timeline, and finalize registers the LoRA as usual. The torch FLUX.2 trainer resumes via `--resume-from <dir>` the same way. (`server/services/loraTraining/index.js`, `server/services/loraTraining/checkpoints.js`, `server/routes/loraTraining.js`, `client/src/services/apiLoraTraining.js`, `client/src/components/loraTraining/TrainingPanel.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`)diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsxindex b0d1877246..eba9989526 100644--- a/client/src/components/loraTraining/TrainingPanel.jsx+++ b/client/src/components/loraTraining/TrainingPanel.jsx@@ -9,7 +9,7 @@import { useState, useEffect, useCallback } from 'react';import { Link } from 'react-router-dom';-import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles } from 'lucide-react';+import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles, RotateCcw } from 'lucide-react';import toast from '../ui/Toast';import { useSseProgress } from '../../hooks/useSseProgress';import CheckpointPicker from './CheckpointPicker';@@ -19,6 +19,7 @@ import {listLoraTrainingRuns,startLoraTrainingRun,cancelLoraTrainingRun,+ resumeLoraTrainingRun,listImageModels,} from '../../services/api';@@ -33,6 +34,7 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRunconst [lastRun, setLastRun] = useState(null);const [starting, setStarting] = useState(false);const [canceling, setCanceling] = useState(false);+ const [resuming, setResuming] = useState(false);useEffect(() => {getLoraTrainingStatus().then((s) => {@@ -108,8 +110,25 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun}};+ const resume = async () => {+ if (!lastRun) return;+ setResuming(true);+ try {+ const { fromStep } = await resumeLoraTrainingRun(lastRun.id);+ toast.success(`Resuming from checkpoint @ step ${fromStep}`);+ refreshRuns();+ } finally {+ setResuming(false);+ }+ };+const setParam = (key, value) => setParams((prev) => ({ ...prev, [key]: value }));+ // A killed run keeps its checkpoints — surface the picker (view + salvage a+ // partial LoRA) and a Resume button whenever a non-completed run saved one.+ const lastRunCheckpoints = lastRun?.artifacts?.checkpoints?.length || 0;+ const canResume = lastRun && ['failed', 'canceled'].includes(lastRun.status) && lastRunCheckpoints > 0;+const disabledReason = !readiness?.trainable? `Needs ${readiness?.required ?? 10} captioned images (have ${readiness?.captioned ?? 0})`: triggerSaving ? 'Saving trigger word…'@@ -191,7 +210,23 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun)}</div>)}- {lastRun?.status === 'completed' && (+ {canResume && (+ <div className="flex items-center justify-between gap-2 rounded-lg border border-port-accent/30 bg-port-accent/5 px-3 py-2">+ <span className="text-xs text-gray-300">+ {lastRunCheckpoints} checkpoint{lastRunCheckpoints === 1 ? '' : 's'} saved — pick up where it stopped.+ </span>+ <button+ type="button"+ onClick={resume}+ disabled={resuming}+ className="px-2.5 py-1.5 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 flex items-center gap-1.5 shrink-0"+ >+ {resuming ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <RotateCcw className="w-3.5 h-3.5" />}+ Resume training+ </button>+ </div>+ )}+ {(lastRun?.status === 'completed' || lastRunCheckpoints > 0) && (<CheckpointPicker run={lastRun} onPromoted={refreshRuns} />)}<div className="grid grid-cols-2 gap-3">diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.jsindex 6ea86b1a42..6ff4c475cf 100644--- a/client/src/services/apiLoraTraining.js+++ b/client/src/services/apiLoraTraining.js@@ -88,6 +88,11 @@ export const getLoraTrainingRun = (runId) => request(`/lora-training/runs/${runIexport const cancelLoraTrainingRun = (runId) =>request(`/lora-training/runs/${runId}/cancel`, { method: 'POST' });+// Resume a failed/canceled run from its latest checkpoint — continues the same+// run (new job, same run id) so the trainer picks up its saved optimizer state.+export const resumeLoraTrainingRun = (runId, { silent = false } = {}) =>+ request(`/lora-training/runs/${runId}/resume`, { method: 'POST', silent });+// 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) =>diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.jsindex f34a481b8d..c729200a19 100644--- a/server/routes/loraTraining.js+++ b/server/routes/loraTraining.js@@ -24,6 +24,7 @@ import {listRuns,listSamples,promoteCheckpoint,+ resumeTrainingRun,runDir,runSamplesDir,startTrainingRun,@@ -95,6 +96,14 @@ router.post('/runs/:id/cancel', asyncHandler(async (req, res) => {res.json(result);}));+// Resume a failed/canceled run from its latest checkpoint — re-enqueues a job+// against the SAME run id (mflux bakes the output path into the checkpoint, so+// the resumed trainer must write back into the original run dir). 202-shaped.+router.post('/runs/:id/resume', asyncHandler(async (req, res) => {+ await getRunRequired(req.params.id); // 404 if the run is unknown+ res.status(202).json(await resumeTrainingRun(req.params.id));+}));+router.delete('/runs/:id', asyncHandler(async (req, res) => {const run = await getRunRequired(req.params.id);if (['queued', 'running'].includes(run.status)) {diff --git a/server/services/loraTraining/checkpoints.js b/server/services/loraTraining/checkpoints.jsindex fd0c9d932a..c0ba017535 100644--- a/server/services/loraTraining/checkpoints.js+++ b/server/services/loraTraining/checkpoints.js@@ -157,6 +157,34 @@ export async function isPreviewCollapsed(previewPath) {const pad7 = (n) => String(n).padStart(7, '0');const pad6 = (n) => String(n).padStart(6, '0');+/**+ * Resolve the latest on-disk checkpoint ARTIFACT (not its adapter) for a run,+ * runtime-aware — the resume point a re-launched run hands the trainer:+ * - mflux: the newest `*_checkpoint.zip` (full optimizer + adapter state) in+ * the run's checkpoints dir → `mflux-train --resume <zip>`.+ * - flux2: the highest `checkpoints/step-NNNNNN/` dir → `--resume-from <dir>`.+ * Reads the disk directly (the trainer may have written more checkpoints than+ * the debounced run record captured before it was killed). Returns+ * `{ step, path }` (absolute) or null when nothing resumable exists.+ */+export function resolveLatestCheckpointArtifact(run) {+ // Highest-step entry whose name parses, among those a runtime-specific filter+ // keeps. Returns { step, path } (absolute) or null.+ const latest = (dir, keep) => {+ if (!existsSync(dir)) return null;+ return readdirSync(dir)+ .filter(keep)+ .map((n) => ({ step: stepFromCheckpointName(n) ?? -1, path: join(dir, n) }))+ .filter((c) => c.step >= 0)+ .sort((a, b) => b.step - a.step)[0] || null;+ };+ if (run.runtime === TRAINING_RUNTIMES.MFLUX) {+ return latest(join(resolveMfluxOutputDir(run.id), 'checkpoints'), (n) => n.endsWith('.zip'));+ }+ const dir = join(runDirFor(run.id), 'checkpoints');+ return latest(dir, (n) => existsSync(join(dir, n, 'pytorch_lora_weights.safetensors')));+}+/*** Resolve a checkpoint's adapter weights to a Buffer, runtime-aware:* - mflux: crack `*_adapter.safetensors` out of the step's checkpoint zip.diff --git a/server/services/loraTraining/checkpoints.test.js b/server/services/loraTraining/checkpoints.test.jsindex 03f7411e57..f5959c3799 100644--- a/server/services/loraTraining/checkpoints.test.js+++ b/server/services/loraTraining/checkpoints.test.js@@ -26,6 +26,7 @@ const {listRunSamples,isPreviewCollapsed,resolveCheckpointAdapterBuffer,+ resolveLatestCheckpointArtifact,selectDeployableCheckpoint,COLLAPSE_ENTROPY_MAX,} = await import('./checkpoints.js');@@ -119,6 +120,16 @@ describe('loraTraining/checkpoints', () => {expect(list[1].deployed).toBe(false);});+ it('resolves the latest on-disk checkpoint zip as the mflux resume point', () => {+ const latest = resolveLatestCheckpointArtifact(buildRun());+ expect(latest).toMatchObject({ step: 500 });+ expect(latest.path).toContain(join('mflux', 'checkpoints', '0000500_checkpoint.zip'));+ });++ it('returns null when a run has no checkpoint dir to resume from', () => {+ expect(resolveLatestCheckpointArtifact({ id: 'no-such-run', runtime: 'mflux' })).toBeNull();+ });+it('lists samples as step+url sorted by step (seeds the live gallery)', () => {const samples = listRunSamples(buildRun());expect(samples.map((s) => s.step)).toEqual([250, 500]);diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex d49f3ef2a9..bf1d0061e8 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -45,6 +45,7 @@ import {listRunCheckpoints,listRunSamples,resolveCheckpointAdapterBuffer,+ resolveLatestCheckpointArtifact,selectDeployableCheckpoint,} from './checkpoints.js';import * as runsDb from './db.js';@@ -97,6 +98,30 @@ const mergeParams = (settings, requestParams = {}) => ({...requestParams,});+// A dataset belongs to a run only while it still points at the run's character.+// Match the full (universeId, entryId) key the dataset store uses — a different+// universe can reuse the same entryId, so entryId alone would falsely re-own a+// reassigned dataset. (flipDatasetAfterRun keeps its own missing-entryId+// fallthrough for pre-reassignment runs that predate the character snapshot.)+const sameCharacter = (a, b) =>+ a?.entryId === b?.entryId && a?.universeId === b?.universeId;++// Re-stamp a dataset as `training` with the run's new job/run ids, but only+// while it still owns the dataset — the dataset can be reassigned to a different+// character between validation and this stamp (patchDataset resets it to draft);+// stamping a moved dataset would strand it in `training` forever (flipDatasetAfterRun+// is character-guarded and would skip the un-flip). Used by both the fresh-launch+// and resume paths.+const stampDatasetTrainingStatus = (run, jobId) =>+ updateDataset(run.datasetId, (current) => {+ if (!sameCharacter(current.character, run.character)) return null;+ return {+ ...current,+ status: 'training',+ training: { ...current.training, lastJobId: jobId, lastRunId: run.id },+ };+ }).catch((err) => console.error(`❌ dataset training-status stamp failed: ${err?.message}`));+/*** Route-facing run launcher. Validates dataset readiness + runtime health,* creates the run record, and enqueues the training job. Returns@@ -166,26 +191,100 @@ export async function startTrainingRun({ datasetId, baseModelId, name = null, pa},});await runsDb.updateRun(runId, { jobId: queued.jobId });- await updateDataset(datasetId, (current) => {- // Same-record re-entrancy guard: if the dataset was reassigned to a- // different character between validateDatasetReady above and this stamp,- // this run no longer owns it. Don't stamp 'training' — flipDatasetAfterRun- // skips character-mismatched runs, so a stamp here would strand the- // reassigned dataset in 'training' forever. Match the full- // (universeId, entryId) key the dataset store uses elsewhere.- if (current.character?.entryId !== run.character.entryId- || current.character?.universeId !== run.character.universeId) return null;- return {- ...current,- status: 'training',- training: { ...current.training, lastJobId: queued.jobId, lastRunId: runId },- };- }).catch((err) => console.error(`❌ dataset training-status stamp failed: ${err?.message}`));+ await stampDatasetTrainingStatus(run, queued.jobId);console.log(`🏋️ Training run ${shortId(runId)} queued — ${routing.runtime}/${baseModelId} dataset=${shortId(datasetId)} job=${shortId(queued.jobId)}`);return { runId, jobId: queued.jobId, position: queued.position, status: 'queued' };}+/**+ * Resume a failed/canceled run from its latest on-disk checkpoint. mflux bakes+ * the output path into the checkpoint zip and reads everything (config, dataset+ * paths, optimizer + adapter state, step counter) from `--resume <zip>` — so a+ * resume MUST re-run in the ORIGINAL run dir, not a fresh one, or the trainer+ * would write its new artifacts where the wrapper's watcher can't see them.+ * We therefore re-enqueue a new job against the SAME runId: new checkpoints and+ * samples append to the existing artifact arrays (the checkpoint picker shows+ * the full timeline across the resume), and finalize registers the LoRA as+ * usual. Progress may briefly read low if the trainer restarts its step bar at+ * the resume point — cosmetic; the durable record catches up on the next flush.+ */+export async function resumeTrainingRun(runId) {+ const run = await runsDb.getRunRequired(runId);+ if (!['failed', 'canceled'].includes(run.status)) {+ throw new ServerError(`Can only resume a failed or canceled run (status: ${run.status})`, {+ status: 409, code: 'RUN_NOT_RESUMABLE',+ });+ }+ const checkpoint = resolveLatestCheckpointArtifact(run);+ if (!checkpoint) {+ throw new ServerError(+ 'No checkpoint to resume from — the run was killed before its first checkpoint saved. Start a fresh run.',+ { status: 409, code: 'NO_RESUMABLE_CHECKPOINT' },+ );+ }++ // Re-validate dataset readiness + ownership exactly like a fresh launch — the+ // dataset may have been edited, deleted, or reassigned since the run failed.+ const { dataset } = await validateDatasetReady(run.datasetId);+ if (!sameCharacter(dataset.character, run.character)) {+ throw new ServerError('Dataset was reassigned to a different character — start a fresh run.', {+ status: 409, code: 'DATASET_REASSIGNED',+ });+ }++ // Engine health: mirror startTrainingRun for the run's existing runtime.+ const settings = await getSettings();+ const pythonPath = settings?.imageGen?.local?.pythonPath || null;+ if (run.runtime === TRAINING_RUNTIMES.FLUX2) {+ if (!(await isFlux2VenvHealthy())) {+ throw new ServerError('FLUX.2 training venv is unavailable — run `bash scripts/setup-image-video.sh`', {+ status: 412, code: 'TRAINING_ENGINE_MISSING',+ });+ }+ } else if (!isMfluxTrainAvailable(pythonPath)) {+ throw new ServerError('mflux-train not found next to the configured python — update mflux (≥0.17)', {+ status: 412, code: 'TRAINING_ENGINE_MISSING',+ });+ }++ const queued = enqueueJob({+ kind: 'training',+ owner: 'lora-training',+ params: {+ runId,+ runtime: run.runtime,+ datasetId: run.datasetId,+ characterId: run.character?.entryId,+ characterName: run.character?.name,+ triggerWord: run.triggerWord,+ baseModelId: run.baseModelId,+ steps: run.params?.steps,+ rank: run.params?.rank,+ pythonPath,+ resumeCheckpoint: checkpoint.path,+ },+ });+ await runsDb.updateRun(runId, (current) => ({+ ...current,+ status: 'queued',+ jobId: queued.jobId,+ error: null,+ errorCode: null,+ errorRepo: null,+ completedAt: null,+ resume: {+ count: (current.resume?.count || 0) + 1,+ fromStep: checkpoint.step,+ resumedAt: new Date().toISOString(),+ },+ }));+ await stampDatasetTrainingStatus(run, queued.jobId);++ console.log(`🏋️ Training run ${shortId(runId)} resumed from step ${checkpoint.step} — job=${shortId(queued.jobId)}`);+ return { runId, jobId: queued.jobId, position: queued.position, status: 'queued', fromStep: checkpoint.step };+}+const emitFailed = (jobId, error) => trainingEvents.emit('failed', { generationId: jobId, error });const flipDatasetAfterRun = (run, { trained, loraFilename = null }) => {@@ -228,7 +327,7 @@ const flipDatasetAfterRun = (run, { trained, loraFilename = null }) => {* queue's dispatcher; this function resolves once the child is spawned* (the queue awaits the terminal event separately).*/-export async function runTraining({ jobId, runId, pythonPath = null }) {+export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckpoint = null }) {const fail = (message) => {console.error(`❌ training [${shortId(jobId)}] ${message}`);emitFailed(jobId, message);@@ -264,8 +363,7 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {// run's now-stale character. failBeforeSpawn's flipDatasetAfterRun is// character-guarded, so it won't disturb the reassigned dataset's state.// Match the full (universeId, entryId) key the dataset store uses elsewhere.- if (dataset.character?.entryId !== run.character.entryId- || dataset.character?.universeId !== run.character.universeId) {+ if (!sameCharacter(dataset.character, run.character)) {return failBeforeSpawn('Dataset was reassigned to a different character after this run was queued — cancel and retrain.');}@@ -301,6 +399,7 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {triggerWord: run.triggerWord,params: run.params,samplePrompt: run.params?.samplePrompt || null,+ resumeFrom: resumeCheckpoint,});} else {bin = pythonPath;@@ -344,6 +443,7 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {configPath,runDir: dir,totalSteps: run.params?.steps || TRAINING_DEFAULTS.steps,+ resumeCheckpoint,});}} catch (err) {@@ -357,7 +457,7 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {delete childEnv.PYTHONPATH;childEnv.PYTHONUNBUFFERED = '1';- console.log(`🏋️ training [${shortId(jobId)}] spawn ${basename(bin)} ${run.runtime} steps=${run.params.steps} rank=${run.params.rank} images=${manifest.images.length}`);+ console.log(`🏋️ training [${shortId(jobId)}] spawn ${basename(bin)} ${run.runtime} steps=${run.params.steps} rank=${run.params.rank} images=${manifest.images.length}${resumeCheckpoint ? ` resume=${basename(resumeCheckpoint)}` : ''}`);const proc = spawn(bin, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });activeProcess = proc;activeJobId = jobId;@@ -613,12 +713,14 @@ export async function listSamples(runId) {*/export async function promoteCheckpoint(runId, step) {const run = await runsDb.getRunRequired(runId);- // Only completed runs (matching the UI, which exposes the picker only there).- // Promoting flips the dataset to `trained` + deploys a LoRA — a failed or- // canceled run shouldn't masquerade as trained off a partial checkpoint.- if (run.status !== 'completed') {- throw new ServerError('Can only promote a checkpoint from a completed run', {- status: 409, code: 'RUN_NOT_COMPLETED',+ // Allow completed runs AND failed/canceled runs that saved at least one+ // checkpoint — promoting a partial checkpoint is a deliberate salvage (the+ // human clicks "Use this" on a specific preview), the same explicit intent+ // the completed-run picker relies on. Only an in-flight run is blocked: its+ // checkpoints are still moving, so "deploy this one" is ambiguous.+ if (['queued', 'running'].includes(run.status)) {+ throw new ServerError('Cancel the run before promoting a checkpoint', {+ status: 409, code: 'RUN_ACTIVE',});}const listed = listRunCheckpoints(run);diff --git a/server/services/loraTraining/runtimes.test.js b/server/services/loraTraining/runtimes.test.jsindex 995f359ffb..2b30dc1654 100644--- a/server/services/loraTraining/runtimes.test.js+++ b/server/services/loraTraining/runtimes.test.js@@ -141,6 +141,29 @@ describe('buildMfluxTrainArgs / buildFlux2TrainArgs', () => {expect(args[args.indexOf('--sample-prompt') + 1]).toContain('kessa');});+ it('appends the resume flag for each runtime when a checkpoint is given', () => {+ const mflux = buildMfluxTrainArgs({+ scriptPath: '/x/train_mflux_lora.py', configPath: '/r/cfg.json', runDir: '/r', totalSteps: 500,+ resumeCheckpoint: '/r/mflux/checkpoints/0000150_checkpoint.zip',+ });+ expect(mflux[mflux.indexOf('--resume-checkpoint') + 1]).toBe('/r/mflux/checkpoints/0000150_checkpoint.zip');++ const flux2 = buildFlux2TrainArgs({+ scriptPath: '/x/train_flux2_lora.py',+ trainRepo: 'black-forest-labs/FLUX.2-klein-4B',+ manifestPath: '/r/manifest.json', runDir: '/r', triggerWord: 'kessa',+ resumeFrom: '/r/checkpoints/step-000150',+ });+ expect(flux2[flux2.indexOf('--resume-from') + 1]).toBe('/r/checkpoints/step-000150');+ });++ it('omits the resume flag on a fresh run', () => {+ const args = buildMfluxTrainArgs({+ scriptPath: '/x.py', configPath: '/r/cfg.json', runDir: '/r', totalSteps: 500,+ });+ expect(args).not.toContain('--resume-checkpoint');+ });+it('refuses non-bf16 train repos', () => {expect(() => buildFlux2TrainArgs({scriptPath: '/x.py', trainRepo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',