Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([issue-1252]): address claude+codex review — load resume adapter into the same default adapter

[._.]/ Adam Eivy897840d1b8a5
diff --git a/scripts/train_flux2_lora.py b/scripts/train_flux2_lora.py
index 8d8338daf2..19adb85dc8 100644
--- a/scripts/train_flux2_lora.py
+++ b/scripts/train_flux2_lora.py
@@ -78,7 +78,7 @@ def parse_args():
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 resume from (restores adapter weights + AdamW optimizer state + step offset)")
+ help="checkpoint dir to resume from (restores adapter + AdamW optimizer state + step offset from optimizer.pt)")
return p.parse_args()
@@ -115,19 +115,30 @@ def lora_target_modules(transformer) -> list:
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."""
+ """Persist the adapter for inference/promotion AND a self-contained resume
+ bundle (`optimizer.pt`) carrying the AdamW state, the PEFT adapter state, and
+ the step counter — so `--resume-from` continues mid-run (correct optimizer
+ momentum + starting-step offset) instead of warm-starting into a fresh
+ `args.steps`-long loop (which would over-train and re-collide step numbers).
+
+ The adapter goes into the bundle as its PEFT state dict (not via the diffusers
+ loader) so resume can restore it into the SAME `default` adapter with
+ `set_peft_model_state_dict` — round-tripping `get_peft_model_state_dict`
+ exactly. Loading the `pytorch_lora_weights.safetensors` back through
+ `pipe.load_lora_weights()` would instead inject a SECOND adapter
+ (`get_adapter_name` returns `default_<n>` when one already exists), leaving the
+ trained weights in `default_1` while export reads `default` — silently wrong.
+ Saved on CPU; `load_state_dict` re-casts onto the fp32 on-device params."""
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")
+ torch.save(
+ {"optimizer": optimizer.state_dict(), "adapter": state, "step": step},
+ ckpt_dir / "optimizer.pt",
+ )
(ckpt_dir / "state.json").write_text(json.dumps({"step": step}))
return ckpt_dir
@@ -243,17 +254,16 @@ def main():
transformer.requires_grad_(False)
targets = lora_target_modules(transformer)
log(f"STATUS:LoRA targets: {', '.join(targets)} (rank {args.rank})")
+ # Always create the single trainable `default` adapter (gaussian init). On
+ # resume its weights are overwritten in-place below from the checkpoint's
+ # PEFT state dict — NOT via pipe.load_lora_weights(), which would inject a
+ # second `default_<n>` adapter and leave training/export out of sync.
transformer.add_adapter(LoraConfig(
r=args.rank,
lora_alpha=args.rank,
init_lora_weights="gaussian",
target_modules=targets,
))
- if args.resume_from:
- resume_dir = Path(args.resume_from)
- if resume_dir.exists():
- pipe.load_lora_weights(str(resume_dir))
- log(f"STATUS:resumed adapter weights from {resume_dir}")
transformer.enable_gradient_checkpointing()
transformer.to(device)
transformer.train()
@@ -264,28 +274,36 @@ 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.)
+ # Resume: restore the adapter weights, AdamW state, and a starting-step
+ # offset from the checkpoint's optimizer.pt bundle, so the loop continues
+ # toward the ORIGINAL total (range(start_step + 1, args.steps + 1)) with warm
+ # momentum instead of re-running a fresh args.steps from a random adapter.
+ # The adapter is loaded into the existing `default` adapter via
+ # set_peft_model_state_dict (in-place — param identities, and therefore the
+ # optimizer state alignment, are preserved). The server only hands us
+ # checkpoints that carry optimizer.pt (resolveLatestCheckpointArtifact gates
+ # on it); a checkpoint that predates optimizer-state resume is a hard error
+ # rather than a silent cold-start onto the random gaussian adapter. (RNG
+ # state is intentionally not restored; the per-step noise/timestep sequence
+ # restarts from the seed, immaterial to quality — the load-bearing fix is
+ # adapter + 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}")
+ from peft.utils import set_peft_model_state_dict
+
+ opt_file = Path(args.resume_from) / "optimizer.pt"
+ if not opt_file.exists():
+ print(
+ f"USER_ERROR:TRAINING_FAILED:resume checkpoint has no optimizer state ({opt_file}) — "
+ "it predates optimizer-state resume; start a fresh run",
+ file=sys.stderr, flush=True,
+ )
+ sys.exit(1)
+ ckpt = torch.load(opt_file, map_location="cpu")
+ set_peft_model_state_dict(transformer, ckpt["adapter"], adapter_name="default")
+ optimizer.load_state_dict(ckpt["optimizer"])
+ start_step = int(ckpt.get("step", 0))
+ log(f"STATUS:resumed adapter + optimizer state — continuing 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")
diff --git a/server/services/loraTraining/checkpoints.js b/server/services/loraTraining/checkpoints.js
index c0ba017535..522eb4ae64 100644
--- a/server/services/loraTraining/checkpoints.js
+++ b/server/services/loraTraining/checkpoints.js
@@ -162,10 +162,16 @@ const pad6 = (n) => String(n).padStart(6, '0');
* 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.
+ * - flux2: the highest `checkpoints/step-NNNNNN/` dir that carries an
+ * `optimizer.pt` resume bundle → `--resume-from <dir>`.
+ * A flux2 checkpoint dir that has only `pytorch_lora_weights.safetensors` (one
+ * written before optimizer-state resume existed) is NOT a resume point — the
+ * trainer can't restore optimizer state from it and would otherwise cold-start
+ * onto a random adapter. Such checkpoints are still listed/promotable via
+ * listRunCheckpoints + resolveCheckpointAdapterBuffer; they just can't be
+ * resumed. 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
@@ -182,7 +188,7 @@ export function resolveLatestCheckpointArtifact(run) {
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')));
+ return latest(dir, (n) => existsSync(join(dir, n, 'optimizer.pt')));
}
/**
diff --git a/server/services/loraTraining/checkpoints.test.js b/server/services/loraTraining/checkpoints.test.js
index c1c57caa41..ead5a5b6ae 100644
--- a/server/services/loraTraining/checkpoints.test.js
+++ b/server/services/loraTraining/checkpoints.test.js
@@ -130,19 +130,30 @@ describe('loraTraining/checkpoints', () => {
expect(resolveLatestCheckpointArtifact({ id: 'no-such-run', runtime: 'mflux' })).toBeNull();
});
- it('resolves the latest flux2 checkpoint dir (the one with adapter weights)', async () => {
+ it('resolves the latest flux2 checkpoint dir that carries an optimizer.pt resume bundle', async () => {
const id = 'run-flux2-fixture';
const ckpts = join(dataRoot, 'training-runs', id, 'checkpoints');
mkdirSync(join(ckpts, 'step-000100'), { recursive: true });
mkdirSync(join(ckpts, 'step-000200'), { recursive: true });
mkdirSync(join(ckpts, 'step-000300'), { recursive: true }); // no weights yet — must be skipped
await writeFile(join(ckpts, 'step-000100', 'pytorch_lora_weights.safetensors'), Buffer.from('w1'));
+ await writeFile(join(ckpts, 'step-000100', 'optimizer.pt'), Buffer.from('o1'));
await writeFile(join(ckpts, 'step-000200', 'pytorch_lora_weights.safetensors'), Buffer.from('w2'));
+ await writeFile(join(ckpts, 'step-000200', 'optimizer.pt'), Buffer.from('o2'));
const latest = resolveLatestCheckpointArtifact({ id, runtime: 'flux2' });
expect(latest).toMatchObject({ step: 200 });
expect(latest.path).toContain(join('checkpoints', 'step-000200'));
});
+ it('skips a flux2 checkpoint that predates optimizer-state resume (adapter only, no optimizer.pt)', async () => {
+ const id = 'run-flux2-legacy';
+ const ckpts = join(dataRoot, 'training-runs', id, 'checkpoints');
+ mkdirSync(join(ckpts, 'step-000150'), { recursive: true });
+ // Pre-optimizer.pt checkpoint: adapter weights but no resume bundle.
+ await writeFile(join(ckpts, 'step-000150', 'pytorch_lora_weights.safetensors'), Buffer.from('w'));
+ expect(resolveLatestCheckpointArtifact({ id, runtime: 'flux2' })).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]);