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

feat([issue-1252]): true optimizer-state resume for the FLUX.2 torch LoRA trainer

[._.]/ Adam Eivy72674925f375
diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsx
index a87daac960..0a3b8c8e23 100644
--- a/client/src/components/loraTraining/TrainingPanel.jsx
+++ b/client/src/components/loraTraining/TrainingPanel.jsx
@@ -126,13 +126,14 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
// A killed run keeps its checkpoints — surface the picker (view + salvage a
// partial LoRA) whenever a non-completed run recorded one, and a Resume button
- // for any failed/canceled mflux run. Gate Resume on status, NOT the recorded
+ // for any failed/canceled run. Gate Resume on status, NOT the recorded
// checkpoint count: a crash can kill the run before the debounced record
// persists its last checkpoint, yet the server resumes from disk — let its
- // 409 (NO_RESUMABLE_CHECKPOINT) handle the genuinely-empty case. mflux only;
- // the FLUX.2 torch trainer's resume restarts the optimizer (server refuses it).
+ // 409 (NO_RESUMABLE_CHECKPOINT) handle the genuinely-empty case. Both runtimes
+ // support true optimizer-state resume (mflux via --resume, FLUX.2 torch via
+ // --resume-from), so this no longer filters by runtime.
const lastRunCheckpoints = lastRun?.artifacts?.checkpoints?.length || 0;
- const canResume = lastRun && ['failed', 'canceled'].includes(lastRun.status) && lastRun.runtime === 'mflux';
+ const canResume = lastRun && ['failed', 'canceled'].includes(lastRun.status);
const disabledReason = !readiness?.trainable
? `Needs ${readiness?.required ?? 10} captioned images (have ${readiness?.captioned ?? 0})`
diff --git a/scripts/train_flux2_lora.py b/scripts/train_flux2_lora.py
index 3537007859..8d8338daf2 100644
--- a/scripts/train_flux2_lora.py
+++ b/scripts/train_flux2_lora.py
@@ -77,7 +77,8 @@ def parse_args():
p.add_argument("--sample-prompt", default=None)
p.add_argument("--seed", type=int, default=42)
p.add_argument("--device", default="auto")
- p.add_argument("--resume-from", default=None, help="checkpoint dir to load adapter weights from")
+ p.add_argument("--resume-from", default=None,
+ help="checkpoint dir to resume from (restores adapter weights + AdamW optimizer state + step offset)")
return p.parse_args()
@@ -113,13 +114,20 @@ def lora_target_modules(transformer) -> list:
return sorted(found)
-def save_checkpoint(pipe_cls, transformer, out_dir: Path, step: int) -> Path:
+def save_checkpoint(pipe_cls, transformer, optimizer, out_dir: Path, step: int) -> Path:
+ """Persist BOTH the adapter weights AND the AdamW optimizer state for the
+ step, so `--resume-from` can continue mid-run (correct optimizer momentum +
+ a starting-step offset) instead of warm-starting the adapter into a fresh
+ `args.steps`-long loop — that would over-train and re-collide step numbers.
+ The optimizer tensors are saved on CPU; `load_state_dict` re-casts them onto
+ the (fp32, on-device) trainable params at resume."""
from peft.utils import get_peft_model_state_dict
ckpt_dir = out_dir / "checkpoints" / f"step-{step:06d}"
ckpt_dir.mkdir(parents=True, exist_ok=True)
state = get_peft_model_state_dict(transformer)
pipe_cls.save_lora_weights(str(ckpt_dir), transformer_lora_layers=state)
+ torch.save({"optimizer": optimizer.state_dict(), "step": step}, ckpt_dir / "optimizer.pt")
(ckpt_dir / "state.json").write_text(json.dumps({"step": step}))
return ckpt_dir
@@ -256,12 +264,37 @@ def main():
p.data = p.data.to(torch.float32)
optimizer = torch.optim.AdamW(trainable, lr=args.lr, weight_decay=0.01)
+ # Resume: restore the AdamW state + a starting-step offset so the loop
+ # continues toward the ORIGINAL total (range(start_step + 1, args.steps + 1))
+ # rather than running a fresh args.steps from the warm-started adapter. Falls
+ # back to the step recorded in state.json when an older checkpoint predates
+ # optimizer.pt — that at least keeps the step counter from renumber-colliding,
+ # even though momentum starts cold. (RNG state is intentionally not restored;
+ # the per-step noise/timestep sequence restarts from the seed, which is
+ # immaterial to training quality — the load-bearing fix is optimizer + step.)
+ start_step = 0
+ if args.resume_from:
+ resume_dir = Path(args.resume_from)
+ opt_file = resume_dir / "optimizer.pt"
+ if opt_file.exists():
+ ckpt = torch.load(opt_file, map_location="cpu")
+ optimizer.load_state_dict(ckpt["optimizer"])
+ start_step = int(ckpt.get("step", 0))
+ log(f"STATUS:resumed optimizer state — continuing from step {start_step}")
+ else:
+ state_file = resume_dir / "state.json"
+ if state_file.exists():
+ start_step = int(json.loads(state_file.read_text()).get("step", 0))
+ log(f"STATUS:no optimizer state in checkpoint — adapter warm-start only, from step {start_step}")
+ if start_step >= args.steps:
+ log(f"STATUS:resume point (step {start_step}) already at/past target {args.steps} — nothing to train")
+
order = list(range(len(examples)))
rng = torch.Generator().manual_seed(args.seed)
final_loss = None
last_checkpoint = None
- for step in range(1, args.steps + 1):
+ for step in range(start_step + 1, args.steps + 1):
if (step - 1) % len(order) == 0:
order = torch.randperm(len(examples), generator=rng).tolist()
ex = examples[order[(step - 1) % len(order)]]
@@ -295,13 +328,13 @@ def main():
log(f"STEP:{step}:{args.steps}:{final_loss:.4f}")
if STOP_REQUESTED:
- ckpt = save_checkpoint(Flux2KleinPipeline, transformer, out_dir, step)
+ ckpt = save_checkpoint(Flux2KleinPipeline, transformer, optimizer, out_dir, step)
log(f"CHECKPOINT:{ckpt}:{step}")
log("STATUS:canceled-checkpoint-saved")
os._exit(143)
if args.checkpoint_every > 0 and step % args.checkpoint_every == 0 and step < args.steps:
- ckpt = save_checkpoint(Flux2KleinPipeline, transformer, out_dir, step)
+ ckpt = save_checkpoint(Flux2KleinPipeline, transformer, optimizer, out_dir, step)
last_checkpoint = ckpt
log(f"CHECKPOINT:{ckpt}:{step}")
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index c24e09b045..5c6c260dab 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -216,19 +216,12 @@ export async function resumeTrainingRun(runId) {
status: 409, code: 'RUN_NOT_RESUMABLE',
});
}
- // mflux only: its `--resume <zip>` restores optimizer state AND the step
- // counter, so training picks up mid-run and finishes at the original total.
- // The torch FLUX.2 trainer's `--resume-from` only warm-starts the adapter
- // weights and then runs a FRESH optimizer loop for the full `steps` again —
- // that would over-train and re-collide checkpoint step numbers, not resume.
- // The arg-builder wiring (buildFlux2TrainArgs `resumeFrom`) is in place for
- // when the trainer learns true optimizer-state resume; until then, refuse it.
- if (run.runtime === TRAINING_RUNTIMES.FLUX2) {
- throw new ServerError(
- 'Resume is only supported for mflux (MLX) runs right now — the FLUX.2 torch trainer restarts its optimizer from step 0, which would over-train. Start a fresh run.',
- { status: 409, code: 'RESUME_UNSUPPORTED_RUNTIME' },
- );
- }
+ // Both runtimes restore optimizer state + the step counter on resume, so
+ // training picks up mid-run and finishes at the original total: mflux via
+ // `mflux-train --resume <zip>`, and the torch FLUX.2 trainer via
+ // `--resume-from <dir>` (restores the AdamW state from the checkpoint's
+ // optimizer.pt and continues range(start_step + 1, steps + 1) — no
+ // over-training, no checkpoint renumber collisions).
const checkpoint = resolveLatestCheckpointArtifact(run);
if (!checkpoint) {
throw new ServerError(
diff --git a/server/services/loraTraining/resume.test.js b/server/services/loraTraining/resume.test.js
new file mode 100644
index 0000000000..dd3bd45950
--- /dev/null
+++ b/server/services/loraTraining/resume.test.js
@@ -0,0 +1,97 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock every external dependency resumeTrainingRun reaches so we can drive the
+// branch logic without a real DB, queue, or python venv. Keeping runtimes.js
+// real lets the test reference TRAINING_RUNTIMES.FLUX2 against the same source.
+const getRunRequiredMock = vi.fn();
+const updateRunMock = vi.fn();
+const resolveLatestCheckpointArtifactMock = vi.fn();
+const validateDatasetReadyMock = vi.fn();
+const enqueueJobMock = vi.fn();
+const updateDatasetMock = vi.fn();
+const isFlux2VenvHealthyMock = vi.fn();
+
+vi.mock('./db.js', () => ({
+ getRunRequired: (...a) => getRunRequiredMock(...a),
+ updateRun: (...a) => updateRunMock(...a),
+ getRun: vi.fn(),
+ listRuns: vi.fn(),
+ deleteRun: vi.fn(),
+}));
+vi.mock('./checkpoints.js', () => ({
+ resolveLatestCheckpointArtifact: (...a) => resolveLatestCheckpointArtifactMock(...a),
+ listRunCheckpoints: vi.fn(),
+ listRunSamples: vi.fn(),
+ resolveCheckpointAdapterBuffer: vi.fn(),
+ selectDeployableCheckpoint: vi.fn(),
+}));
+vi.mock('./dataset.js', () => ({ validateDatasetReady: (...a) => validateDatasetReadyMock(...a) }));
+vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+vi.mock('../../lib/pythonSetup.js', () => ({
+ isFlux2VenvHealthy: (...a) => isFlux2VenvHealthyMock(...a),
+ resolveFlux2Python: vi.fn(() => '/venv/python'),
+}));
+vi.mock('../mediaJobQueue/index.js', () => ({
+ enqueueJob: (...a) => enqueueJobMock(...a),
+ getJob: vi.fn(),
+ mediaJobEvents: { emit: vi.fn(), on: vi.fn() },
+}));
+vi.mock('../loraDatasets.js', () => ({ updateDataset: (...a) => updateDatasetMock(...a) }));
+
+const { TRAINING_RUNTIMES } = await import('./runtimes.js');
+const { resumeTrainingRun } = await import('./index.js');
+
+const flux2Run = (overrides = {}) => ({
+ id: 'run-flux2',
+ status: 'failed',
+ runtime: TRAINING_RUNTIMES.FLUX2,
+ datasetId: 'ds-1',
+ character: { entryId: 'c1', universeId: 'u1' },
+ triggerWord: 'kessa',
+ baseModelId: 'm1',
+ params: { steps: 600, rank: 16 },
+ ...overrides,
+});
+
+describe('resumeTrainingRun — flux2 path', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ updateRunMock.mockResolvedValue();
+ updateDatasetMock.mockResolvedValue();
+ validateDatasetReadyMock.mockResolvedValue({ dataset: { character: { entryId: 'c1', universeId: 'u1' } } });
+ isFlux2VenvHealthyMock.mockResolvedValue(true);
+ enqueueJobMock.mockReturnValue({ jobId: 'job-1', position: 0 });
+ });
+
+ it('enqueues a resume job for a failed flux2 run (no RESUME_UNSUPPORTED_RUNTIME)', async () => {
+ getRunRequiredMock.mockResolvedValue(flux2Run());
+ resolveLatestCheckpointArtifactMock.mockReturnValue({ step: 150, path: '/runs/run-flux2/checkpoints/step-000150' });
+
+ const result = await resumeTrainingRun('run-flux2');
+
+ expect(result).toMatchObject({ runId: 'run-flux2', jobId: 'job-1', status: 'queued', fromStep: 150 });
+ expect(enqueueJobMock).toHaveBeenCalledTimes(1);
+ const job = enqueueJobMock.mock.calls[0][0];
+ expect(job.kind).toBe('training');
+ expect(job.params.runtime).toBe(TRAINING_RUNTIMES.FLUX2);
+ // The checkpoint dir flows through to the trainer's --resume-from.
+ expect(job.params.resumeCheckpoint).toBe('/runs/run-flux2/checkpoints/step-000150');
+ // The run record is flipped back to queued with the resume bookkeeping.
+ expect(updateRunMock).toHaveBeenCalledWith('run-flux2', expect.any(Function));
+ });
+
+ it('still rejects a flux2 run with no on-disk checkpoint (NO_RESUMABLE_CHECKPOINT)', async () => {
+ getRunRequiredMock.mockResolvedValue(flux2Run());
+ resolveLatestCheckpointArtifactMock.mockReturnValue(null);
+
+ await expect(resumeTrainingRun('run-flux2')).rejects.toMatchObject({ code: 'NO_RESUMABLE_CHECKPOINT' });
+ expect(enqueueJobMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses to resume a still-running flux2 run (RUN_NOT_RESUMABLE)', async () => {
+ getRunRequiredMock.mockResolvedValue(flux2Run({ status: 'running' }));
+
+ await expect(resumeTrainingRun('run-flux2')).rejects.toMatchObject({ code: 'RUN_NOT_RESUMABLE' });
+ expect(enqueueJobMock).not.toHaveBeenCalled();
+ });
+});