Repository navigation
Resume diffusion training from a stop-and-save checkpoint - #8163
Conversation
Stopping a diffusion LoRA run and saving at step 11 wrote only the adapter,
so restarting the same configuration began again at step 1: the AdamW
moments, the LR-schedule position, the sampler cycle, the RNG streams and
the step counter all died with the trainer subprocess.
New core/training/diffusion_checkpoint.py owns a single versioned bundle
format under the run's own output_dir:
checkpoint-<N>/ trainer_state.json manifest + completion marker
adapter_model.safetensors
ema_adapter.safetensors (when ema_decay > 0)
optimizer.pt
scheduler.pt
rng_state.pt
Every file is written into a hidden staging directory whose manifest comes
last, then the directory is promoted with one os.replace, so a killed
process leaves either the previous checkpoint or a .tmp-checkpoint-* nobody
scans - never a half-written bundle that reads as valid. The manifest
records an identity (kind, family, base repo + revision, dataset
fingerprint, LoRA targets/rank/alpha, precision) plus the optimizer class,
and `kind` is carried so a video trainer can reuse the format unchanged.
Both trainers now loop `range(resumed, cfg.train_steps)`: train_steps is the
TARGET TOTAL, so a checkpoint at 11 with a target of 500 runs 12..500. One
writer serves both the new `save_steps` interval (0, off, by default) and
stop-and-save, which keeps producing the deployable adapter exactly as
before and now writes the bundle first, so a failed export still leaves a
resumable run.
The start route validates a resume - path containment, family, base repo,
dataset fingerprint, LoRA shape, precision, remaining steps - alongside the
precision preflight and again after dataset discovery, both BEFORE resident
GPU models are evicted, and pins the exact bundle it accepted. can_resume /
checkpoint_step / checkpoint_path / resume_blocked_reason and the
resumed_from_job_id lineage are persisted and re-derived from disk on every
read, so deleting a checkpoint removes the action instead of leaving a
button that 400s. The Train tab gains a Resume action next to Deploy to
Create, on the partial-adapter card, and on a crashed run's card.
Also fixes the LoRA sidecar recording the configured step count rather than
the one reached: an adapter saved by stopping at 11 of 500 advertised 500.
…ader Five fixes, four of them found by running the thing rather than reading it. A real interrupted-and-resumed SDXL run on a B200 is bit-identical to an uninterrupted control on learning rate, both Adam moments, the LoRA weights and every loss from the resume point on, with torch AdamW and with bitsandbytes AdamW8bit, and after a SIGKILL. Except in one case. CUDA RNG restore was all-or-nothing on the visible-device count. set_rng_state_all needs one state per visible device, so the guard around it meant a bundle written with fewer devices visible than the resume sees restored nothing at all, including cuda:0, the only device training touches. The per-step noise stream then restarted at the wrong offset while the step counter, the LR, the sampler and the optimizer were all correct, so the run completed looking healthy and was silently wrong: all 192 LoRA tensors diverged from the control and the first resumed step was off by 0.024. The trainer is a spawned child inheriting CUDA_VISIBLE_DEVICES, which Studio masks elsewhere, so a mask change between the run and the Resume click was enough. Restore device by device instead; verified bit-exact against the same control. read_checkpoint validated headers and called it a load. The state-file check walks a torch zip's pickle to STOP and wants one non-empty data/ member, so truncating the tensor storages themselves passes it, and torch.load then returns uninitialized memory (non-finite, order 1e22) which the resume feeds to the optimizer as Adam moments. Record each file's size in the manifest and compare it. Additive: a bundle without sizes skips the check rather than failing it, and an older build ignores the key, so no version bump and no orphaned checkpoint. The same header check passes a .pt that torch.load refuses, so a pickle carrying a global outside the weights_only allowlist cleared the start route: 200 OK, resident GPU model evicted, child dead on a raw UnpicklingError. That is the outcome the preflight exists to prevent, so preflight_resume now actually opens every state file the manifest lists and turns any failure into a ResumeError. The listing path keeps the cheap check, because it pays it once per bundle per request. not_before fenced off an earlier run's checkpoints but nothing fenced the other way, so a finished run offered, and would resume, a checkpoint its successor wrote into the shared output directory. The identity gate cannot catch that: same family, base, dataset and LoRA shape. Fence with the run's end time too, leaving a bundle with no created_at alone so an older run stays resumable. Stop-without-saving stopped being a discard. Before periodic checkpoints the output directory was only ever created inside the save gate, so a discard left nothing; now save_steps writes bundles as the run goes and a discard left up to save_total_limit copies of the optimizer state in a directory the user got no artifact from, with no way to see or delete them. Clear them, and remove the directory if it is ours to remove. One thing deliberately not changed: on Windows a genuine fsync failure is still swallowed. CPython maps os.fsync to the UCRT's _commit, which reports every FlushFileBuffers failure as EBADF and puts the real code in _doserrno, so the errno cannot be told apart from a volume that simply cannot flush. Raising on it would fail every save on such a volume, and that write error is sticky for the life of the run record. The size check above covers the truncation a lost writeback actually produces. The docstring now says this instead of claiming the discrimination is universal.
`tsc -b` rejects `Record<string, unknown> as DiffusionTrainingStartRequest`: the two types do not overlap enough for a single-step assertion, and the three required paths are missing from the widened side. This failed every job that builds the frontend. Destructure the three replaced keys off the typed config instead of deleting them off a widened copy, and re-state base_model / data_dir / output_dir, which the guard above has already proved present but `Partial` cannot carry. npm run typecheck clean, npm test 952 passing.
…ld keep Six fixes, mostly about a save or a stop deleting something it had no business deleting. Pruning is by step, and a resume legitimately writes a bundle that is not the highest numbered one in the folder: resume 10, stop at 15 with 20 and 30 present and a limit of 2, and the checkpoint just promoted is the one deleted -- while the service reports checkpoint_saved for a path that no longer exists. The writer now pins the bundle it just promoted. discard_existing cleared the directory before staging anything, so a kill or an I/O error mid-write left the new run with no checkpoint and every earlier run sharing the folder with none either. The old bundles are recorded and removed after the new one is promoted. A no-save stop cleared every bundle in the output directory, including the one a resumed run had continued from -- an accidental resume then a discard left the ORIGINAL stopped run unresumable. Both trainers now record what was there before their first write and remove only their own. Restoring an adapter checked that every SAVED tensor landed, which says nothing about a live trainable parameter the checkpoint never had: a truncated adapter holding a strict subset passed, and the full optimizer state was loaded on top, so restored Adam moments drove freshly initialised weights while the run reported a clean resume. Checked both ways now. EMA is not part of the validated identity, so a resume can enable it for a run that had it off. The EMA is built before the adapter is restored and the checkpoint carries no shadow, so the shadow kept its initialisation noise and every later update, plus the exported EMA adapter, blended that in. It is reseeded from the restored weights instead. A resumed run that died before its first save was reported unresumable, because the source bundle it was validated against predates its own start fence. It falls back to that bundle. And an output directory legitimately named checkpoint-<N> was read as a bundle rather than scanned, so resume was refused with the real checkpoint sitting inside it. Six tests, each confirmed against a mutation of the line it guards.
An image overwritten in place with different content of exactly the same byte length kept its name, its size and its caption, so the fingerprint was unchanged and the resume preflight accepted the dataset. The restored optimizer and scheduler then carried an old experiment on against different training images, which is the one thing the fingerprint exists to refuse. Head and tail rather than the whole file. This runs on the route thread before the resident model is evicted, so hashing every image would make the preflight scale with the dataset; two different images agreeing on their first and last 64 KiB as well as their exact length is not something that arises from editing a dataset. Not tamper-proof, and does not need to be -- the documented tradeoff is pinned by a test that shows two files differing only past both probe windows are indistinguishable.
- the dataset fingerprint sampled a tail only past 128 KiB, so a 64-128 KiB image (most JPEGs) was fingerprinted on its first 64 KiB alone and an in-place replacement sharing that head went unnoticed. - a first save that failed still retired the discard, so the next successful save left an earlier run's higher-numbered bundle in place for a later Resume to pick. - the same-step shortcut returned any valid bundle at that number, so resuming checkpoint-10 in a folder holding checkpoint-15 and stopping at 15 reported a save while dropping the freshly trained state; it now requires the bundle to be the one this run resumed from. - a readable but incomplete EMA shadow was loaded as authoritative, blending restored averages with fresh initialisation for the uncovered tensors while the run reported a clean resume; it is refused with a reason instead.
- the SDXL trainer read out_dir for the pre-run checkpoint scan while it was still unbound on the normal path: every fresh and resumed SDXL run raised UnboundLocalError after the full model setup. - discard identified a run's own bundles by pathname, so one this run had OVERWRITTEN at a pre-existing step survived the discard; identities are captured at run start now. - resuming from directory A into a reused output_dir B skipped the first-save discard, leaving B's higher-numbered bundles to outrank this run. - a bundle with no optimizer or scheduler state loaded as an adapter-only resume, restarting the moments and the schedule while reporting a clean continue. - lora_dropout was absent from the resume identity though both trainers build the adapter with it; the optional-field rule also treated a real 0.0 as unknown, which would have skipped exactly the comparison that matters. - the resumed event's step and total now seed the live counters, so the UI stops showing 0/0 and an early OOM is not persisted as step 0 of 0.
…romotion _seed_source_identity wrote into the state dict that the very next statement replaced with _idle_state(), so a resume that died during the model load persisted no source timestamp after all. It runs after the reset now, and still before the pump thread, which is the only other writer of that state. _promote leaves the slot empty for the instant between the swap-aside and the rename. A history or detail read landing there handed the displaced bundle back, and the writer's own os.replace then failed against a directory that had reappeared, losing the checkpoint. Read-side recovery leaves a freshly written replaced- entry to its writer; a stale- orphan, which no current writer produces, is unaffected, and writers themselves recover immediately. Read-side recovery also walked the entries in filesystem order, so a stacked slot could restore an older branch instead of the bundle that was in it before the crash. It sorts newest first, like the discard path already does. And a bundle whose RNG tensors could not be captured is now a write FAILURE rather than a promoted checkpoint. capture_rng_state returns what it managed to read, so the save reported success, the service emitted checkpoint_saved, and the history advertised a resumable stop that the preflight refuses the moment the user clicks Resume.
os.replace does not restamp a directory -- verified: the inode keeps the mtime the bundle was written with. So an old checkpoint moved aside looked long-abandoned the instant it arrived and the grace added last round protected nothing. The displaced entry is stamped at the moment of the swap. A CUDA run whose get_rng_state_all raised kept the CPU half, which is non-empty, so the write-time check accepted it and the preflight (which only requires torch_cpu) offered it -- and the restore left the CUDA generator at its freshly seeded position, changing every latent, noise and timestep draw after the resume. The capture is all-or-nothing on a CUDA host. describe_resume_state named whatever passed the cheap header scan. The UI sends that exact path back, the preflight treats it as explicit and cannot scan past it, so an unloadable newest bundle defeated the directory fallback built for that case. It now names one that passes the full gate. And the pre-dataset preflight carries no target: the target refusal is terminal, so a newest bundle from another dataset already at the count aborted the scan before the dataset-aware pass could find the one matching the requested images.
…n its own Four fixes from the review round: The parent-side discard ran even after the child had done its own. The child's cleanup hands a displaced slot back to the bundle it replaced, so the path this run wrote to then holds ANOTHER run's checkpoint, and deleting it by pathname destroyed that run's resume point. The state half of the discard still applies either way. prune_checkpoints excluded pre-existing bundles by pathname, so a save at a step whose directory was already there was treated as pre-existing even though the bundle occupying that path is now this run's. The limit could be exceeded once per overwritten slot. It compares identity now, as the cleanup helpers do. fp8 and mxfp8 conversion can fail on the host and both fall back to bf16, while the identity recorded the request. A bundle requested as fp8 and trained in bf16 could resume onto a real fp8 base and report a clean continue. The DiT trainer now records the post-conversion value in a new optional identity field. A landed checkpoint only updated in-memory state, so Studio dying after a periodic save left a resumable bundle that Previous runs -- built from the run JSONs and nothing else -- had no entry or Resume action for. A checkpoint now persists an interim record, written as interrupted because that is the outcome if nothing else happens; the terminal write replaces it, and the reader restates the live job as running.
…p disposition Five fixes from the review round: A checkpoint_failed event made the block sticky in memory only, so a Studio exit after one left the last record advertising the older checkpoint as resumable -- the one the service had just decided is stale. It asks for an interim record now, and a later successful write clears and replaces it. The interim record is written with an error status, so the resume fields were derived as though the run were over and the still-running job came back with can_resume true. Restating it as running clears them. ema_decay joins the identity. restore_resume_state loads the old shadow tensors and update count while the trainer builds LoRAEMA from the incoming decay, so a resume with a different one applies a new coefficient to an average produced under the old. A record with a nonnumeric counter raised out of _refresh_resume_state and took the whole Previous runs endpoint with it, where every other kind of corruption there is skipped per record. Both the listing and the detail read are guarded now. Only the first stop request reaches the child. A later stop-without-saving cannot un-export an adapter the child has already written, so honouring it set a parent discard that deleted the checkpoints and marked the run discarded while its published adapter and catalog entry stayed on disk.
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7421558dd2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| displaced: Optional[Path] = None | ||
| if final.exists(): | ||
| displaced = root / f"{_STAGING_PREFIX}replaced-{step}-{uuid.uuid4().hex[:8]}" | ||
| os.replace(final, displaced) |
There was a problem hiding this comment.
Keep displaced branch checkpoints discoverable
When an explicit branched resume starts from an older checkpoint and later saves at a step already occupied by another retained branch (for example, resume checkpoint-10 and stop at checkpoint-15), this moves the original checkpoint-15 under .tmp-checkpoint-replaced-*. All resume scans ignore that name, and the stopped-with-save path for a same-directory resume never restores or otherwise exposes it, so the previous run immediately becomes unresumable and the hidden bundle remains indefinitely unless the new branch is later resumed and completed or discarded. Preserve the displaced branch under a discoverable unique checkpoint name or settle it when the replacement run stops successfully.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The scenario does not leave the previous run unresumable: with its own checkpoint-10 still there, its start/end fence excludes the new checkpoint-15 (written after it ended) and describe_resume_state answers checkpoint-10, verified locally.
The two remedies are also not available here. A bundle cannot be parked under another checkpoint name: read_checkpoint rejects any directory whose checkpoint-<N> disagrees with the manifest's global_step, so one step has exactly one discoverable name in this layout. And settling the displaced bundle when the replacement stops with save means deleting it, which is what _promote deliberately stopped doing: it is held precisely so a later discard of that run hands the slot back via _retire_replaced_slots(restore=True). Nor does it sit indefinitely: the next run in the directory settles it either way (fresh run clears it, a run that discards or completes restores it into the empty slot).
| cache_variants = int(getattr(cfg, "cache_variants", 0) or 0), | ||
| center_crop = _flag_key(getattr(cfg, "center_crop", None)), | ||
| random_flip = _flag_key(getattr(cfg, "random_flip", None)), | ||
| enable_tf32 = _flag_key(getattr(cfg, "enable_tf32", None)), |
There was a problem hiding this comment.
Record the effective compile mode in checkpoint identity
For DiT runs, a checkpoint created with compiled transformer blocks can currently be resumed with compile_transformer="off", or with "auto" on a host where compilation resolves differently or fails, because the identity records TF32 and effective base precision but not the effective compiled result. torch.compile may select fused kernels and different reduction order, so restoring RNG streams and optimizer moments while switching execution mode no longer provides the trajectory-preserving resume this gate is intended to enforce. Record the resolved compile result after _maybe_compile_transformer and compare it during the trainer-side preflight, using the same optional-field treatment as other post-load properties.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. _maybe_compile_transformer returns whether the compile_repeated_blocks call returned, not whether the run executed compiled code: the wrap is lazy, and it sets torch._dynamo.config.suppress_errors = True right before it, so a frame that fails to compile at the first step runs eager while the flag still reads True (documented behaviour of that config - it forces a fallback to eager instead of raising). So the field would record True on the exact host Codex names, where compilation resolves differently or fails, and could not enforce what it is being added for.
What it would do reliably is the opposite: once known on both sides, a known-vs-known difference is a hard refusal, so a bundle written on a host with triton could not be resumed on one without it, or across the auto split (_should_compile keys on device, base precision and int8) - blocking a resume over a performance optimisation. That puts it with the GPU model and the cuBLAS/cuDNN kernel choice, which also perturb reduction order and are likewise not recorded. enable_tf32 is in the identity because it is a user-set arithmetic precision mode, not a backend kernel choice.
| # Not the bundle this run resumed: something replaced the slot after the fact. | ||
| if not written or abs(written - float(source_created_at)) > 1e-6: | ||
| return None | ||
| return (candidate, manifest) |
There was a problem hiding this comment.
Fully validate source checkpoints before enabling Resume
When a resumed run fails before writing a checkpoint of its own, this fallback returns its source bundle after only read_checkpoint's structural/header validation. If that source's optimizer, scheduler, or RNG payload has since become unloadable while its header and recorded size still look valid, describe_resume_state reports can_resume: true and pins this exact path, even though the normal output-directory path deliberately applies _fully_loadable to prevent such dead Resume actions. Apply the same full-loadability gate here so an errored retry is not advertised when the start route will immediately reject it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 516c5c3. _source_checkpoint_bundle returned on read_checkpoint alone while the directory scan next to it passes usable=_fully_loadable, and both answers get pinned back to the start route verbatim, so a source whose required state or real torch.load had gone since was advertised as resumable and refused on the first click. The gate now runs on the fallback too, covering both routes into it (output dir gone, and output dir present but holding nothing inside this run's fence). Regression test test_a_source_fallback_bundle_is_held_to_the_same_load_gate reproduces it against a bundle whose header still parses, and asserts preflight_resume rejects the same path.
|
Ran the stop-at-a-checkpoint-then-resume case on a B200, since it was the one thing the PR listed as unverified. Studio installed twice from clean trees, Setup on both sides: family Z-Image, base The settings grid, identical apart from the new field. Left, The card offers Deploy to Create and Train another, and nothing else. Right, this branch, stopped at 20/60. Same folder now holds: with {"can_resume": true, "checkpoint_step": 20,
"checkpoint_path": ".../outputs/shot8163-resume/checkpoint-20"}Clicking that button is the part that mattered:
Two notes on what this does not cover. The interrupt step was wherever the poll happened to catch each run rather than a fixed number, so the two sides stopped at 32 and 20; that only affects which step the card names. And this exercises the DiT trainer on z-image, not the SDXL path. |
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |



Summary
Interrupted diffusion training cannot be resumed. Stop-and-save at step 11 wrote a partial adapter, but restarting the same configuration began a new job at step 1. The completed-run view offers Deploy to Create and no resume action.
The cause is that stop-and-save writes adapter weights only. The AdamW8bit moments, the LR-scheduler position, the RNG and sampler state and the step index all die with the training subprocess. Text training already has full resume in
core/training/resume.py, so this mirrors that pattern rather than inventing one.Reported on both Windows and Linux in an external QA pass.
Checkpoint format
<output_dir>/checkpoint-<N>/containingtrainer_state.json(the manifest, written last so it doubles as the completion marker),adapter_model.safetensors,ema_adapter.safetensors,optimizer.pt,scheduler.ptandrng_state.pt. Staged in.tmp-checkpoint-<N>-<uuid>/and promoted with a singleos.replace; an occupied slot is swapped aside and deleted only after the new bundle is in place, so a killed process never leaves a half-checkpoint that looks valid.The manifest carries
format,versionandkind("image", so a future video trainer can reuse it unchanged),global_step,target_steps,micro_step,samplerorder and position,rngstate per stream,ema_updates,optimizer_class,progress,files, and anidentityblock of family, base repo and revision, dataset fingerprint, LoRA targets, rank, alpha, precision and resolution.Adapter tensors are stored keyed by parameter name rather than in peft or diffusers export format. That is exactly the set the optimizer holds moments for, and it keeps the module free of a peft dependency.
What changed
New
core/training/diffusion_checkpoint.pyholds the writer, validator, identity gate, RNG capture and restore, and loader. One writer serves both periodic saves and stop-and-save, replacing the adapter-only writes in both trainers. Stop-and-save still produces the deployable adapter it does today, so Deploy to Create is unaffected.The validation layer is modelled on
resume.pyand rejects a mismatched family, base repo, dataset fingerprint, LoRA targets or precision, and any corrupt bundle, before evicting the resident GPU model. It sits alongside the existing precision preflight in the start route.resume_from_checkpointis added toDiffusionTrainingStartRequestandDiffusionLoraConfigand loaded before the step loop in both trainers. On resumetrain_stepsmeans the target total, so a checkpoint at 11 with a target of 500 continues at 12 and stops at 500.New API surface:
resume_from_checkpoint,resumed_from_job_id,save_steps(default 0, off) andsave_total_limit(default 2) on start;checkpoint_path,checkpoint_step,resume_blocked_reasonandresumed_from_stepon status; andoutput_dir,can_resume,checkpoint_step,checkpoint_path,resume_blocked_reason,resumed_from_job_idandresumed_from_stepon the run records.Frontend adds a Resume action to all three cards and a "Checkpoint every" field.
Also fixed while in the area: the LoRA sidecar recorded
steps: cfg.train_steps, the configured total, rather than the step actually reached.Testing
Two honest caveats on that command. It needs
--ignorefortest_mcp_server.pyandtest_rag_ocr_fallback.py, which fail to collect on a box missing pymupdf and an MCP dep and abort the whole run. The one skip istest_bitsandbytes_adamw8bit_state_round_trips:unsloth_zooinstalls a raising bitsandbytes stub that is live once the suite imports unsloth, so the test skips rather than pretending. I ran that path standalone against real bitsandbytes 0.50.0 on a B200, where the quantized state (state1,state2,qmap1/2,absmax1/2) round-trips and four further steps land bitwise identical.Full backend suite: identical failure and error counts to the pristine tree, verified by stash and rerun. Cross-platform CI green on ubuntu, macOS and Windows.
Bugs found in review and fixed
preflight_resumepicked a different bundle than the UI advertised when two runs share an output dir. The exactcheckpoint_pathis now round-tripped.KeyErrorafter GPU eviction. Now aResumeErrornaming both implementations.started_atfence plusdiscard_existingon a fresh run's first write.zlib.errorfrom a client-supplied corrupt.ptescaped as a 500.One of my own fixes nearly broke Windows: raising on
fsyncfailure would have failed every save there, since_commitneeds a write handle. It now opensO_RDWRand distinguishes real I/O failures, which fail the save, from platform refusals, which are ignored.Known gaps
base_precision: "auto"is not a hard reject on resume. Two auto runs can resolve differently from free VRAM. LoRA tensors and their moments are precision-independent, so this is a slightly different continuation rather than corruption; the resolved mode is recorded and the DiT trainer warns on mismatch. Making it a reject needs the identity to carry the resolved value, which the route cannot compute before load.range(resumed, cfg.train_steps), and everything else runs against a realnn.Linear, optimizer anddiffusers.get_schedulerthrough the same shared helpers. A real stop-at-11-then-resume on a GPU is the one thing left unverified.