Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Resume diffusion training from a stop-and-save checkpoint (#8163)

Daniel Han4e7755b7a44d
diff --git a/studio/backend/core/training/diffusion_checkpoint.py b/studio/backend/core/training/diffusion_checkpoint.py
new file mode 100644
index 00000000000..a6b666eb6f8
--- /dev/null
+++ b/studio/backend/core/training/diffusion_checkpoint.py
@@ -0,0 +1,2157 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Resumable checkpoints for diffusion (image / future video) LoRA training.
+
+A diffusion run used to write exactly one thing -- the deployable adapter -- at the very
+end, so a stop at step 11 left the AdamW moments, the LR-schedule position, the RNG
+streams and the step counter to die with the subprocess: restarting the same
+configuration began again at step 1. This module is the single writer and the single
+reader of the state that makes a run continuable.
+
+Layout, under the run's own ``output_dir`` (so the resumed run keeps writing into the
+same folder the adapter is published from)::
+
+ <output_dir>/
+ pytorch_lora_weights.safetensors <- the deployable adapter (unchanged)
+ checkpoint-11/
+ trainer_state.json <- manifest + completion marker
+ adapter_model.safetensors <- peft-format LoRA tensors
+ ema_adapter.safetensors <- the EMA shadow, when ema_decay > 0
+ optimizer.pt <- optimizer.state_dict()
+ scheduler.pt <- lr_scheduler.state_dict()
+ rng_state.pt <- torch CPU + per-device CUDA RNG states
+
+``trainer_state.json`` is written LAST inside a hidden staging directory, and the whole
+staging directory is then promoted with a single ``os.replace``. A process killed at any
+point leaves either the previous checkpoint or a ``.tmp-checkpoint-*`` directory that no
+scanner ever matches -- never a half-written ``checkpoint-<N>`` that looks valid.
+
+Identity: every bundle records the training identity it belongs to (family, base repo +
+revision, dataset fingerprint, LoRA targets/rank/alpha, precision). ``preflight_resume``
+compares that against the incoming request and refuses a mismatch with a user-facing
+reason, so the start route can reject BEFORE it evicts the resident GPU model.
+
+``kind`` ("image" today) is carried in both the manifest and the identity so a future
+video trainer can write and validate its own bundles through this same code without a
+format change: a video checkpoint simply records ``kind = "video"`` and will not be
+offered to an image run (or vice versa).
+"""
+
+from __future__ import annotations
+
+import contextlib
+import errno
+import hashlib
+import json
+import os
+import random
+import re
+import shutil
+import time
+import uuid
+from dataclasses import dataclass, replace
+from pathlib import Path
+from typing import Any, Callable, Optional, Iterable
+
+# Bumped only for a breaking layout change. A reader refuses a version it does not know.
+CHECKPOINT_FORMAT = "unsloth-diffusion-checkpoint"
+CHECKPOINT_VERSION = 1
+
+CHECKPOINT_PREFIX = "checkpoint-"
+# Hidden, and does NOT start with "checkpoint-", so neither glob("checkpoint-*") nor a user's
+# file browser mistakes a half-written bundle for a real one.
+_STAGING_PREFIX = ".tmp-checkpoint-"
+
+TRAINER_STATE_FILENAME = "trainer_state.json"
+ADAPTER_FILENAME = "adapter_model.safetensors"
+EMA_FILENAME = "ema_adapter.safetensors"
+OPTIMIZER_FILENAME = "optimizer.pt"
+SCHEDULER_FILENAME = "scheduler.pt"
+RNG_FILENAME = "rng_state.pt"
+
+# How many checkpoint-<N> bundles to keep in a run's output dir. A LoRA bundle is a few MB, but
+# a 10000-step run at save_steps=50 would otherwise leave 200 of them.
+DEFAULT_SAVE_TOTAL_LIMIT = 2
+
+
+class ResumeError(ValueError):
+ """A resume request that cannot be honoured. The message is shown to the user."""
+
+
+# ── identity ──────────────────────────────────────────────────────────────────
+# Human labels for the identity fields that HARD-REJECT a resume, in report order.
+_IDENTITY_LABELS: tuple[tuple[str, str], ...] = (
+ ("kind", "training type"),
+ ("family", "model family"),
+ ("base_model", "base model"),
+ ("base_revision", "base model revision"),
+ ("dataset_fingerprint", "training images"),
+ ("lora_target_modules", "LoRA target modules"),
+ ("lora_rank", "LoRA rank"),
+ ("lora_alpha", "LoRA alpha"),
+ ("lora_dropout", "LoRA dropout"),
+ ("cfg_dropout", "caption dropout"),
+ # The trajectory. Each of these is read from the INCOMING config by the trainer while the
+ # optimizer moments and the scheduler position come from the bundle, so changing one
+ # continues a run whose objective or learning-rate curve is no longer the one those moments
+ # were produced under -- reported as a clean continue.
+ ("flow_shift", "timestep shift"),
+ ("weighting_scheme", "loss weighting scheme"),
+ ("snr_gamma", "min-SNR gamma"),
+ ("lr_scheduler", "learning-rate schedule"),
+ ("lr_warmup_steps", "learning-rate warmup"),
+ # The input stream. Both trainers build the latent cache and the crop/flip variant plan
+ # from these BEFORE restore_resume_state puts the RNG back, so changing one continues the
+ # old optimizer and sampler against a different sequence of images.
+ ("seed", "random seed"),
+ ("cache_latents", "latent caching"),
+ ("cache_mode", "latent cache path"),
+ # The mode the LOOP actually ran in, which the request does not settle:
+ # UNSLOTH_DIFFUSION_NO_LATENT_CACHE turns it off, and an over-budget cache falls back to
+ # encoding in-loop. The two paths draw their crops and flips from different streams
+ # (variant_rng versus the loop rng), so a restored RNG state does not reproduce the run.
+ ("cache_variants", "cached crop variants"),
+ ("center_crop", "centre cropping"),
+ ("random_flip", "random flipping"),
+ # The matmul kernels. _apply_perf_flags routes CUDA matmuls through TF32 or strict fp32
+ # from this, so restoring moments produced under one into a run using the other continues
+ # the trajectory at a different numeric precision -- and off is the documented strict
+ # reproducibility mode, which a resume that silently defaults it back on undoes.
+ ("enable_tf32", "TF32 matmuls"),
+ # The update shape. The batch and accumulation counts decide how many samples each
+ # optimizer step consumes, and the clip norm is applied to the restored moments on the
+ # very next update, so all three change the trajectory the checkpoint was produced on.
+ ("train_batch_size", "batch size"),
+ ("gradient_accumulation_steps", "gradient accumulation"),
+ ("max_grad_norm", "gradient clipping"),
+ # Recorded from the beginning, but only for the UI until now. Both trainers resize and
+ # crop the incoming images to it before the restored sampler and moments see anything, so
+ # a checkpoint trained at 1024 could report a clean resume and finish at 768.
+ ("resolution", "training resolution"),
+ ("precision", "mixed precision"),
+ ("base_precision", "base precision"),
+ # What the frozen base was ACTUALLY converted to. fp8 and mxfp8 conversion can fail on the
+ # host and both fall back to bf16, so a bundle requested as fp8 records fp8 while its
+ # moments were produced against bf16 linears. Resuming that on a host where the conversion
+ # succeeds continues those moments against an fp8 base and reports a clean resume.
+ ("base_precision_effective", "resolved base precision"),
+ # The EMA coefficient. restore_resume_state loads the old shadow tensors and update count
+ # while the trainer builds LoRAEMA from the INCOMING decay, so every later update applies a
+ # new coefficient to an average produced under the old one and the exported EMA adapter is a
+ # hybrid -- reported as a faithful continuation.
+ ("ema_decay", "EMA decay"),
+)
+# Fields whose value can legitimately be unknown on one side (an uncached Hub repo has no
+# resolvable revision; the start route knows the dataset only after its own discovery pass).
+# Unknown on either side means "cannot tell", which must not be reported as a mismatch.
+_OPTIONAL_IDENTITY_FIELDS = frozenset(
+ {
+ "base_revision",
+ "dataset_fingerprint",
+ "lora_dropout",
+ "cfg_dropout",
+ # Absent only in a manifest written before these were recorded, which reads as
+ # "cannot tell" rather than as a mismatch.
+ "ema_decay",
+ "flow_shift",
+ "weighting_scheme",
+ "snr_gamma",
+ "lr_scheduler",
+ "lr_warmup_steps",
+ "seed",
+ "cache_latents",
+ "cache_mode",
+ "cache_variants",
+ "center_crop",
+ "random_flip",
+ "enable_tf32",
+ "train_batch_size",
+ "gradient_accumulation_steps",
+ "max_grad_norm",
+ # Known only inside the trainer, and only for the DiT path. Unknown on either side
+ # reads as "cannot tell", which is what keeps the route's pre-eviction preflight and
+ # the SDXL trainer unaffected.
+ "base_precision_effective",
+ }
+)
+# What source_revision() returns when it cannot resolve a revision offline.
+_UNRESOLVED_REVISION = "unresolved"
+
+
+def _revision_is_comparable(value: Any) -> bool:
+ """Only a real Hub commit (``rev-<sha>``) is a hard identity for the base model.
+
+ ``source_revision`` also returns a ``dir-<hash>`` built from the file SIZES AND MTIMES of a
+ LOCAL base directory. That is the right key for a conditioning cache, but far too brittle for
+ a resume gate: re-downloading, re-quantizing, or merely touching the local base changes it
+ while the weights are the same, and the user would get an unactionable
+ "different base model revision (dir-abc vs dir-def)" refusal. Compare Hub revisions, treat a
+ local directory's marker as advisory."""
+ return isinstance(value, str) and value.startswith("rev-")
+
+
+@dataclass(frozen = True)
+class CheckpointIdentity:
+ """What a checkpoint was trained as. Two bundles are interchangeable only when every
+ field here agrees, so resuming can never continue a FLUX run into an SDXL adapter, or
+ feed rank-16 moments to a rank-32 optimizer.
+
+ ``base_revision`` and ``dataset_fingerprint`` are optional: the first is resolved from
+ the local Hub cache and reads ``unresolved`` when the repo has not been fetched yet, the
+ second is only known once the dataset has been walked. Either being unknown skips that
+ comparison rather than failing it."""
+
+ family: str
+ base_model: str
+ lora_target_modules: tuple[str, ...]
+ lora_rank: int
+ lora_alpha: int
+ precision: str
+ base_precision: str
+ resolution: int
+ kind: str = "image"
+ base_revision: Optional[str] = None
+ dataset_fingerprint: Optional[str] = None
+ lora_dropout: Optional[float] = None
+ # Caption (classifier-free-guidance) dropout. The DiT loop asks rng.random() once per
+ # sample when it is above zero and swaps in the empty prompt on a hit, so changing it
+ # across a resume diverges the restored RNG stream on the very next step AND changes the
+ # objective, while the run reports a clean continue. A bundle from before this field
+ # existed reads None, which the optional rule skips rather than reporting as a mismatch.
+ cfg_dropout: Optional[float] = None
+ # Trajectory-defining knobs, all optional for the same reason: a bundle from before they
+ # were recorded reads unknown, not mismatched.
+ flow_shift: Optional[str] = None
+ weighting_scheme: Optional[str] = None
+ # Text, not a float: None is the documented way to DISABLE min-SNR, so a float field could
+ # not tell "trained with it off" from "written before the field existed" -- and the optional
+ # rule would skip the comparison for both. "off" is the disabled value; None is absence.
+ snr_gamma: Optional[str] = None
+ lr_scheduler: Optional[str] = None
+ lr_warmup_steps: Optional[int] = None
+ seed: Optional[int] = None
+ # Booleans as text ("on"/"off") for the same reason snr_gamma is: False is a real value and
+ # None has to stay reserved for a manifest that predates the field.
+ cache_latents: Optional[str] = None
+ # Resolved, not requested, and known only inside the trainer -- the start route leaves it
+ # None, which the optional rule reads as "cannot tell" so the pre-eviction preflight is
+ # unaffected. The trainer's own preflight, which runs with the real value, is where a
+ # mismatched cache path is caught.
+ cache_mode: Optional[str] = None
+ cache_variants: Optional[int] = None
+ center_crop: Optional[str] = None
+ random_flip: Optional[str] = None
+ enable_tf32: Optional[str] = None
+ train_batch_size: Optional[int] = None
+ gradient_accumulation_steps: Optional[int] = None
+ # Text, so 0.0 (clipping disabled) is a value and None stays "not recorded".
+ max_grad_norm: Optional[str] = None
+ # Text for the same reason: 0.0 means EMA is off, which is a real setting, and None has to
+ # stay reserved for a manifest that predates the field.
+ ema_decay: Optional[str] = None
+ # Post-conversion, set by the DiT trainer once it knows whether fp8/mxfp8 took. None
+ # everywhere else, which the optional rule reads as "cannot tell".
+ base_precision_effective: Optional[str] = None
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "kind": self.kind,
+ "family": self.family,
+ "base_model": self.base_model,
+ "base_revision": self.base_revision,
+ "dataset_fingerprint": self.dataset_fingerprint,
+ "lora_target_modules": list(self.lora_target_modules),
+ "lora_rank": int(self.lora_rank),
+ "lora_alpha": int(self.lora_alpha),
+ # Both trainers pass this to the LoRA constructor, so it changes the stochastic
+ # forward pass the restored optimizer moments were produced against. Written as a
+ # rounded float: a manifest from before this field existed reads as None, which the
+ # optional-field rule below skips rather than reporting as a mismatch.
+ "lora_dropout": self.lora_dropout,
+ "cfg_dropout": self.cfg_dropout,
+ "flow_shift": self.flow_shift,
+ "weighting_scheme": self.weighting_scheme,
+ "snr_gamma": self.snr_gamma,
+ "lr_scheduler": self.lr_scheduler,
+ "lr_warmup_steps": self.lr_warmup_steps,
+ "seed": self.seed,
+ "cache_latents": self.cache_latents,
+ "cache_mode": self.cache_mode,
+ "cache_variants": self.cache_variants,
+ "center_crop": self.center_crop,
+ "random_flip": self.random_flip,
+ "enable_tf32": self.enable_tf32,
+ "train_batch_size": self.train_batch_size,
+ "gradient_accumulation_steps": self.gradient_accumulation_steps,
+ "max_grad_norm": self.max_grad_norm,
+ "ema_decay": self.ema_decay,
+ "base_precision_effective": self.base_precision_effective,
+ "precision": self.precision,
+ "base_precision": self.base_precision,
+ # A hard identity field, not just a label: both trainers resize and crop the
+ # incoming images to it before the restored sampler and moments see anything, so a
+ # bundle trained at 1024 could report a clean resume and finish at 768. Loadable
+ # tensors are not a faithful resume.
+ "resolution": int(self.resolution),
+ }
+
+ @classmethod
+ def from_dict(cls, data: Any) -> Optional["CheckpointIdentity"]:
+ """Rebuild an identity from a manifest. Returns None for anything unreadable, so a
+ hand-edited or truncated record reads as "no identity" instead of raising."""
+ if not isinstance(data, dict):
+ return None
+ try:
+ targets = data.get("lora_target_modules") or []
+ if not isinstance(targets, (list, tuple)):
+ return None
+ return cls(
+ family = str(data.get("family") or ""),
+ base_model = str(data.get("base_model") or ""),
+ lora_target_modules = tuple(str(t) for t in targets),
+ lora_rank = int(data.get("lora_rank") or 0),
+ lora_alpha = int(data.get("lora_alpha") or 0),
+ lora_dropout = _optional_float(data.get("lora_dropout")),
+ cfg_dropout = _optional_float(data.get("cfg_dropout")),
+ flow_shift = _optional_str(data.get("flow_shift")),
+ weighting_scheme = _optional_str(data.get("weighting_scheme")),
+ snr_gamma = _optional_str(data.get("snr_gamma")),
+ lr_scheduler = _optional_str(data.get("lr_scheduler")),
+ lr_warmup_steps = _optional_int(data.get("lr_warmup_steps")),
+ seed = _optional_int(data.get("seed")),
+ cache_latents = _optional_str(data.get("cache_latents")),
+ cache_mode = _optional_str(data.get("cache_mode")),
+ cache_variants = _optional_int(data.get("cache_variants")),
+ center_crop = _optional_str(data.get("center_crop")),
+ random_flip = _optional_str(data.get("random_flip")),
+ enable_tf32 = _optional_str(data.get("enable_tf32")),
+ train_batch_size = _optional_int(data.get("train_batch_size")),
+ gradient_accumulation_steps = _optional_int(data.get("gradient_accumulation_steps")),
+ max_grad_norm = _optional_str(data.get("max_grad_norm")),
+ ema_decay = _optional_str(data.get("ema_decay")),
+ base_precision_effective = _optional_str(data.get("base_precision_effective")),
+ precision = str(data.get("precision") or ""),
+ base_precision = str(data.get("base_precision") or ""),
+ resolution = int(data.get("resolution") or 0),
+ kind = str(data.get("kind") or "image"),
+ base_revision = _optional_str(data.get("base_revision")),
+ dataset_fingerprint = _optional_str(data.get("dataset_fingerprint")),
+ )
+ except (TypeError, ValueError):
+ return None
+
+ def with_dataset(self, fingerprint: Optional[str]) -> "CheckpointIdentity":
+ """A copy carrying the dataset fingerprint, filled in once the images are known."""
+ return replace(self, dataset_fingerprint = fingerprint)
+
+ def mismatch_reason(self, other: "CheckpointIdentity") -> Optional[str]:
+ """Why ``other`` (the incoming request) cannot continue ``self`` (the checkpoint),
+ or None when they are compatible. Reports the FIRST difference so the message names
+ one concrete thing to change."""
+ mine, theirs = self.as_dict(), other.as_dict()
+ for field, label in _IDENTITY_LABELS:
+ a, b = mine.get(field), theirs.get(field)
+ # None / "" is "cannot tell". NOT falsiness: a lora_dropout of 0.0 is a real value
+ # and the commonest one, so truthiness would skip exactly the comparison that
+ # matters -- 0.0 against 0.15.
+ if field in _OPTIONAL_IDENTITY_FIELDS and (a in (None, "") or b in (None, "")):
+ continue
+ if field == "base_revision" and not (
+ _revision_is_comparable(a) and _revision_is_comparable(b)
+ ):
+ continue
+ if a == b:
+ continue
+ if field == "dataset_fingerprint":
+ return (
+ "The training images have changed since this checkpoint was written, so "
+ "the run cannot continue from it. Restore the original dataset, or start "
+ "a new run."
+ )
+ return (
+ f"This checkpoint was trained with a different {label} "
+ f"({_render(a)} vs {_render(b)}), so it cannot be resumed into this run."
+ )
+ return None
+
+
+def _optional_str(value: Any) -> Optional[str]:
+ if value is None:
+ return None
+ text = str(value).strip()
+ return text or None
+
+
+def _optional_float(value: Any) -> Optional[float]:
+ """A rounded float, or None for anything unreadable (including a manifest that predates
+ the field). None is the "cannot tell" the optional-field rule skips."""
+ if value is None:
+ return None
+ try:
+ return round(float(value), 6)
+ except (TypeError, ValueError):
+ return None
+
+
+def _snr_gamma_key(value: Any) -> str:
+ """min-SNR as a comparable token. None DISABLES the weighting, so it gets its own value
+ rather than the unknown the optional-field rule skips."""
+ number = _optional_float(value)
+ return "off" if number is None else f"{number}"
+
+
+def _flag_key(value: Any) -> Optional[str]:
+ """A boolean as a comparable token, so False is a value and None stays "not recorded"."""
+ if value is None:
+ return None
+ return "on" if bool(value) else "off"
+
+
+def _optional_int(value: Any) -> Optional[int]:
+ """An int, or None for anything unreadable. Same "cannot tell" as _optional_float."""
+ if value is None or isinstance(value, bool):
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _render(value: Any) -> str:
+ if isinstance(value, list):
+ return ", ".join(str(v) for v in value) or "none"
+ return str(value) if value not in (None, "") else "unset"
+
+
+def dataset_fingerprint(pairs: Any) -> str:
+ """A stable content marker for the (image, caption) pairs a run trains on.
+
+ Built from each image's FILE NAME, byte size and resolved caption, sorted, so it is
+ invariant to the dataset folder being moved or re-imported under a different root
+ (which the run config already records) while still catching an added, removed,
+ re-captioned or replaced image. Never raises: an unstatable file contributes ``?``
+ rather than failing a preflight."""
+ parts: list[str] = []
+ for entry in pairs or ():
+ try:
+ path, caption = entry[0], entry[1]
+ except (IndexError, KeyError, TypeError):
+ continue
+ parts.append(f"{Path(str(path)).name}:{_content_probe(path)}:{caption}")
+ digest = hashlib.sha256("|".join(sorted(parts)).encode("utf-8", "replace")).hexdigest()
+ return f"ds-{len(parts)}-{digest[:24]}"
+
+
+# Enough of each file to tell two images apart, without reading a multi-gigabyte dataset on a
+# preflight that runs before the resident GPU model is evicted.
+_PROBE_BYTES = 65536
+
+
+def _content_probe(path: Any) -> str:
+ """``size-digest`` for one dataset file, or ``?`` when it cannot be read.
+
+ Size alone let an image be overwritten IN PLACE with different content of exactly the same
+ length -- same filename, same caption -- and the preflight accepted the dataset, so the
+ restored optimizer and scheduler carried on an old experiment against different images.
+
+ The head and tail rather than the whole file: hashing every image would make this scale with
+ the dataset, and two different images agreeing on their first and last 64 KiB as well as
+ their exact byte length is not a case that arises from editing a dataset. It is not a
+ tamper-proof digest and does not need to be."""
+ try:
+ size = os.path.getsize(path)
+ digest = hashlib.sha256()
+ with open(path, "rb") as handle:
+ digest.update(handle.read(_PROBE_BYTES))
+ if size > _PROBE_BYTES:
+ # Every byte past the head is covered, either as the tail sample or, for a file
+ # under 2x the probe, in full. The old `> 2 * _PROBE_BYTES` gate left a band
+ # (64 KiB to 128 KiB, which is most JPEGs) reading its first 64 KiB and nothing
+ # else, so a same-length replacement sharing a head went unnoticed.
+ handle.seek(max(_PROBE_BYTES, size - _PROBE_BYTES))
+ digest.update(handle.read(_PROBE_BYTES))
+ # ValueError: open() rejects an embedded NUL rather than raising OSError.
+ except (OSError, ValueError):
+ return "?"
+ return f"{size}-{digest.hexdigest()[:16]}"
+
+
+def _resolve_lora_targets(cfg: Any) -> tuple[str, ...]:
+ """The LoRA target modules the trainer will actually attach for ``cfg``.
+
+ A DiT family replaces the generic attention default with its own projections
+ (``_select_lora_targets``), so the identity must resolve the same tuple the trainer
+ will; otherwise the start route would compute a different fingerprint from the run and
+ every resume would look like a mismatch. Imported lazily -- the DiT trainer imports this
+ module at load time, so the reverse edge has to be deferred."""
+ configured = tuple(cfg.lora_target_modules)
+ if str(getattr(cfg, "resolved_family", "") or "").strip().lower() == "sdxl":
+ return configured
+ # Deliberately NOT wrapped in a try/except: quietly falling back to the generic tuple would
+ # make the route compute a different fingerprint from the trainer, its preflight would pass,
+ # and the mismatch would surface in the child AFTER the GPU residents were freed.
+ from core.training.diffusion_dit_trainer import _SPECS, _select_lora_targets
+
+ spec = _SPECS.get(cfg.resolved_family)
+ if spec is None:
+ return configured
+ return tuple(_select_lora_targets(configured, spec.lora_targets))
+
+
+def with_cache_mode(identity: "CheckpointIdentity", used_cache: bool) -> "CheckpointIdentity":
+ """Record the latent-cache path the loop ACTUALLY took.
+
+ The config only carries the request. The environment override and the over-budget fallback
+ can both turn it off, and the cached and uncached paths consume different RNG streams for
+ crops and flips, so a bundle written on one and resumed on the other restores a state that
+ no longer reproduces the training stream."""
+ return replace(identity, cache_mode = "cached" if used_cache else "in-loop")
+
+
+def with_resolved_base_precision(
+ identity: "CheckpointIdentity", resolved: Any
+) -> "CheckpointIdentity":
+ """Record the base precision the transformer was ACTUALLY converted to.
+
+ The config carries the request, and "auto" is not even a precision. Worse, fp8 and mxfp8
+ conversion can fail on the host and both fall back to bf16 with only a warning in progress,
+ so a bundle requested as fp8 recorded fp8 while its optimizer moments were produced against
+ bf16 linears. A later resume on a host where the conversion does take then restores those
+ moments onto an fp8 frozen base and calls it a clean continue."""
+ value = str(resolved or "").strip().lower()
+ if not value:
+ return identity # nothing resolved; leave it unknown rather than asserting a value
+ return replace(identity, base_precision_effective = value)
+
+
+def with_resolved_revision(identity: "CheckpointIdentity", base_model: Any) -> "CheckpointIdentity":
+ """``identity`` with its base revision re-read now that the base model is on disk.
+
+ The identity is built BEFORE the multi-GB load, deliberately -- a mismatched resume should
+ fail in seconds, not after a download. But on the first run of an uncached Hub repo there is
+ no local ref to read, so the revision records "unresolved" and the bundle it goes into can
+ never enforce which commit it was trained on. Re-read once the loader has populated the
+ cache: an unresolved value is not comparable, so a repo that could not be read keeps
+ whatever was recorded, and a later resume against a repo that has advanced is refused
+ instead of quietly restoring the adapter and the Adam moments onto different frozen base
+ weights.
+
+ The re-read is unconditional. A local ``refs/main`` can still report the OLD commit before
+ the load and be refreshed by ``from_pretrained`` itself, so returning early on an
+ already-comparable value left the pre-load revision standing for a base that had since
+ advanced -- the resume then compared A against A and restored A's adapter and moments onto
+ B's frozen weights, which is the exact outcome this field exists to prevent.
+ """
+ from core.training.diffusion_train_extras import source_revision
+
+ resolved = source_revision(base_model)
+ if not _revision_is_comparable(resolved) or resolved == identity.base_revision:
+ return identity
+ return replace(identity, base_revision = resolved)
+
+
+def identity_for_config(
+ cfg: Any,
+ *,
+ dataset_pairs: Any = None,
+ resolved_targets: Optional[tuple[str, ...]] = None,
+ kind: str = "image",
+) -> CheckpointIdentity:
+ """The identity a run with ``cfg`` would produce.
+
+ ``resolved_targets`` is the LoRA target tuple the trainer will actually attach; pass it
+ where it is already known (the DiT trainer holds its family spec), otherwise it is
+ resolved here the same way, so the start route and the trainer always agree.
+ ``base_precision`` is the REQUESTED mode, not the one ``auto`` resolves to at load time
+ -- the start route has to compute the same identity before anything is loaded."""
+ from core.training.diffusion_train_common import effective_mixed_precision
+ from core.training.diffusion_train_extras import source_revision
+
+ targets = tuple(resolved_targets) if resolved_targets else _resolve_lora_targets(cfg)
+ return CheckpointIdentity(
+ family = str(getattr(cfg, "resolved_family", "") or ""),
+ base_model = str(cfg.base_model or ""),
+ lora_target_modules = targets,
+ lora_rank = int(cfg.lora_rank),
+ lora_alpha = int(cfg.lora_alpha if cfg.lora_alpha is not None else cfg.lora_rank),
+ lora_dropout = round(float(getattr(cfg, "lora_dropout", 0.0) or 0.0), 6),
+ cfg_dropout = round(float(getattr(cfg, "cfg_dropout", 0.0) or 0.0), 6),
+ # flow_shift is float | "auto" | None, so it is recorded as text: "auto" and the number
+ # it resolves to are different runs, and comparing them as floats would lose that.
+ flow_shift = str(getattr(cfg, "flow_shift", None)),
+ weighting_scheme = str(getattr(cfg, "weighting_scheme", "") or "none"),
+ snr_gamma = _snr_gamma_key(getattr(cfg, "snr_gamma", None)),
+ lr_scheduler = str(getattr(cfg, "lr_scheduler", "") or "constant"),
+ lr_warmup_steps = int(getattr(cfg, "lr_warmup_steps", 0) or 0),
+ seed = int(getattr(cfg, "seed", 0) or 0),
+ cache_latents = _flag_key(getattr(cfg, "cache_latents", None)),
+ 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)),
+ train_batch_size = int(getattr(cfg, "train_batch_size", 0) or 0),
+ gradient_accumulation_steps = int(getattr(cfg, "gradient_accumulation_steps", 0) or 0),
+ max_grad_norm = f"{round(float(getattr(cfg, 'max_grad_norm', 0.0) or 0.0), 6)}",
+ ema_decay = f"{round(float(getattr(cfg, 'ema_decay', 0.0) or 0.0), 6)}",
+ # The EFFECTIVE precision, not the request: a pre-Ampere card resolves bf16 to fp16, and
+ # recording the request let an fp16 bundle resume in bf16 on a newer card -- restored
+ # moments continuing under different frozen-base numerics, reported as a clean resume.
+ precision = effective_mixed_precision(cfg),
+ base_precision = str(getattr(cfg, "base_precision", "") or ""),
+ resolution = int(cfg.resolution),
+ kind = kind,
+ base_revision = source_revision(cfg.base_model),
+ dataset_fingerprint = dataset_fingerprint(dataset_pairs) if dataset_pairs else None,
+ )
+
+
+# ── RNG capture / restore ─────────────────────────────────────────────────────
+def capture_rng_state(streams: Optional[dict[str, Any]] = None) -> dict[str, Any]:
+ """Snapshot every random stream a diffusion run draws from.
+
+ ``streams`` maps a name to a ``random.Random`` instance the trainer owns (the loop's
+ index/crop stream and the latent-cache variant stream are separate objects, so the
+ module-level ``random`` state does not cover them). Returns
+ ``{"json": <JSON-safe dict>, "tensors": <torch tensors>}``; the caller writes the first
+ into the manifest and the second into ``rng_state.pt``. Never raises."""
+ payload: dict[str, Any] = {
+ "python": _random_state_to_json(random.getstate()),
+ "streams": {},
+ "numpy": None,
+ }
+ for name, stream in (streams or {}).items():
+ try:
+ payload["streams"][str(name)] = _random_state_to_json(stream.getstate())
+ except Exception: # noqa: BLE001 -- a stream we cannot read simply is not restored
+ continue
+ try:
+ import numpy as np
+ kind, keys, pos, has_gauss, cached = np.random.get_state()
+ payload["numpy"] = {
+ "bit_generator": str(kind),
+ "keys": [int(k) for k in keys],
+ "pos": int(pos),
+ "has_gauss": int(has_gauss),
+ "cached_gaussian": float(cached),
+ }
+ except Exception: # noqa: BLE001 -- no numpy / a non-MT19937 global generator
+ payload["numpy"] = None
+
+ tensors: dict[str, Any] = {}
+ try:
+ import torch
+ tensors["torch_cpu"] = torch.get_rng_state()
+ if torch.cuda.is_available():
+ try:
+ for i, state in enumerate(torch.cuda.get_rng_state_all()):
+ tensors[f"torch_cuda_{i}"] = state
+ except Exception: # noqa: BLE001 -- one device erroring loses the whole capture
+ # ALL OR NOTHING on a CUDA host. Keeping the CPU half made the result non-empty,
+ # so the write-time check accepted it and the preflight (which only requires
+ # torch_cpu) offered it -- and the restore then left the CUDA generator at its
+ # freshly seeded position, silently changing every latent, noise and timestep
+ # draw from the resumed step on. An empty result fails the write instead.
+ tensors = {}
+ except Exception: # noqa: BLE001 -- torch RNG capture is best-effort
+ tensors = {}
+ return {"json": payload, "tensors": tensors}
+
+
+def restore_rng_state(
+ payload: Optional[dict[str, Any]],
+ tensors: Optional[dict[str, Any]] = None,
+ streams: Optional[dict[str, Any]] = None,
+) -> None:
+ """Undo ``capture_rng_state``. Every part is independent and best-effort: a checkpoint
+ written on a 2-GPU box restored on a 1-GPU box still restores everything else."""
+ payload = payload or {}
+ state = _random_state_from_json(payload.get("python"))
+ if state is not None:
+ try:
+ random.setstate(state)
+ except (TypeError, ValueError):
+ pass
+ saved_streams = payload.get("streams")
+ if isinstance(saved_streams, dict):
+ for name, stream in (streams or {}).items():
+ got = _random_state_from_json(saved_streams.get(str(name)))
+ if got is None:
+ continue
+ try:
+ stream.setstate(got)
+ except (TypeError, ValueError):
+ continue
+ np_state = payload.get("numpy")
+ if isinstance(np_state, dict):
+ try:
+ import numpy as np
+ np.random.set_state(
+ (
+ str(np_state.get("bit_generator") or "MT19937"),
+ np.array(np_state.get("keys") or [], dtype = np.uint32),
+ int(np_state.get("pos") or 0),
+ int(np_state.get("has_gauss") or 0),
+ float(np_state.get("cached_gaussian") or 0.0),
+ )
+ )
+ except Exception: # noqa: BLE001 -- no numpy, or an incompatible generator
+ pass
+ if not tensors:
+ return
+ try:
+ import torch
+
+ cpu = tensors.get("torch_cpu")
+ if cpu is not None:
+ torch.set_rng_state(cpu.cpu().to(torch.uint8))
+ if torch.cuda.is_available():
+ # Per device, not set_rng_state_all. That call needs one state per visible
+ # device, so covering it with an all-or-nothing guard meant a bundle written
+ # with fewer devices visible than the resume sees restored NOTHING -- including
+ # cuda:0, the only device training touches. The whole per-step noise stream
+ # (randn_like for the latent and the noise, randint for the timestep) then
+ # restarted at the wrong offset while every other part of the resume looked
+ # correct, so the run finished healthy and silently wrong: measured on a real
+ # B200 SDXL run, 192/192 LoRA tensors differed from the uninterrupted control
+ # and the first step after the resume was off by 0.024. The exposure is
+ # ordinary -- 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. Restoring device by device covers whatever the bundle
+ # holds and leaves the rest alone, and is identical to the old behaviour when
+ # the counts match (verified bit-exact against the same control).
+ for i in range(torch.cuda.device_count()):
+ state = tensors.get(f"torch_cuda_{i}")
+ if state is None:
+ continue
+ torch.cuda.set_rng_state(state.cpu().to(torch.uint8), i)
+ except Exception: # noqa: BLE001 -- best-effort restore, never fatal
+ pass
+
+
+def _random_state_to_json(state: Any) -> Optional[list[Any]]:
+ """``random.Random.getstate()`` is ``(version, tuple[int, ...], gauss)``; JSON has no
+ tuples, so store it as nested lists."""
+ try:
+ version, keys, gauss = state
+ return [int(version), [int(k) for k in keys], gauss]
+ except (TypeError, ValueError):
+ return None
+
+
+def _random_state_from_json(value: Any) -> Optional[tuple]:
+ if not isinstance(value, (list, tuple)) or len(value) != 3:
+ return None
+ try:
+ return (int(value[0]), tuple(int(k) for k in value[1]), value[2])
+ except (TypeError, ValueError):
+ return None
+
+
+# ── writing ───────────────────────────────────────────────────────────────────
+def save_checkpoint(
+ *,
+ output_dir: str | os.PathLike[str],
+ step: int,
+ adapter_state: dict[str, Any],
+ identity: CheckpointIdentity,
+ target_steps: int,
+ optimizer: Any = None,
+ lr_scheduler: Any = None,
+ ema_state: Optional[dict[str, Any]] = None,
+ ema_updates: int = 0,
+ rng: Optional[dict[str, Any]] = None,
+ sampler_state: Optional[dict[str, Any]] = None,
+ progress: Optional[dict[str, Any]] = None,
+ save_total_limit: int = DEFAULT_SAVE_TOTAL_LIMIT,
+ discard_existing: bool = False,
+ source_checkpoint: Optional[str | os.PathLike[str]] = None,
+ preexisting: "Optional[Iterable[Any]]" = None,
+) -> str:
+ """Write one resumable ``checkpoint-<step>`` bundle and return its path.
+
+ The ONE writer: periodic saves (``cfg.save_steps``) and stop-and-save both come through
+ here, so a stopped run and a crashed-then-restarted run resume from byte-identical
+ state. Everything lands in a hidden staging directory whose manifest is written last;
+ the directory is then promoted with a single ``os.replace``, so a kill at any instant
+ leaves the previous checkpoint intact and no valid-looking partial behind.
+
+ ``source_checkpoint`` is the bundle this run resumed FROM, when it resumed. It is what
+ makes the "this step is already written" shortcut below safe: without it, a stop at a
+ step some OTHER run happens to have written would silently keep that run's state.
+
+ ``discard_existing`` drops any bundle already in the directory first. A run that did NOT
+ resume owns its output dir outright (it overwrites the published adapter there too), so
+ checkpoints left by an EARLIER run of the same adapter name must go: they would otherwise
+ outrank the new run's lower-numbered ones and a later Resume would silently continue the
+ wrong training.
+
+ Raises OSError / ValueError / RuntimeError on a real write failure -- callers treat that
+ as "this run cannot be resumed" and surface it, rather than failing the training."""
+ import torch
+ from safetensors.torch import save_file
+
+ step = int(step)
+ if step < 0:
+ raise ValueError("checkpoint step must be >= 0")
+ if not adapter_state:
+ # An empty safetensors file has no keys, so the bundle would fail its own validation and
+ # read as "no checkpoint" -- a silent un-resumable run. Fail loudly at write time instead.
+ raise ValueError("refusing to write a checkpoint with no adapter tensors")
+ root = Path(output_dir).expanduser()
+ root.mkdir(parents = True, exist_ok = True)
+ doomed: list[Path] = []
+ if discard_existing:
+ # Recorded now, deleted AFTER the new bundle is promoted. Clearing first means a kill or
+ # an I/O failure mid-write leaves the directory with no checkpoint at all -- and any
+ # earlier run sharing the folder has irreversibly lost its own, which is the opposite of
+ # what this writer promises.
+ doomed = list_checkpoints(root)
+ else:
+ # Re-reaching a step that already has a VALID bundle happens one way SAFELY: the run
+ # resumed at N and stopped before N+1 completed, so its state is byte-identical to what
+ # is already there, and keeping it avoids the one destructive branch in _promote
+ # (swapping a good bundle out to make room), where a kill would leave the slot empty.
+ #
+ # It has to be THAT bundle, though. Resuming checkpoint-10 in a folder that also holds
+ # checkpoint-15 and stopping at 15 is the same arithmetic and a completely different
+ # situation: the freshly trained optimizer, scheduler, sampler and RNG would be dropped
+ # on the floor and checkpoint_saved would name a bundle from an earlier run.
+ existing = root / f"{CHECKPOINT_PREFIX}{step}"
+ if (
+ source_checkpoint is not None
+ and Path(source_checkpoint).expanduser().resolve() == existing.resolve()
+ and read_checkpoint(existing) is not None
+ ):
+ return str(existing)
+ staging = root / f"{_STAGING_PREFIX}{step}-{uuid.uuid4().hex[:8]}"
+ staging.mkdir(parents = True, exist_ok = False)
+
+ try:
+ _save_tensors(save_file, adapter_state, staging / ADAPTER_FILENAME)
+ files = {"adapter": ADAPTER_FILENAME}
+ optimizer_class: Optional[str] = None
+ optimizer_param_names: Optional[list[str]] = None
+ if ema_state:
+ _save_tensors(save_file, ema_state, staging / EMA_FILENAME)
+ files["ema"] = EMA_FILENAME
+ if optimizer is not None:
+ # torch.save, not safetensors: an optimizer state dict is a nested structure of
+ # tensors AND scalars (bitsandbytes AdamW8bit additionally carries uint8 moments
+ # plus their quantization maps), which safetensors cannot express.
+ _torch_save(torch, optimizer.state_dict(), staging / OPTIMIZER_FILENAME)
+ files["optimizer"] = OPTIMIZER_FILENAME
+ optimizer_class = optimizer_key(optimizer)
+ # `adapter_state` is trainable_state_dict(model), i.e. named_parameters() order --
+ # the same traversal the trainers build their param list from, so its key order IS
+ # the optimizer's positional order.
+ optimizer_param_names = [str(name) for name in adapter_state]
+ if lr_scheduler is not None:
+ _torch_save(torch, lr_scheduler.state_dict(), staging / SCHEDULER_FILENAME)
+ files["scheduler"] = SCHEDULER_FILENAME
+ rng_json: Optional[dict[str, Any]] = None
+ if rng:
+ rng_json = rng.get("json")
+ rng_tensors = rng.get("tensors") or {}
+ if not rng_tensors:
+ # capture_rng_state never raises -- it returns what it managed to read -- so a
+ # torch generator it could not snapshot produced a bundle with no rng file at
+ # all. save_checkpoint returned happily, the service emitted checkpoint_saved,
+ # and the history advertised a resumable stop that _assert_required_state then
+ # refuses the moment the user clicks Resume. Fail the WRITE instead, which the
+ # caller reports as resume_blocked_reason.
+ raise RuntimeError(
+ "the run's random-number state could not be captured, so this checkpoint "
+ "would not be resumable"
+ )
+ _torch_save(torch, rng_tensors, staging / RNG_FILENAME)
+ files["rng"] = RNG_FILENAME
+
+ manifest: dict[str, Any] = {
+ "format": CHECKPOINT_FORMAT,
+ "version": CHECKPOINT_VERSION,
+ "kind": identity.kind,
+ "global_step": step,
+ "target_steps": int(target_steps),
+ # Checkpoints are only ever taken on an optimizer-step boundary, so the
+ # gradient-accumulation position is always clean. Recorded explicitly so a future
+ # mid-accumulation checkpoint is a value change, not a format change.
+ "micro_step": 0,
+ "created_at": time.time(),
+ "identity": identity.as_dict(),
+ "sampler": sampler_state or None,
+ "rng": rng_json,
+ "ema_updates": int(ema_updates),
+ # Which optimizer wrote the moments. bitsandbytes AdamW8bit stores "state1"/"state2",
+ # torch AdamW stores "exp_avg"/"exp_avg_sq", and the trainers pick between them from
+ # the host (bnb present, fused kernel available, UNSLOTH_DIFFUSION_FP32_OPTIM). Both
+ # accept the other's state_dict and then KeyError on the first step, so the resume
+ # has to compare this instead.
+ "optimizer_class": optimizer_class,
+ # The trainable parameter names in the order the optimizer holds them. Its state is
+ # keyed by POSITION, so a PEFT/diffusers upgrade that changes traversal order while
+ # keeping the same names would rebind every Adam moment to a different tensor --
+ # and many LoRA projections share a shape, so it loads cleanly and silently corrupts
+ # the continued trajectory. Additive: an older bundle has no list and skips the
+ # check rather than failing it.
+ "optimizer_param_names": optimizer_param_names,
+ # Loop bookkeeping that is not state to restore into an object (running loss, wall
+ # clock). Nested rather than merged, so a caller can never shadow a reserved key.
+ "progress": dict(progress or {}),
+ "files": files,
+ # Byte size per listed file, so read_checkpoint can catch a truncation the
+ # header parse structurally cannot. _valid_state_file walks a torch zip's pickle
+ # to STOP and requires one non-empty data/ member; truncating the tensor storages
+ # themselves leaves both intact, and torch.load then returns UNINITIALIZED memory
+ # -- measured at +/-1e22 and non-finite -- which a resume feeds straight into the
+ # optimizer as Adam moments. The run diverges on its first step while reporting a
+ # clean resume. This is free to write and free to check.
+ #
+ # Additive on purpose: an older bundle has no sizes and skips the check rather
+ # than failing it, and an older build ignores the key, so no version bump.
+ "file_sizes": _file_sizes(staging, files),
+ }
+ # LAST: the manifest is the completion marker, so nothing may be written after it.
+ _write_text(staging / TRAINER_STATE_FILENAME, json.dumps(manifest, indent = 2))
+ _fsync_dir(staging)
+ final = _promote(staging, root, step)
+ except BaseException:
+ shutil.rmtree(staging, ignore_errors = True)
+ raise
+ for stale in doomed:
+ # `final` can be one of these when the new step reuses an existing bundle's name;
+ # _promote already replaced it, so removing it here would delete the new checkpoint.
+ if stale != final:
+ shutil.rmtree(stale, ignore_errors = True)
+ _prune_staging(root)
+ # The source bundle is pinned as well as the one just written. A resumed run writes into
+ # the directory it resumed FROM, so with keep=2 a run that resumes checkpoint-10 and saves
+ # 20 and 30 prunes 10 -- and "stop without saving" then removes only what this run wrote,
+ # leaving the ORIGINAL stopped run with no resume point at all. Its own bundle is not this
+ # run's to spend.
+ prune_checkpoints(
+ root,
+ keep = save_total_limit,
+ protect = final,
+ also_protect = _source_bundle_path(root, source_checkpoint),
+ preexisting = preexisting,
+ )
+ return str(final)
+
+
+def optimizer_key(optimizer: Any) -> str:
+ """A stable name for an optimizer implementation, e.g. ``bitsandbytes.optim.adamw.AdamW8bit``.
+ Fused vs. non-fused torch AdamW share a class and a state layout, so they compare equal."""
+ cls = type(optimizer)
+ return f"{getattr(cls, '__module__', '?')}.{getattr(cls, '__qualname__', cls.__name__)}"
+
+
+def _save_tensors(save_file: Any, state: dict[str, Any], path: Path) -> None:
+ """safetensors refuses tensors that share storage, so detach/clone every entry onto CPU
+ (a LoRA state dict is megabytes, and this runs at most once per save_steps)."""
+ payload = {
+ str(k): v.detach().to("cpu", copy = True).contiguous()
+ for k, v in (state or {}).items()
+ if v is not None
+ }
+ save_file(payload, str(path))
+ _fsync_file(path)
+
+
+def _torch_save(torch: Any, obj: Any, path: Path) -> None:
+ torch.save(obj, str(path))
+ _fsync_file(path)
+
+
+def _file_sizes(staging: Path, files: dict[str, str]) -> dict[str, int]:
+ """``{role: bytes}`` for everything already written into the staging dir."""
+ sizes: dict[str, int] = {}
+ for role, name in files.items():
+ try:
+ sizes[role] = int((staging / name).stat().st_size)
+ except OSError:
+ continue
+ return sizes
+
+
+def _write_text(path: Path, text: str) -> None:
+ path.write_text(text, encoding = "utf-8")
+ _fsync_file(path)
+
+
+# errno values that mean "this platform / filesystem will not flush that handle" rather than
+# "the data did not make it". Windows' _commit needs write access, network and container
+# filesystems return EINVAL/ENOTSUP for fsync, and neither says anything about the write.
+_FSYNC_UNSUPPORTED = frozenset(
+ code
+ for code in (
+ getattr(errno, name, None)
+ for name in ("EACCES", "EPERM", "EINVAL", "ENOTSUP", "EOPNOTSUPP", "EBADF", "ENOSYS")
+ )
+ if code is not None
+)
+
+
+def _fsync_file(path: Path) -> None:
+ """Flush the file to the device. Without it a host crash (not just a process kill) can
+ promote a directory whose manifest is durable but whose tensors are still in page cache.
+
+ A REAL fsync failure is raised, not swallowed: delayed allocation means ENOSPC and writeback
+ EIO surface here rather than at write() time, and ``_valid_state_file`` only parses a
+ safetensors header, so a bundle whose tensor bytes never reached the device would be
+ promoted and later read as valid. The caller turns that into "this run cannot be resumed".
+ A platform that simply cannot flush the handle is not such a failure and is ignored.
+
+ That discrimination is real on POSIX and NOT available on Windows: CPython maps os.fsync
+ to the UCRT's _commit, which collapses every FlushFileBuffers failure into EBADF and puts
+ the actual Win32 code in _doserrno, where Python does not look. EBADF has to stay in the
+ set below, because a volume that cannot flush reports it too, and failing every save on
+ such a volume is the worse error -- especially as the resulting write error is sticky for
+ the life of the run record. So on Windows a genuine flush failure is swallowed here, and
+ the durability guarantee rests on the per-file size check in read_checkpoint instead,
+ which catches the truncation a lost writeback actually produces."""
+ try:
+ # O_RDWR, not O_RDONLY: Windows' _commit maps to FlushFileBuffers, which needs write
+ # access on the handle. We just wrote the file, so we own it.
+ fd = os.open(str(path), os.O_RDWR)
+ except OSError:
+ return
+ try:
+ os.fsync(fd)
+ except OSError as error:
+ if error.errno not in _FSYNC_UNSUPPORTED:
+ raise
+ finally:
+ os.close(fd)
+
+
+def _fsync_dir(path: Path) -> None:
+ if not hasattr(os, "O_DIRECTORY"): # Windows cannot open a directory as a file descriptor
+ return
+ try:
+ fd = os.open(str(path), os.O_RDONLY | os.O_DIRECTORY)
+ except OSError:
+ return
+ try:
+ os.fsync(fd)
+ except OSError:
+ pass
+ finally:
+ os.close(fd)
+
+
+def _promote(staging: Path, root: Path, step: int) -> Path:
+ """Rename the staging directory into place.
+
+ ``os.replace`` onto an EXISTING directory is not supported (POSIX rename() needs an empty
+ target; Windows MoveFileEx rejects it outright), so an occupied slot is first swapped out
+ to a staging name. The displaced bundle is KEPT there rather than deleted: two runs can
+ share an output directory (resume checkpoint-10 in a folder that also holds checkpoint-15,
+ then save at 15), and the older run's bundle is not this run's to spend -- discarding this
+ run removes the replacement and hands the slot back to what was there.
+
+ A swap-aside that CANNOT be done (a Windows lock, a cross-device oddity) fails the save.
+ Deleting the occupant to free the slot was the older behaviour and the worse one: a partial
+ delete can fail the promotion too, and by then there is no copy left to put back."""
+ final = root / f"{CHECKPOINT_PREFIX}{step}"
+ displaced: Optional[Path] = None
+ if final.exists():
+ displaced = root / f"{_STAGING_PREFIX}replaced-{step}-{uuid.uuid4().hex[:8]}"
+ os.replace(final, displaced)
+ # os.replace does NOT restamp the directory: the inode keeps whatever mtime the bundle
+ # was written with, so an old checkpoint moved aside looked long-abandoned the instant
+ # it arrived and a concurrent read handed it straight back into the slot we are about to
+ # fill. Stamp it with the moment of the swap, which is what the grace is measuring.
+ with contextlib.suppress(OSError):
+ os.utime(displaced, None)
+ try:
+ os.replace(staging, final)
+ except OSError:
+ # The slot is now empty and the only copy of the last resumable state is the one we
+ # moved aside, so put it back before the failure propagates. Without this, a resave of
+ # an occupied step (a resumed run rewriting checkpoint-15) that fails to promote leaves
+ # the run with no checkpoint at all -- strictly worse than the stale one it replaced.
+ if displaced is not None:
+ with contextlib.suppress(OSError):
+ os.replace(displaced, final)
+ raise
+ _fsync_dir(root)
+ return final
+
+
+# ``.tmp-checkpoint-stale-<step>-<uuid>`` / ``.tmp-checkpoint-replaced-<step>-<uuid>``: the step
+# is what _promote encodes, so an orphan can be handed back to the slot it came from. ``stale``
+# is a promotion killed mid-swap; ``replaced`` is a bundle a later write displaced, held so the
+# slot can be restored if that write is later discarded.
+_STALE_SLOT = re.compile(r"^(?:stale|replaced)-(\d+)-")
+_REPLACED_SLOT = re.compile(r"^replaced-(\d+)-")
+
+
+def _prune_staging(root: Path) -> None:
+ """Drop abandoned staging directories from an earlier killed process. Safe because only
+ one trainer ever writes into a run's output dir, and this runs after our own promotion.
+
+ A ``stale-<step>`` orphan whose slot is EMPTY is not abandoned work: it is the previous
+ bundle, moved aside by a promotion that was killed before the rename landed. Deleting it
+ would throw away the run's last resumable state, so it is handed back to its slot instead.
+
+ A ``replaced-<step>`` orphan is not abandoned work either, even with its slot occupied: it
+ is the bundle THIS run displaced, held so that discarding this run does not take another
+ run's resume point with it. Only the cleanup paths retire those.
+ """
+ try:
+ entries = list(root.glob(f"{_STAGING_PREFIX}*"))
+ except OSError:
+ return
+
+ # Newest first, so a stacked slot gets its immediate predecessor back rather than whichever
+ # entry the filesystem happened to list first.
+ def _written_at(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+ for entry in sorted(entries, key = _written_at, reverse = True):
+ suffix = entry.name[len(_STAGING_PREFIX) :]
+ if _recover_orphaned_slot(root, entry) or _REPLACED_SLOT.match(suffix):
+ continue
+ shutil.rmtree(entry, ignore_errors = True)
+
+
+# How long a ``replaced-`` bundle must have been sitting before a READ path will hand it back.
+# _promote leaves the slot empty for the microseconds between the swap-aside and the rename,
+# and a history or detail read landing in that window moved the old bundle back in -- so the
+# writer's own os.replace then failed against a directory that had reappeared, and the periodic
+# or stop-and-save checkpoint was lost. A few seconds covers a window measured in microseconds
+# while still recovering a genuinely crashed promotion on the user's next poll. Only
+# ``replaced-`` entries wait: a ``stale-`` orphan is from an older build and never in flight,
+# and writers pass 0 because they run after their own promotion.
+_LIVE_REPLACEMENT_GRACE_SECONDS = 5.0
+
+
+def _recover_orphaned_slots(
+ root: Path, *, min_age: float = _LIVE_REPLACEMENT_GRACE_SECONDS
+) -> None:
+ """Hand every stale orphan back to its empty slot. Read paths call this before deciding a
+ run has nothing to resume; it never deletes anything.
+
+ Newest first per slot, for the reason ``_retire_replaced_slots`` sorts: replacements stack,
+ and filesystem order would restore whichever appeared first -- an older branch's adapter,
+ optimizer and RNG rather than the bundle that was in the slot immediately before the crash.
+ """
+ try:
+ entries = list(root.glob(f"{_STAGING_PREFIX}*"))
+ except OSError:
+ return
+
+ def _written_at(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+ now = time.time()
+ for entry in sorted(entries, key = _written_at, reverse = True):
+ in_flight_shape = _REPLACED_SLOT.match(entry.name[len(_STAGING_PREFIX) :]) is not None
+ if in_flight_shape and min_age > 0 and (now - _written_at(entry)) < min_age:
+ continue # possibly a promotion in flight; leave it to the writer
+ _recover_orphaned_slot(root, entry)
+
+
+def _recover_orphaned_slot(root: Path, entry: Path) -> bool:
+ """True when ``entry`` is a stale bundle that must not be swept up: either it was handed
+ back to its empty slot, or the hand-back failed and leaving it on disk beats deleting the
+ only copy of the run's last resumable state."""
+ match = _STALE_SLOT.match(entry.name[len(_STAGING_PREFIX) :])
+ if match is None:
+ return False
+ slot = root / f"{CHECKPOINT_PREFIX}{int(match.group(1))}"
+ if slot.exists():
+ return False
+ try:
+ os.replace(entry, slot)
+ except OSError:
+ # Could not hand it back. Leaving it on disk is still better than deleting the only
+ # copy of the run's last resumable state.
+ pass
+ return True
+
+
+def _retire_replaced_slots(root: Path, *, restore: bool) -> None:
+ """Settle the bundles this run displaced, once its own are gone.
+
+ ``restore`` hands each one back to the slot the cleanup just emptied, which is the whole
+ reason it was kept: the pre-existing bundle comes back instead of dying with the run that
+ overwrote it. False is the fresh-run case, where the adapter those bundles belong to has
+ just been overwritten and they are a trap rather than resumable state. Either way, nothing
+ is left behind afterwards.
+ """
+ try:
+ entries = list(root.glob(f"{_STAGING_PREFIX}replaced-*"))
+ except OSError:
+ return
+
+ # NEWEST first per slot. Replacements stack: a run that crashed after displacing
+ # checkpoint-15 leaves its copy behind, and a later run displacing the same slot leaves
+ # another. Restoring whichever sorted first by NAME (a uuid, so effectively at random)
+ # resurrected an older branch's optimizer state instead of the predecessor that was
+ # actually in the slot, and later resumes then continued the wrong lineage.
+ def _written_at(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+ entries.sort(key = _written_at, reverse = True)
+ restored_slots: set[Path] = set()
+ for entry in entries:
+ match = _REPLACED_SLOT.match(entry.name[len(_STAGING_PREFIX) :])
+ slot = root / f"{CHECKPOINT_PREFIX}{int(match.group(1))}" if match else None
+ if restore and slot is not None and slot not in restored_slots and not slot.exists():
+ try:
+ os.replace(entry, slot)
+ restored_slots.add(slot)
+ continue
+ except OSError:
+ # Could not hand it back. Leaving it on disk still beats deleting the only copy
+ # of another run's last resumable state.
+ continue
+ shutil.rmtree(entry, ignore_errors = True)
+
+
+def _source_bundle_path(root: Path, source_checkpoint) -> Optional[Path]:
+ """The bundle this run resumed from, when it lives in ``root``. None otherwise."""
+ if not source_checkpoint:
+ return None
+ try:
+ source = Path(source_checkpoint).expanduser().resolve()
+ except OSError:
+ return None
+ for candidate in list_checkpoints(root):
+ try:
+ if candidate.resolve() == source:
+ return candidate
+ except OSError:
+ continue
+ return None
+
+
+def prune_checkpoints(
+ output_dir: str | os.PathLike[str],
+ keep: int = DEFAULT_SAVE_TOTAL_LIMIT,
+ *,
+ protect: Optional[Path] = None,
+ also_protect: Optional[Path] = None,
+ preexisting: "Optional[Iterable[Any]]" = None,
+) -> None:
+ """Keep only the ``keep`` newest ``checkpoint-<N>`` bundles. ``keep <= 0`` keeps all.
+
+ ``protect`` and ``also_protect`` are never pruned. Newest is by STEP, and a resume can legitimately write a bundle
+ that is not the highest-numbered one in the folder: resume checkpoint-10, stop at 15, with 20
+ and 30 still present and keep=2, and the bundle just written is the one deleted -- while the
+ service reports checkpoint_saved for a path that no longer exists, and the run's own start
+ fence stops those older bundles from making it resumable. So the caller pins the one it just
+ promoted, and the limit applies to the rest.
+
+ ``preexisting`` are the bundles that were in the directory before this run wrote anything.
+ They are not this run's to spend: the supported branched resume (continue checkpoint-10
+ while 20 and 30 are still there) pins 10 and the new 15, drops ``keep`` to zero and used to
+ delete 20 and 30 outright -- irreversibly, and a later stop-without-saving cannot bring them
+ back. They are excluded entirely, so the limit governs only what this run wrote."""
+ if keep <= 0:
+ return
+ # Identity, not pathname, for the same reason the cleanup helpers use it: a run can save at
+ # a step whose directory was already there (resume checkpoint-10 in a folder that also holds
+ # checkpoint-15, save at 15), and the bundle occupying that path afterwards is THIS run's.
+ # Excluding it as pre-existing let the limit be exceeded once per overwritten slot -- an old
+ # checkpoint-10 with keep=2 and saves at 10, 20 and 30 retained all three -- which is real
+ # disk on a long run. An entry with no identity (an older caller, or a bundle that could not
+ # be read) keeps the pathname behaviour, which errs towards keeping.
+ kept_from_before: set[Path] = set()
+ for entry in preexisting or ():
+ if isinstance(entry, tuple):
+ path, identity = Path(entry[0]), entry[1]
+ if identity is not None and _bundle_identity(path) != identity:
+ continue
+ kept_from_before.add(path)
+ else:
+ kept_from_before.add(Path(entry))
+ survivors = [c for c in list_checkpoints(output_dir) if c not in kept_from_before]
+ for pinned in (protect, also_protect):
+ if pinned is not None and pinned in survivors:
+ # It occupies one of the kept slots whether or not it sorted into the top `keep`.
+ survivors = [c for c in survivors if c != pinned]
+ keep = max(0, keep - 1)
+ for stale in survivors[keep:]:
+ shutil.rmtree(stale, ignore_errors = True)
+
+
+def clear_checkpoints(output_dir: str | os.PathLike[str]) -> None:
+ """Remove every ``checkpoint-<N>`` bundle in ``output_dir``. Used when a fresh (non-resumed)
+ run takes over an output directory that an earlier run of the same name left checkpoints in."""
+ root = Path(output_dir).expanduser()
+ for stale in list_checkpoints(root):
+ shutil.rmtree(stale, ignore_errors = True)
+ _retire_replaced_slots(root, restore = False)
+
+
+def resumed_into_this_dir(cfg: Any, output_dir: "str | os.PathLike[str]") -> bool:
+ """Whether the bundle this run resumed FROM lives in ``output_dir``.
+
+ The usual case, and the one the first-save discard is skipped for: a resumed run shares its
+ source's directory, so clearing "everything that was here" would take the source with it.
+ An API caller can instead resume from directory A into a reused output_dir B, and then B's
+ contents are as foreign as they would be to a fresh run -- keeping them lets a higher-step
+ bundle outlive this run and be picked by a later resume by directory."""
+ source = getattr(cfg, "resume_from_checkpoint", None)
+ if not source:
+ return False
+ try:
+ root = Path(output_dir).expanduser().resolve()
+ candidate = Path(str(source)).expanduser().resolve()
+ except OSError:
+ return False
+ # The request names either the bundle itself or the directory holding it.
+ return candidate == root or candidate.parent == root
+
+
+def snapshot_checkpoints(output_dir: str | os.PathLike[str]) -> list[tuple[Path, Optional[tuple]]]:
+ """The bundles in ``output_dir`` right now, each with its identity.
+
+ Captured BEFORE the run's first write, because ownership cannot be decided by pathname at
+ cleanup time: a resumed run can overwrite a bundle that was already there, and by then the
+ directory holds this run's state under the old name."""
+ return [(path, _bundle_identity(path)) for path in list_checkpoints(output_dir)]
+
+
+def retire_own_checkpoints(
+ output_dir: str | os.PathLike[str],
+ preexisting: "Iterable[Any]",
+ *,
+ resumed_here: bool = True,
+) -> None:
+ """Drop the bundles a finished run leaves behind.
+
+ Same selection as ``clear_own_checkpoints`` and a different reason: nothing here is being
+ discarded, the run simply has no continuation left. Without it the newest bundle in the
+ directory is the last periodic save (the final iteration writes none), and a later resume
+ -- which cannot see that the run completed -- rolls the whole training state back to it.
+
+ ``resumed_here`` False means a FRESH run in this directory, and then the bundles that were
+ already here go too. A fresh run that never wrote one of its own (the default
+ ``save_steps=0``) never reaches the ``discard_existing`` clear inside the writer, so it
+ published its adapter beside a previous run's checkpoints -- which a later resume by output
+ directory would continue instead. The adapter those belonged to has just been overwritten,
+ so they are not resumable state, only a trap.
+ """
+ if resumed_here:
+ clear_own_checkpoints(output_dir, preexisting)
+ return
+ root = Path(output_dir).expanduser()
+ for stale in list_checkpoints(root):
+ shutil.rmtree(stale, ignore_errors = True)
+ _retire_replaced_slots(root, restore = False)
+
+
+def discard_preexisting_checkpoints(
+ output_dir: str | os.PathLike[str], preexisting: "Iterable[Any]"
+) -> None:
+ """Remove the bundles this run FOUND, keeping the ones it wrote. The inverse of
+ ``clear_own_checkpoints``.
+
+ For a fresh retrain that stops WITH save: it owns the directory (it overwrites the published
+ adapter there), and its stop bundle is a lower step than an earlier run's leftovers. Resume
+ by directory picks the newest bundle by step, so those leftovers outrank the partial the user
+ just saved and a Resume continues the wrong training. A run that RESUMED here does not call
+ this: the bundles it found include the one it continued from, which is not its to spend.
+ """
+ root = Path(output_dir).expanduser()
+ keep: dict[Path, Optional[tuple]] = {}
+ for entry in preexisting:
+ if isinstance(entry, tuple):
+ path, identity = entry
+ keep[Path(path)] = identity
+ else:
+ keep[Path(entry)] = _bundle_identity(Path(entry))
+ for stale in list_checkpoints(root):
+ # Identity, not pathname: a bundle this run WROTE OVER one that was here is this run's,
+ # and deleting it would throw away the stop checkpoint the user asked for.
+ if stale in keep and keep[stale] == _bundle_identity(stale):
+ shutil.rmtree(stale, ignore_errors = True)
+ _retire_replaced_slots(root, restore = False)
+
+
+def discard_named_checkpoints(paths: "Iterable[Any]") -> None:
+ """Remove the exact bundles named, then hand any slot they displaced back.
+
+ The parent-side twin of ``clear_own_checkpoints``: a child that is killed after a
+ stop-without-saving never runs its own cleanup, and the parent knows only the paths it saw
+ ``checkpoint_saved`` for -- which is precisely the set this run wrote. Anything that predated
+ the run is untouched, and a bundle written OVER a predecessor gives its slot back.
+ """
+ roots: set[Path] = set()
+ for value in paths:
+ if not value:
+ continue
+ try:
+ path = Path(str(value)).expanduser()
+ except (TypeError, ValueError):
+ continue
+ if checkpoint_step(path) < 0:
+ continue # not a bundle path; never delete something we cannot name
+ roots.add(path.parent)
+ shutil.rmtree(path, ignore_errors = True)
+ for root in roots:
+ _retire_replaced_slots(root, restore = True)
+
+
+def clear_own_checkpoints(output_dir: str | os.PathLike[str], preexisting: "Iterable[Any]") -> None:
+ """Remove the bundles THIS run wrote, leaving the ones it found.
+
+ A discard must not take the checkpoint the run resumed FROM with it: a resumed run writes
+ into the same directory the source bundle lives in, so an accidental resume followed by
+ "stop without saving" would otherwise leave the original stopped run unresumable -- the one
+ thing the user was trying not to disturb. Bundles are identified by the set captured before
+ the run's first write, not by step number, because a resume writes lower numbers than the
+ ones already there."""
+ # Keyed by path AND by the bundle's own identity, not by path alone. A resumed run can
+ # periodically save at a step whose directory was already there (resume checkpoint-10 in a
+ # folder that also holds checkpoint-15, save at 15), which REPLACES that bundle: the
+ # original is gone either way, and matching on the name alone then preserved the discarded
+ # run's replacement as though it were the bundle it overwrote.
+ keep: dict[Path, Optional[tuple]] = {}
+ for entry in preexisting:
+ # A bare path (an older caller) keeps the pathname-only behaviour for that entry.
+ if isinstance(entry, tuple):
+ path, identity = entry
+ keep[Path(path)] = identity
+ else:
+ keep[Path(entry)] = _bundle_identity(Path(entry))
+ for stale in list_checkpoints(output_dir):
+ if stale in keep and keep[stale] == _bundle_identity(stale):
+ continue
+ shutil.rmtree(stale, ignore_errors = True)
+ # A bundle this run wrote OVER a pre-existing one has just been removed, so its slot is free
+ # and the displaced original goes back into it. Without this the discard takes the other
+ # run's resume point with it: the replacement is not the bundle it overwrote, so the identity
+ # match above cannot keep it, and the original was already gone.
+ _retire_replaced_slots(Path(output_dir).expanduser(), restore = True)
+
+
+def _bundle_identity(path: Path) -> Optional[tuple]:
+ """What distinguishes one bundle at this path from another written over it.
+
+ The manifest is written last and carries the writing run's own start time, so it separates
+ "the bundle that was here" from "the bundle this run put here" without hashing tensors.
+ None for an unreadable or absent manifest, which compares equal to itself and so leaves an
+ unreadable pre-existing directory alone."""
+ try:
+ manifest = json.loads((path / TRAINER_STATE_FILENAME).read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ return None
+ # created_at is the moment THIS bundle's manifest was written -- the completion marker, so
+ # it exists on every valid bundle and differs between two writes at the same step.
+ return (manifest.get("created_at"), manifest.get("global_step"))
+
+
+# ── reading + validation ──────────────────────────────────────────────────────
+def checkpoint_step(path: Path) -> int:
+ """The step encoded in a ``checkpoint-<N>`` directory name, or -1."""
+ name = path.name
+ if not name.startswith(CHECKPOINT_PREFIX):
+ return -1
+ try:
+ step = int(name[len(CHECKPOINT_PREFIX) :])
+ except ValueError:
+ return -1
+ return step if step >= 0 else -1
+
+
+def list_checkpoints(output_dir: str | os.PathLike[str]) -> list[Path]:
+ """Every ``checkpoint-<N>`` directory under ``output_dir``, newest step first. Does not
+ validate; use ``read_checkpoint`` / ``latest_valid_checkpoint`` for that."""
+ root = Path(output_dir).expanduser()
+ try:
+ found = [p for p in root.glob(f"{CHECKPOINT_PREFIX}*") if p.is_dir()]
+ except OSError:
+ return []
+ return sorted((p for p in found if checkpoint_step(p) >= 0), key = checkpoint_step, reverse = True)
+
+
+def read_checkpoint(path: str | os.PathLike[str]) -> Optional[dict[str, Any]]:
+ """The manifest of a COMPLETE, self-consistent bundle, or None.
+
+ Every gate a resume depends on is checked here: the manifest parses and declares a
+ format/version this build understands, its ``global_step`` agrees with the directory
+ name, and every file the manifest lists is present and parses as the state file it
+ claims to be. A staging directory promoted mid-write cannot pass, because the manifest
+ is the last thing written."""
+ directory = Path(path).expanduser()
+ if not directory.is_dir():
+ return None
+ try:
+ manifest = json.loads((directory / TRAINER_STATE_FILENAME).read_text(encoding = "utf-8"))
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
+ return None
+ if not isinstance(manifest, dict):
+ return None
+ if manifest.get("format") != CHECKPOINT_FORMAT:
+ return None
+ version = manifest.get("version")
+ if (
+ not isinstance(version, int)
+ or isinstance(version, bool)
+ or not 1 <= version <= CHECKPOINT_VERSION
+ ):
+ return None
+ step = manifest.get("global_step")
+ if isinstance(step, bool) or not isinstance(step, int) or step < 0:
+ return None
+ named_step = checkpoint_step(directory)
+ if named_step >= 0 and named_step != step:
+ return None
+ files = manifest.get("files")
+ if not isinstance(files, dict) or not files.get("adapter"):
+ return None
+ sizes = manifest.get("file_sizes")
+ sizes = sizes if isinstance(sizes, dict) else {}
+ for role, name in files.items():
+ if not isinstance(name, str) or not name or Path(name).name != name:
+ return None
+ # Optimizer / scheduler state can be validly tensor-free (SGD without momentum, a
+ # constant LR schedule), so only the weight bundles must carry tensors.
+ if not _valid_state_file(directory / name, require_tensor = role in ("adapter", "ema")):
+ return None
+ expected_size = sizes.get(role)
+ if isinstance(expected_size, int) and not isinstance(expected_size, bool):
+ # Absent on a bundle written before sizes were recorded, which skips the check
+ # rather than failing it -- an old checkpoint stays resumable.
+ try:
+ if (directory / name).stat().st_size != expected_size:
+ return None
+ except OSError:
+ return None
+ return manifest
+
+
+def _valid_state_file(path: Path, require_tensor: bool = True) -> bool:
+ """Reuse the LLM resume validator: it already parses a safetensors header and walks a
+ torch zip's pickle to the STOP opcode without importing torch.
+
+ Wrapped in a blanket catch because a resume path is CLIENT-supplied: that validator only
+ guards ``(OSError, ValueError, BadZipFile)``, so a deflate-corrupt member raises
+ ``zlib.error`` straight out of a route preflight and 500s it. Anything unreadable is, by
+ definition, not a usable checkpoint."""
+ from core.training.resume import _valid_state_file as _validate
+ try:
+ return _validate(path, require_tensor = require_tensor)
+ except Exception: # noqa: BLE001 -- unreadable in any way == not resumable
+ return False
+
+
+def latest_valid_checkpoint(
+ output_dir: str | os.PathLike[str],
+ not_before: Optional[float] = None,
+ not_after: Optional[float] = None,
+ usable: "Optional[Callable[[Path, dict], bool]]" = None,
+) -> Optional[tuple[Path, dict]]:
+ """The newest complete bundle under ``output_dir`` as ``(path, manifest)``, or None.
+ Scans newest-first and skips any bundle that fails validation, so one corrupt
+ checkpoint does not hide the good one before it.
+
+ ``not_before`` (a run's start time) skips bundles written BEFORE it. Two runs can share an
+ output directory -- training the same adapter name twice writes into the same folder -- and
+ the earlier run's bundles can carry higher step numbers than the later run's, so without
+ this a fresh run would advertise, and then resume, a different run's training state.
+
+ ``not_after`` (a run's end time) is the same fence in the other direction, and it matters
+ just as much: with only a lower bound, an EARLIER run that has already finished still sees
+ every bundle a LATER run wrote into the shared folder, and offers the newest of them as
+ its own. The identity gate cannot catch that -- same family, same base, same dataset, same
+ LoRA shape -- so the earlier run resumes the later run's optimizer moments, LR position
+ and RNG under its own config, and records the wrong lineage while doing it."""
+ # Repair first. A promotion killed between the swap-aside and the rename leaves the run's
+ # only bundle under the hidden stale name, and _prune_staging fixes that -- but it runs
+ # after a later successful save, which a user who cannot resume will never reach. So the
+ # read path that decides "there is nothing to resume" hands the orphan back to its slot
+ # before it answers. Idempotent, and it only ever touches an EMPTY slot.
+ _recover_orphaned_slots(Path(output_dir).expanduser())
+ for candidate in list_checkpoints(output_dir):
+ manifest = read_checkpoint(candidate)
+ if manifest is None:
+ continue
+ if not_before is not None:
+ try:
+ created = float(manifest.get("created_at") or 0.0)
+ except (TypeError, ValueError):
+ created = 0.0
+ if created < float(not_before):
+ continue
+ if not_after is not None:
+ try:
+ created = float(manifest.get("created_at") or 0.0)
+ except (TypeError, ValueError):
+ created = 0.0
+ # A bundle with no usable created_at (0.0) is not fenced out by the upper bound:
+ # it predates the field, and refusing it would make an old run unresumable.
+ if created and created > float(not_after):
+ continue
+ # An extra gate for callers whose answer PINS the bundle it names.
+ if usable is not None and not usable(candidate, manifest):
+ continue
+ return candidate, manifest
+ return None
+
+
+def iter_valid_checkpoints(output_dir: str | os.PathLike[str]) -> "list[tuple[Path, dict]]":
+ """Every structurally complete bundle under ``output_dir``, newest first.
+
+ ``latest_valid_checkpoint`` answers with the first one; the resume preflight needs the rest,
+ because its own checks (identity, required state, a real torch.load) are stricter than the
+ header scan. Stopping at the newest defeated the two-checkpoint retention policy: a bundle
+ whose optimizer file passes the header walk but fails to load left the run unresumable with
+ an intact older copy sitting beside it."""
+ _recover_orphaned_slots(Path(output_dir).expanduser())
+ found: list[tuple[Path, dict]] = []
+ for candidate in list_checkpoints(output_dir):
+ manifest = read_checkpoint(candidate)
+ if manifest is not None:
+ found.append((candidate, manifest))
+ return found
+
+
+# Run statuses that can never be continued, with the reason shown in the UI.
+_UNRESUMABLE_STATUS = {
+ "completed": "This run finished its full step count, so there is nothing left to train.",
+ "running": "This run is still training.",
+}
+
+
+def _fully_loadable(path: Path, manifest: dict[str, Any]) -> bool:
+ """Whether ``path`` passes every non-identity gate ``preflight_resume`` applies.
+
+ ``read_checkpoint`` is a header scan, so the newest bundle can pass it and still fail the
+ required-state check or a real torch.load. Advertising THAT one as the run's resume point
+ pinned it: the UI sends back the exact checkpoint_path, which the preflight then treats as
+ explicit and cannot scan past -- defeating the directory fallback built for this case.
+ """
+ try:
+ _assert_required_state(path, manifest)
+ _assert_optimizer_buildable(path, manifest)
+ _assert_loadable(path, manifest)
+ except ResumeError:
+ return False
+ return True
+
+
+def _source_checkpoint_bundle(
+ source_checkpoint, source_created_at: Optional[float] = None
+) -> Optional[tuple[Path, dict[str, Any]]]:
+ """The bundle a run RESUMED FROM, when it is still readable on disk AND still the same one.
+
+ A resume that ends before writing a bundle of its own -- an OOM on the first restored step
+ is the usual way -- has nothing under its own output dir, and if that dir is a new one it
+ may not even exist. The source it was validated against is still there and still correct to
+ continue from, so it is read directly rather than by widening the started_at fence, which
+ exists to keep an unrelated earlier run's bundles out.
+
+ ``source_created_at`` is the manifest timestamp recorded when this run actually resumed.
+ A pathname is not an identity: another run can write its own ``checkpoint-<N>`` over the
+ same slot, and with a matching training identity the route would accept it -- silently
+ continuing a different branch's adapter and moments under this run's lineage. Absent (an
+ older record), the check is skipped rather than refusing an otherwise valid fallback.
+ """
+ if not source_checkpoint:
+ return None
+ try:
+ candidate = Path(str(source_checkpoint)).expanduser()
+ manifest = read_checkpoint(candidate) if candidate.is_dir() else None
+ except OSError:
+ return None
+ if manifest is None:
+ return None
+ if source_created_at:
+ try:
+ written = float(manifest.get("created_at") or 0.0)
+ except (TypeError, ValueError):
+ written = 0.0
+ # 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
+ # Same gate the directory scan applies, for the same reason: this path is pinned back to the
+ # start route verbatim, and read_checkpoint is only a header scan. A source whose required
+ # state or real torch.load has gone since would be advertised as resumable and refused on
+ # the first click.
+ if not _fully_loadable(candidate, manifest):
+ return None
+ return (candidate, manifest)
+
+
+def describe_resume_state(
+ output_dir: Optional[str],
+ *,
+ status: Optional[str] = None,
+ started_at: Optional[float] = None,
+ ended_at: Optional[float] = None,
+ source_checkpoint: Optional[str] = None,
+ source_created_at: Optional[float] = None,
+ total_steps: Optional[int] = None,
+) -> dict[str, Any]:
+ """What the UI needs to offer (or explain the absence of) a Resume action for a run.
+
+ Returns ``can_resume`` / ``checkpoint_step`` / ``checkpoint_path`` /
+ ``resume_blocked_reason``. Mirrors the LLM ``can_resume_run`` rules: a completed run has
+ nothing left, a stopped run needs remaining steps, an errored run is resumable purely on
+ the state it left behind. Never raises: a deleted or unreadable output directory simply
+ reports that there is nothing to resume from."""
+ blank: dict[str, Any] = {
+ "can_resume": False,
+ "checkpoint_step": None,
+ "checkpoint_path": None,
+ "resume_blocked_reason": None,
+ }
+ if not output_dir:
+ return blank
+ blocked = _UNRESUMABLE_STATUS.get(str(status or "").strip().lower())
+ if blocked:
+ return {**blank, "resume_blocked_reason": blocked}
+ try:
+ root = Path(str(output_dir)).expanduser()
+ if not root.is_dir():
+ # A resume into a NEW output dir that died before its first save never created it,
+ # and the bundle it was validated against is still sitting in the source dir. The
+ # fallback below is exactly for that, so it has to be reachable from here.
+ recovered = _source_checkpoint_bundle(source_checkpoint, source_created_at)
+ if recovered is None:
+ return {
+ **blank,
+ "resume_blocked_reason": "This run's output folder no longer exists.",
+ }
+ found = recovered
+ else:
+ found = latest_valid_checkpoint(
+ root,
+ not_before = started_at,
+ not_after = ended_at,
+ # The action this answer drives sends the exact path back, which the preflight
+ # then treats as explicit and cannot scan past -- so the bundle named here has
+ # to be one that will actually load, not merely one whose header parses.
+ usable = _fully_loadable,
+ )
+ if found is None and source_checkpoint:
+ # This run RESUMED and then ended before writing a bundle of its own -- an OOM on
+ # the first restored step is the usual way. The source it was validated against is
+ # still on disk and still correct to continue from, but it predates started_at, so
+ # the fence above excludes it and the run reads as unresumable when retrying is the
+ # obvious thing to do. Read it directly rather than widening the fence, which exists
+ # to stop an unrelated earlier run's bundles being offered.
+ found = _source_checkpoint_bundle(source_checkpoint, source_created_at)
+ except OSError:
+ return blank
+ if found is None:
+ if not list_checkpoints(root):
+ reason = "This run saved no resume checkpoint, so it cannot be continued."
+ elif started_at is not None and latest_valid_checkpoint(root) is not None:
+ # Bundles are there, but every one predates this run: they belong to an earlier run
+ # that trained into the same folder. Saying "corrupt" here would be a lie.
+ reason = (
+ "This run saved no resume checkpoint of its own; the checkpoints in its folder "
+ "were left by an earlier run of the same adapter."
+ )
+ else:
+ reason = "This run's checkpoints are incomplete or corrupt, so it cannot be resumed."
+ return {**blank, "resume_blocked_reason": reason}
+ path, manifest = found
+ step = int(manifest.get("global_step") or 0)
+ # The target the resume would run to. The record's own total_steps wins (it is what the UI
+ # replays); the manifest's copy covers a record written before that field existed.
+ target = int(total_steps or manifest.get("target_steps") or 0)
+ if target and step >= target:
+ return {
+ **blank,
+ "checkpoint_step": step,
+ "checkpoint_path": str(path),
+ "resume_blocked_reason": (
+ f"This run's checkpoint is already at step {step} of {target}, so there is "
+ "nothing left to train."
+ ),
+ }
+ return {
+ "can_resume": True,
+ "checkpoint_step": step,
+ "checkpoint_path": str(path),
+ "resume_blocked_reason": None,
+ }
+
+
+# ── resume preflight ──────────────────────────────────────────────────────────
+def resolve_resume_dir(path_value: str) -> Path:
+ """Contain a client-supplied resume path under the Studio outputs root.
+
+ Accepts either the run's ``output_dir`` (what the UI replays, matching the LLM resume
+ flow) or an explicit ``checkpoint-<N>`` directory. Raises ResumeError with a
+ user-facing message for a path that escapes outputs, comes from another operating
+ system, or no longer exists."""
+ from core.training.resume import normalize_resume_output_dir
+ from utils.paths import outputs_root
+
+ try:
+ resolved = Path(normalize_resume_output_dir(str(path_value)))
+ except ValueError as error:
+ message = str(error)
+ if not message.startswith("Resume checkpoint"):
+ # The containment resolver raises an internal "path escapes root: <abs> -> <abs>"
+ # that quotes server paths at the user; replace it with the same wording the LLM
+ # resume flow shows.
+ message = "Resume checkpoint must be inside Unsloth outputs."
+ raise ResumeError(message) from error
+ # A name that cleans away to nothing (".", "outputs", "./.") lands on the outputs ROOT, where
+ # the scan would sweep checkpoint dirs across unrelated runs. Same guard the start route
+ # applies to output_dir.
+ if resolved.resolve(strict = False) == outputs_root().resolve(strict = False):
+ raise ResumeError(
+ f"'{path_value}' is the outputs folder itself, not a training run inside it."
+ )
+ return resolved
+
+
+# What restore_resume_state() refuses to continue without. Kept here rather than inferred from
+# the manifest, because the manifest is exactly what a truncated or hand-edited bundle gets
+# wrong: _assert_loadable only opens the roles the bundle happens to LIST, so a checkpoint that
+# lists an adapter and nothing else passed the route preflight, the resident GPU model was
+# evicted, and the child then died on "This checkpoint carries no optimizer state".
+# The random.Random streams both trainers construct and hand to capture_rng_state. Named here
+# because the preflight has to know what a complete bundle carries.
+_TRAINER_RNG_STREAMS: tuple[str, ...] = ("loop", "variant")
+
+_REQUIRED_STATE: tuple[tuple[str, str], ...] = (
+ ("adapter", "the trained LoRA weights"),
+ ("optimizer", "the optimizer moments"),
+ ("scheduler", "the learning-rate schedule position"),
+ # Both image trainers draw the latent, the noise and the timestep from torch immediately
+ # after resume, so a bundle with no RNG file continues a different random stream while
+ # restore_rng_state leaves the generator at its fresh seed and says nothing.
+ ("rng", "the random-number generator state"),
+)
+
+
+def _assert_required_state(path: Path, manifest: dict[str, Any]) -> None:
+ """Refuse a bundle missing state the trainer treats as mandatory, BEFORE teardown."""
+ files = manifest.get("files")
+ listed = files if isinstance(files, dict) else {}
+ missing = [
+ label
+ for role, label in _REQUIRED_STATE
+ if not isinstance(listed.get(role), str) or not listed.get(role)
+ ]
+ # The sampler's permutation lives in the manifest rather than a file. Required for an
+ # image bundle, where both trainers always supply a sampler and the child refuses without
+ # it -- after the route has evicted the resident models. Left optional for any other kind,
+ # whose trainer may legitimately have none.
+ if str(manifest.get("kind") or "image") == "image" and not isinstance(
+ manifest.get("sampler"), dict
+ ):
+ missing.append("the dataset sampler position")
+ # The torch generator lives in the rng FILE; the two random.Random streams the trainers own
+ # (the loop's index/crop draws and the latent-cache variant picks) live in the manifest
+ # beside it. restore_rng_state is per-part best-effort, so a bundle that lists the file but
+ # has lost either stream restores torch and silently leaves those two at their fresh seeds:
+ # crop and flip selection diverges on the first step, and the sampler draws a different
+ # permutation once its saved cycle ends. Both trainers always write both.
+ rng_manifest = manifest.get("rng")
+ saved_streams = rng_manifest.get("streams") if isinstance(rng_manifest, dict) else None
+ if not isinstance(saved_streams, dict) or not all(
+ isinstance(saved_streams.get(name), (list, tuple)) for name in _TRAINER_RNG_STREAMS
+ ):
+ missing.append("the trainer's random-number streams")
+ if not missing:
+ return
+ raise ResumeError(
+ f"'{path.name}' is missing {_join_clauses(missing)}, so the run cannot be continued "
+ "from it. Resume from an earlier checkpoint, or start a new run."
+ )
+
+
+def _join_clauses(items: list[str]) -> str:
+ if len(items) == 1:
+ return items[0]
+ return ", ".join(items[:-1]) + " and " + items[-1]
+
+
+def _assert_optimizer_buildable(path: Path, manifest: dict[str, Any]) -> None:
+ """Refuse moments this host provably cannot build an optimizer for, BEFORE teardown.
+
+ The trainers choose bitsandbytes AdamW8bit or torch AdamW from the HOST, so a bundle can
+ arrive with foreign moments -- and the child's own check then fires after the route has
+ evicted the resident inference models and loaded a multi-GB base, for a run that is
+ guaranteed to terminate without training.
+
+ Deliberately one-directional, and deliberately import-free. ``find_spec`` answers "is
+ bitsandbytes installed" without creating a CUDA context in the Studio process, but it
+ cannot tell an installed-and-broken wheel (which the trainer catches and falls back from)
+ from a working one. So only the case that cannot be wrong is refused here: 8-bit moments
+ with no bitsandbytes to load them, or with the fp32 override forcing torch AdamW. The
+ other direction stays with the child, where the real optimizer object exists.
+ """
+ saved = manifest.get("optimizer_class")
+ if not isinstance(saved, str) or "bitsandbytes" not in saved:
+ return
+ reason = None
+ if os.environ.get("UNSLOTH_DIFFUSION_FP32_OPTIM", "") in ("1", "true"):
+ reason = "UNSLOTH_DIFFUSION_FP32_OPTIM forces plain torch AdamW on this host"
+ else:
+ try:
+ import importlib.util
+ if importlib.util.find_spec("bitsandbytes") is None:
+ reason = "bitsandbytes is not installed on this host"
+ except (ImportError, ValueError):
+ reason = "bitsandbytes is not installed on this host"
+ if reason is None:
+ return
+ raise ResumeError(
+ f"'{path.name}' carries bitsandbytes 8-bit optimizer state, but {reason}, so its "
+ "moments cannot be restored. Install bitsandbytes (or unset the override) to continue "
+ "this run."
+ )
+
+
+def _assert_loadable(path: Path, manifest: dict[str, Any]) -> None:
+ """Actually open every state file the manifest lists, and turn any failure into a
+ ResumeError.
+
+ read_checkpoint deliberately only parses headers -- it is called once per bundle by the
+ run-history listing, which must stay cheap -- so it cannot tell a torch zip that walks to
+ STOP from one torch.load will refuse. A pickle carrying a global outside the weights_only
+ allowlist is exactly that, and it passed the route preflight: 200 OK, resident GPU model
+ evicted, then the child died on a raw UnpicklingError. That is precisely the outcome the
+ module docstring promises this preflight prevents, so pay the load here, on the one
+ bundle a user actually asked to resume. These are MB-scale files and this runs in a
+ worker thread."""
+ loaded = LoadedCheckpoint(path = path, manifest = manifest)
+ files = manifest.get("files")
+ for role in (files or {}) if isinstance(files, dict) else ():
+ try:
+ if role in ("adapter", "ema"):
+ loaded.tensors(role)
+ else:
+ state = loaded.torch_state(role)
+ if role == "rng" and not (
+ isinstance(state, dict) and state.get("torch_cpu") is not None
+ ):
+ # An rng file with no torch state restores nothing torch draws from, which
+ # is every latent, noise and timestep the loop asks for.
+ raise ResumeError(
+ f"'{path.name}' carries no torch random-number state, so the run "
+ "would continue on a different random stream. Resume from an earlier "
+ "checkpoint, or start a new run."
+ )
+ except ResumeError:
+ raise
+ except Exception as error: # noqa: BLE001 -- any unreadable state file is a refusal
+ raise ResumeError(
+ f"The '{role}' file in '{path.name}' could not be read back "
+ f"({type(error).__name__}), so this checkpoint cannot be resumed."
+ ) from error
+
+
+def preflight_resume(
+ path_value: str, *, identity: CheckpointIdentity, target_steps: int
+) -> tuple[str, int]:
+ """Validate a resume request and return ``(checkpoint_dir, resumed_step)``.
+
+ Called by the start route BEFORE the resident GPU model is evicted, and again inside
+ the trainer, so a rejected resume never costs the user their loaded pipeline. Raises
+ ResumeError with a message written for the user.
+
+ ``identity`` may leave ``dataset_fingerprint`` unset on the first (pre-discovery) pass;
+ that comparison is then skipped and re-run once the images are known."""
+ root = resolve_resume_dir(path_value)
+ # An explicit checkpoint-<N> directory resumes exactly that step; a run directory takes
+ # its newest complete bundle.
+ #
+ # The name alone does not settle which it is. An adapter can legitimately be called
+ # "checkpoint-2026", and its output directory then matches the bundle pattern while
+ # containing checkpoint-11 rather than a trainer_state.json of its own -- read as an
+ # explicit bundle it is simply rejected, with the real checkpoint sitting inside it. So the
+ # explicit branch is taken only when the path IS a valid bundle.
+ explicit = read_checkpoint(root) if checkpoint_step(root) >= 0 else None
+ candidates: list[tuple[Path, dict]]
+ if explicit is not None:
+ candidates = [(root, explicit)]
+ else:
+ candidates = iter_valid_checkpoints(root)
+ if not candidates and checkpoint_step(root) >= 0:
+ # Named like a bundle, is not one, and holds no bundles either: the original
+ # message is the accurate one.
+ raise ResumeError(
+ f"'{root.name}' is not a complete training checkpoint (it is missing files, "
+ "or was left behind by an interrupted save)."
+ )
+ if not candidates:
+ raise ResumeError(
+ "No complete training checkpoint was found for this run, so there is nothing to "
+ "resume from. Start a new run instead."
+ )
+ # Newest first, and a failure here is not the end of the search when a DIRECTORY was given:
+ # the header scan that produced this list is deliberately cheap, so the newest bundle can
+ # fail torch.load or turn out to be missing required state while the retained older one is
+ # perfectly good. Stopping at the first failure made the retention policy pointless. An
+ # EXPLICIT bundle has no alternatives, so its first failure is still the answer.
+ first_error: Optional[ResumeError] = None
+ for path, manifest in candidates:
+ try:
+ return _validated_resume(path, manifest, identity, target_steps)
+ except ResumeError as exc:
+ # "Already at the target" is an answer, not a damaged bundle. Falling past it
+ # walked back to checkpoint-400 of a run that finished at 500 and retrained
+ # completed work -- the exact rollback the fence exists to prevent. Only a bundle
+ # that cannot be USED is a reason to try the retained one behind it.
+ if getattr(exc, "terminal", False):
+ raise
+ if first_error is None:
+ first_error = exc
+ assert first_error is not None
+ raise first_error
+
+
+def _terminal(error: ResumeError) -> ResumeError:
+ """Mark a refusal as final: it describes the REQUEST, not a damaged bundle, so the directory
+ scan must not walk past it to an older checkpoint."""
+ error.terminal = True # type: ignore[attr-defined]
+ return error
+
+
+def _validated_resume(
+ path: Path, manifest: dict[str, Any], identity: CheckpointIdentity, target_steps: int
+) -> tuple[str, int]:
+ """The full per-bundle gate: identity, required state, and a real load of every file."""
+ saved = CheckpointIdentity.from_dict(manifest.get("identity"))
+ if saved is None:
+ raise ResumeError(
+ "This checkpoint does not record what it was trained from, so it cannot be "
+ "safely resumed."
+ )
+ reason = saved.mismatch_reason(identity)
+ if reason:
+ raise ResumeError(reason)
+ # After the identity gate, so a mismatched bundle still fails fast on the cheap check.
+ _assert_required_state(path, manifest)
+ _assert_optimizer_buildable(path, manifest)
+ _assert_loadable(path, manifest)
+ step = int(manifest.get("global_step") or 0)
+ if target_steps and step >= int(target_steps):
+ # Terminal: the newest bundle having nothing left to train says nothing is WRONG with
+ # it, so the directory scan must stop here rather than offering the retained older one.
+ raise _terminal(
+ ResumeError(
+ f"This checkpoint is already at step {step} of {int(target_steps)}, so there "
+ "is nothing left to train. Raise the step count to continue it."
+ )
+ )
+ return str(path), step
+
+
+# ── loading ───────────────────────────────────────────────────────────────────
+@dataclass
+class LoadedCheckpoint:
+ """A validated bundle, with its tensors read lazily so a preflight never pays for them."""
+
+ path: Path
+ manifest: dict[str, Any]
+
+ @property
+ def step(self) -> int:
+ return int(self.manifest.get("global_step") or 0)
+
+ @property
+ def target_steps(self) -> int:
+ return int(self.manifest.get("target_steps") or 0)
+
+ @property
+ def ema_updates(self) -> int:
+ return int(self.manifest.get("ema_updates") or 0)
+
+ @property
+ def optimizer_class(self) -> Optional[str]:
+ value = self.manifest.get("optimizer_class")
+ return str(value) if value else None
+
+ @property
+ def optimizer_param_names(self) -> Optional[list[str]]:
+ """The trainable names in the order the optimizer held them, or None on a bundle from
+ before this was recorded (which skips the check rather than failing it)."""
+ value = self.manifest.get("optimizer_param_names")
+ if not isinstance(value, list) or not value:
+ return None
+ return [str(name) for name in value]
+
+ @property
+ def progress(self) -> dict[str, Any]:
+ state = self.manifest.get("progress")
+ return state if isinstance(state, dict) else {}
+
+ @property
+ def running_loss(self) -> float:
+ """The loss total accumulated up to ``step``, so a resumed run's reported average
+ stays an average over the WHOLE run rather than restarting at the resume point."""
+ try:
+ return float(self.progress.get("running_loss") or 0.0)
+ except (TypeError, ValueError):
+ return 0.0
+
+ @property
+ def sampler_state(self) -> Optional[dict[str, Any]]:
+ state = self.manifest.get("sampler")
+ return state if isinstance(state, dict) else None
+
+ @property
+ def rng_json(self) -> Optional[dict[str, Any]]:
+ state = self.manifest.get("rng")
+ return state if isinstance(state, dict) else None
+
+ def _file(self, role: str) -> Optional[Path]:
+ files = self.manifest.get("files")
+ name = files.get(role) if isinstance(files, dict) else None
+ if not isinstance(name, str) or not name or Path(name).name != name:
+ return None
+ candidate = self.path / name
+ return candidate if candidate.is_file() else None
+
+ def tensors(
+ self,
+ role: str,
+ device: str = "cpu",
+ ) -> dict[str, Any]:
+ """The safetensors bundle for ``role`` (``adapter`` / ``ema``), or {}."""
+ from safetensors.torch import load_file
+
+ path = self._file(role)
+ return load_file(str(path), device = device) if path is not None else {}
+
+ def torch_state(self, role: str) -> Optional[Any]:
+ """A ``torch.save``d state dict (``optimizer`` / ``scheduler`` / ``rng``), or None.
+
+ Loaded with ``weights_only = True``: these files are written by Studio into its own
+ outputs directory, but a resume path is client-supplied, so the loader must never be
+ able to execute pickled code. Verified to round-trip bitsandbytes AdamW8bit state,
+ whose quantized moments and maps are plain uint8/fp32 tensors."""
+ import torch
+
+ path = self._file(role)
+ if path is None:
+ return None
+ return torch.load(str(path), map_location = "cpu", weights_only = True)
+
+
+def load_checkpoint(path: str | os.PathLike[str]) -> LoadedCheckpoint:
+ """Open a bundle that ``preflight_resume`` already accepted. Raises ResumeError if it
+ became unreadable in between (a concurrent delete, a half-mounted volume)."""
+ directory = Path(path).expanduser()
+ manifest = read_checkpoint(directory)
+ if manifest is None:
+ raise ResumeError(
+ f"The training checkpoint at '{directory}' could not be read; it may have been "
+ "deleted or damaged since the run started."
+ )
+ return LoadedCheckpoint(path = directory, manifest = manifest)
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index fe4124a894f..1c03917a58c 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -58,6 +58,20 @@ from core.training.diffusion_train_common import (
PermutationBatchSampler,
repo_is_prequantized,
resolve_train_steps,
+ restore_resume_state,
+ write_resume_checkpoint,
+)
+from core.training.diffusion_checkpoint import (
+ clear_own_checkpoints,
+ discard_preexisting_checkpoints,
+ retire_own_checkpoints,
+ resumed_into_this_dir,
+ snapshot_checkpoints,
+ identity_for_config,
+ with_cache_mode,
+ with_resolved_base_precision,
+ with_resolved_revision,
+ preflight_resume,
)
from core.training.diffusion_train_extras import (
LoRAEMA,
@@ -1481,7 +1495,12 @@ def run_dit_lora_training(
on_event: Optional[EventCb] = None,
should_stop: Optional[StopCb] = None,
) -> str:
- """Train a flow-matching DiT LoRA (FLUX.1 / FLUX.2 / Qwen-Image / Z-Image / Krea 2) and export it."""
+ """Train a flow-matching DiT LoRA (FLUX.1 / FLUX.2 / Qwen-Image / Z-Image / Krea 2) and export it.
+
+ Resumable: ``cfg.resume_from_checkpoint`` restores the adapter, optimizer moments, LR
+ position, EMA shadow, sampler cycle and RNG streams from a ``checkpoint-<N>`` bundle,
+ and the loop runs steps N+1..train_steps (the TARGET TOTAL). A stop-and-save and every
+ ``cfg.save_steps`` interval write such a bundle."""
cfg = config.normalized()
spec = _SPECS.get(cfg.resolved_family)
if spec is None:
@@ -1530,11 +1549,32 @@ def run_dit_lora_training(
)
# Resolve num_epochs into a concrete train_steps now the dataset size is known, and rebind cfg so every downstream read agrees.
cfg = replace(cfg, train_steps = resolve_train_steps(cfg, len(pairs)), num_epochs = 0)
+ # Validate a resume request against this run's identity BEFORE the multi-GB phased load, so
+ # a mismatched checkpoint fails in seconds. The identity uses the RESOLVED LoRA targets,
+ # which for a DiT family are the spec's, not the generic default the config carries.
+ identity = identity_for_config(
+ cfg,
+ dataset_pairs = pairs,
+ resolved_targets = _select_lora_targets(cfg.lora_target_modules, spec.lora_targets),
+ )
+ if cfg.resume_from_checkpoint:
+ preflight_resume(
+ cfg.resume_from_checkpoint, identity = identity, target_steps = cfg.train_steps
+ )
_emit(on_event, "model_load_started", num_images = len(pairs))
if _check_stop():
out_dir = Path(cfg.output_dir).expanduser()
_emit(
- on_event, "complete", output_dir = str(out_dir), lora_path = None, stopped = True, steps_run = 0
+ on_event,
+ "complete",
+ output_dir = str(out_dir),
+ lora_path = None,
+ stopped = True,
+ steps_run = 0,
+ # Same disposition the full path reports. A stop with save=false is a DISCARD
+ # however early it lands, and without it the resume fallback offers the source
+ # bundle back as though the attempt were still live.
+ discarded = not save_on_stop,
)
return str(out_dir)
@@ -1551,12 +1591,15 @@ def run_dit_lora_training(
on_event,
_check_stop,
lambda: save_on_stop,
+ identity,
)
finally:
_restore_perf_flags(perf_snap)
-def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_stop, _save_on_stop):
+def _train_dit(
+ cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_stop, _save_on_stop, identity
+):
"""The body of ``run_dit_lora_training``, split out so the backend perf flags are
snapshot/restored around it in exactly one place."""
import torch
@@ -1646,6 +1689,10 @@ def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_sto
lora_path = None,
stopped = True,
steps_run = 0,
+ # As above: a discard is a discard however early the stop lands.
+ # _save_on_stop is the accessor this function is handed; the flag itself
+ # lives in the caller's scope.
+ discarded = not _save_on_stop(),
)
return str(out_dir)
if latent_cache is not None and vae is not None:
@@ -1731,25 +1778,109 @@ def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_sto
)
_emit(on_event, "model_load_completed", compiled = compiled, base_precision = base_precision)
+ # See the SDXL trainer: the base is on disk now, so its commit can be read and written into
+ # every bundle this run saves. The identity built before the load says "unresolved" on the
+ # first run of an uncached repo, and an unresolved revision is not comparable, so a later
+ # resume could not tell that the repo had moved underneath it.
+ identity = with_resolved_revision(identity, cfg.base_model)
+ # See the SDXL trainer: the cache path the loop actually took, not the one requested.
+ identity = with_cache_mode(identity, latent_cache is not None)
+ # ...and the precision the frozen base ended up in. base_precision is still the request at
+ # this point ("auto" resolves here, and a failed fp8/mxfp8 conversion has already fallen
+ # back to bf16), so without this a bundle records a base it was never trained against.
+ identity = with_resolved_base_precision(identity, base_precision)
transformer.train()
n_images = len(image_paths)
batch_size = cfg.train_batch_size
# Permutation-cycle index sampler (shared with the SDXL trainer): visits every image once per cycle, so a short run covers the whole dataset. Uses the loop's own rng to stay seed-deterministic.
index_sampler = PermutationBatchSampler(n_images, rng)
+
+ # Restore a previous run (adapter, optimizer moments, LR position, EMA shadow, sampler cycle,
+ # RNG streams) before the loop, so it picks up at `resumed + 1`. None for a fresh run.
+ rng_streams = {"loop": rng, "variant": variant_rng}
+ restored = restore_resume_state(
+ cfg,
+ model = transformer,
+ optimizer = optimizer,
+ lr_scheduler = lr_sched,
+ identity = identity,
+ on_event = on_event,
+ ema = ema,
+ sampler = index_sampler,
+ rng_streams = rng_streams,
+ )
+ resumed = restored.step if restored is not None else 0
+ # Whether this run's source bundle lives in THIS directory. Resuming from
+ # directory A into a reused output_dir B leaves B's existing bundles as foreign
+ # as they would be for a fresh run -- so the first save has to clear them, or a
+ # higher-numbered one survives and a later resume by B picks it over this run.
+ resumed_here = bool(resumed) and resumed_into_this_dir(cfg, out_dir)
+ # The bundles that were already here when this run started, so a discard below
+ # removes only what this run wrote. A resumed run shares its source's directory.
+ preexisting_checkpoints = snapshot_checkpoints(out_dir)
+ if restored is not None:
+ was = restored.progress.get("resolved_base_precision")
+ if was and was != base_precision:
+ # Not fatal: the LoRA tensors and their optimizer moments are precision-independent,
+ # only the frozen base's numerics change. But base_precision="auto" picks from free
+ # VRAM, so this can happen silently and is worth saying out loud.
+ _emit(
+ on_event,
+ "warning",
+ message = (
+ f"Resuming a checkpoint trained with a {was} base in {base_precision}; "
+ f"set base_precision explicitly to keep them identical."
+ ),
+ )
+
stopped = False
- running_loss = 0.0
+ # Carried over so avg_loss stays an average over the whole run, not just since the resume.
+ running_loss = restored.running_loss if restored is not None else 0.0
peak_gb = 0.0
t_start = time.time()
t_steady = None
- done = 0
+ # Starts at the resumed step so a no-op resume still reports the real step.
+ done = resumed
+
+ def _save_checkpoint(step: int) -> None:
+ # Outcome is reported by write_resume_checkpoint's own checkpoint_saved /
+ # checkpoint_failed events, so a run that crashes after a save is still known to be
+ # resumable (and one whose save failed is still known to be blocked).
+ _written, _error = write_resume_checkpoint(
+ cfg,
+ step = step,
+ model = transformer,
+ optimizer = optimizer,
+ lr_scheduler = lr_sched,
+ identity = identity,
+ on_event = on_event,
+ ema = ema,
+ sampler = index_sampler,
+ rng_streams = rng_streams,
+ # base_precision="auto" resolves from free VRAM at load time, so the identity (which
+ # records the REQUESTED mode) cannot tell nf4 from bf16 across two "auto" runs.
+ # Recorded here so a resume can at least report the change.
+ progress = {"running_loss": running_loss, "resolved_base_precision": base_precision},
+ # NOT discard_existing. A fresh run does own its output dir, but deleting the
+ # previous run's bundles at the FIRST periodic save spends them before this run
+ # has produced anything: "stop without saving" then removes only what this run
+ # wrote, leaves the previous adapter in place, and the run it belonged to is
+ # unresumable -- cancelling a retrain destroyed the thing being retrained. The
+ # clear happens on the completion path instead, once the new adapter is saved.
+ discard_existing = False,
+ # And the bundles that were here before this run: a branched resume must not
+ # prune the higher-numbered checkpoints it did not write.
+ preexisting = preexisting_checkpoints,
+ )
+
# bf16 autocast around the forward + loss, matching the diffusers dreambooth scripts: it reconciles the fp32 LoRA params with the bnb 4-bit base matmuls. Without it the 4-bit backward on FLUX dies.
autocast = (
torch.autocast(device_type = "cuda", dtype = torch.bfloat16)
if device == "cuda"
else nullcontext()
)
- for opt_step in range(cfg.train_steps):
+ for opt_step in range(resumed, cfg.train_steps):
optimizer.zero_grad(set_to_none = True)
step_loss = 0.0
for _ in range(cfg.gradient_accumulation_steps):
@@ -1820,17 +1951,20 @@ def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_sto
running_loss += step_loss
done = opt_step + 1
now = time.time()
- if done == 1:
+ # Rates count only the steps THIS process ran, so a resumed run does not divide by
+ # steps it never executed.
+ ran_here = done - resumed
+ if ran_here == 1:
# Step 1 pays the one-time costs (cudnn autotune, compile warmup), so the reported rate starts after it.
t_steady = now
if done % cfg.log_every == 0 or done == cfg.train_steps:
if device == "cuda":
peak_gb = round(torch.cuda.max_memory_allocated() / 1e9, 2)
per_step = batch_size * cfg.gradient_accumulation_steps
- if t_steady is not None and done > 1:
- sps = round((done - 1) * per_step / max(now - t_steady, 1e-6), 3)
+ if t_steady is not None and ran_here > 1:
+ sps = round((ran_here - 1) * per_step / max(now - t_steady, 1e-6), 3)
else:
- sps = round(done * per_step / max(now - t_start, 1e-6), 3)
+ sps = round(ran_here * per_step / max(now - t_start, 1e-6), 3)
_emit(
on_event,
"progress",
@@ -1843,7 +1977,17 @@ def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_sto
samples_per_second = sps,
peak_memory_gb = peak_gb or None,
)
- if _check_stop():
+ stop_now = _check_stop()
+ # Periodic resume point. Skipped on the final step (a finished run has nothing left to
+ # resume) and when stopping, since the stop path writes one at the exact step.
+ if (
+ not stop_now
+ and cfg.save_steps
+ and done % cfg.save_steps == 0
+ and done < cfg.train_steps
+ ):
+ _save_checkpoint(done)
+ if stop_now:
stopped = True
break
@@ -1852,10 +1996,16 @@ def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_sto
ema_path: Optional[str] = None
if not (stopped and not _save_on_stop()):
out_dir.mkdir(parents = True, exist_ok = True)
+ # Stopping early is exactly when the run should be resumable, so write the bundle BEFORE
+ # the adapter export: if that export then fails, the run still comes back. A completed run
+ # has nothing left to resume.
+ if stopped and done > 0:
+ _save_checkpoint(done)
layers = get_peft_model_state_dict(transformer)
spec.save(pipe, str(out_dir), layers)
lora_path = str(out_dir / DEFAULT_LORA_FILENAME)
- catalog_path = _publish_to_lora_catalog(lora_path, cfg)
+ # ``done`` (the step reached), not cfg.train_steps: a stop at 11/500 must not advertise 500.
+ catalog_path = _publish_to_lora_catalog(lora_path, cfg, done)
if ema is not None and ema.updates > 0:
try:
# Report the adapter FILE, like lora_path, so a caller can load it directly.
@@ -1863,6 +2013,30 @@ def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_sto
ema_path = str(Path(ema_dir) / DEFAULT_LORA_FILENAME)
except Exception as exc: # noqa: BLE001 -- the primary adapter is already saved
_emit(on_event, "warning", message = f"EMA adapter save failed: {exc}")
+ if not stopped:
+ # Same as the LoRA trainer: a completed run has nothing to resume, and the final
+ # iteration writes no bundle, so save_steps leaves the run's own checkpoint-400
+ # behind for a later resume to roll back to. An earlier run's bundles stay.
+ retire_own_checkpoints(out_dir, preexisting_checkpoints, resumed_here = resumed_here)
+ elif not resumed_here:
+ # Stopped WITH save on a fresh retrain: the stop bundle is a LOWER step than
+ # the leftovers of the earlier run in this directory, and resume-by-directory
+ # picks the newest by step -- so those would outrank the partial just saved
+ # and continue the wrong training. A resumed run keeps what it found.
+ discard_preexisting_checkpoints(out_dir, preexisting_checkpoints)
+ else:
+ # Discarded: the user asked to throw this run away. Before periodic checkpoints
+ # existed a discard left nothing behind, because the output directory was only ever
+ # created inside this save gate. save_steps now writes bundles as the run goes, so
+ # without this a discard leaves up to save_total_limit copies of the optimizer state
+ # in a directory the user never got an artifact from -- invisible to every scanner,
+ # unresumable (the record is marked discarded), and with no delete path in the UI.
+ clear_own_checkpoints(out_dir, preexisting_checkpoints)
+ try:
+ out_dir.rmdir()
+ except OSError:
+ # Not ours to remove if anything else is in it (a previous run's adapter).
+ pass
_emit(
on_event,
"complete",
@@ -1875,6 +2049,10 @@ def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_sto
stopped = stopped,
steps_run = done if cfg.train_steps else 0,
wall_seconds = round(time.time() - t_start, 1),
+ resumed_from_step = resumed or None,
+ # "Stop without saving" discards the run, so its own periodic checkpoints must not keep
+ # offering to continue it.
+ discarded = bool(stopped and not _save_on_stop()),
)
return str(out_dir)
@@ -1882,9 +2060,16 @@ def _train_dit(cfg, spec, pairs, rng, device, weight_dtype, on_event, _check_sto
def _make_optimizer(params, lr):
"""8-bit AdamW (bitsandbytes) when available -- half the optimizer state, no accuracy
regression for LoRA -- else torch AdamW, fused on CUDA (with a fallback when this
- build/device lacks the fused kernel)."""
+ build/device lacks the fused kernel).
+
+ UNSLOTH_DIFFUSION_FP32_OPTIM forces plain (non-fused) AdamW, as it does for SDXL: the
+ accuracy guard wants the reference optimizer, and a host where the override means one
+ thing for one trainer and nothing for the other cannot answer "can this checkpoint be
+ resumed here" before the run starts."""
import torch
+ if os.environ.get("UNSLOTH_DIFFUSION_FP32_OPTIM", "") in ("1", "true"):
+ return torch.optim.AdamW(params, lr = lr)
try:
import bitsandbytes as bnb
return bnb.optim.AdamW8bit(params, lr = lr)
diff --git a/studio/backend/core/training/diffusion_lora_trainer.py b/studio/backend/core/training/diffusion_lora_trainer.py
index 0002ccecd52..ce76d1c39bc 100644
--- a/studio/backend/core/training/diffusion_lora_trainer.py
+++ b/studio/backend/core/training/diffusion_lora_trainer.py
@@ -66,6 +66,19 @@ from core.training.diffusion_train_common import ( # noqa: F401
get_trainer,
PermutationBatchSampler,
resolve_train_steps,
+ restore_resume_state,
+ write_resume_checkpoint,
+)
+from core.training.diffusion_checkpoint import (
+ clear_own_checkpoints,
+ discard_preexisting_checkpoints,
+ retire_own_checkpoints,
+ resumed_into_this_dir,
+ snapshot_checkpoints,
+ identity_for_config,
+ with_cache_mode,
+ with_resolved_revision,
+ preflight_resume,
)
@@ -282,7 +295,13 @@ def run_diffusion_lora_training(
Emits ``model_load_started`` / ``model_load_completed`` / ``progress`` (step, loss) /
``complete`` (output_dir, lora_path) events via ``on_event``; ``error`` is emitted by
the process adapter. Honours ``should_stop`` (checked before model load and between
- optimizer steps); a stop saves a partial adapter unless it carries ``save=False``."""
+ optimizer steps); a stop saves a partial adapter unless it carries ``save=False``.
+
+ Resumable: ``cfg.resume_from_checkpoint`` restores the adapter, the optimizer moments,
+ the LR-schedule position, the sampler cycle and every RNG stream from a
+ ``checkpoint-<N>`` bundle, and the loop then runs steps N+1..train_steps
+ (``train_steps`` is the TARGET TOTAL, not an additional budget). A stop-and-save and
+ every ``cfg.save_steps`` interval write such a bundle."""
import torch
import torch.nn.functional as F
from diffusers import DDPMScheduler, StableDiffusionXLPipeline
@@ -328,6 +347,15 @@ def run_diffusion_lora_training(
)
# Resolve num_epochs into a concrete train_steps now the dataset size is known, and rebind cfg so every downstream read agrees.
cfg = replace(cfg, train_steps = resolve_train_steps(cfg, len(pairs)), num_epochs = 0)
+ # Validate a resume request against this run's identity BEFORE the multi-GB base model
+ # load, so a mismatched checkpoint fails in seconds instead of after the download.
+ identity = identity_for_config(cfg, dataset_pairs = pairs)
+ if cfg.resume_from_checkpoint:
+ preflight_resume(
+ cfg.resume_from_checkpoint,
+ identity = identity,
+ target_steps = cfg.train_steps,
+ )
_emit(on_event, "model_load_started", num_images = len(pairs))
# Honour a stop requested before the (slow) base model load.
@@ -340,6 +368,10 @@ def run_diffusion_lora_training(
lora_path = None,
stopped = True,
steps_run = 0,
+ # Same disposition the full path reports. A stop with save=false is a DISCARD
+ # however early it lands, and without it the resume fallback offers the source
+ # bundle back as though the attempt were still live.
+ discarded = not save_on_stop,
)
return str(out_dir)
@@ -435,6 +467,8 @@ def run_diffusion_lora_training(
lora_path = None,
stopped = True,
steps_run = 0,
+ # As above: a discard is a discard however early the stop lands.
+ discarded = not save_on_stop,
)
return str(out_dir)
else:
@@ -451,6 +485,14 @@ def run_diffusion_lora_training(
variant_rng = random.Random(cfg.seed + 1)
_emit(on_event, "model_load_completed", compiled = compiled)
+ # The base is on disk now, so its commit can finally be read: the identity above was
+ # built before the load and records "unresolved" on the first run of an uncached repo,
+ # which no later resume could then enforce. Only ever adds the constraint.
+ identity = with_resolved_revision(identity, cfg.base_model)
+ # And the cache path the loop actually took, which the request does not settle: the
+ # env override and the over-budget fallback both turn it off, and the two paths draw
+ # crops and flips from different RNG streams.
+ identity = with_cache_mode(identity, latent_cache is not None)
# Permutation-cycle index sampler: each image is visited once per cycle before any repeat, so a short run does not leave a small dataset partly unseen.
index_sampler = PermutationBatchSampler(len(pairs), rng)
@@ -461,15 +503,73 @@ def run_diffusion_lora_training(
chosen = [pairs[i] for i in idx]
return idx, [c[0] for c in chosen], [c[1] for c in chosen]
+ # Restore a previous run's state (adapter, optimizer moments, LR position, sampler cycle,
+ # RNG streams) BEFORE the loop, so `resumed` is the last completed step and the loop
+ # picks up at resumed + 1. Zero for a fresh run; a mismatch raises out to the adapter.
+ rng_streams = {"loop": rng, "variant": variant_rng}
+ restored = restore_resume_state(
+ cfg,
+ model = unet,
+ optimizer = optimizer,
+ lr_scheduler = lr_sched,
+ identity = identity,
+ on_event = on_event,
+ sampler = index_sampler,
+ rng_streams = rng_streams,
+ )
+ resumed = restored.step if restored is not None else 0
+ # Bound HERE, not at the export below: the checkpoint scan and the periodic saves both
+ # need it, and the two earlier assignments live inside early-return branches -- so on
+ # every normal run this read came before any binding at all.
+ out_dir = Path(cfg.output_dir).expanduser()
+ # Whether this run's source bundle lives in THIS directory. Resuming from
+ # directory A into a reused output_dir B leaves B's existing bundles as foreign
+ # as they would be for a fresh run -- so the first save has to clear them, or a
+ # higher-numbered one survives and a later resume by B picks it over this run.
+ resumed_here = bool(resumed) and resumed_into_this_dir(cfg, out_dir)
+ # The bundles that were already here when this run started, so a discard below
+ # removes only what this run wrote. A resumed run shares its source's directory.
+ preexisting_checkpoints = snapshot_checkpoints(out_dir)
+
unet.train()
stopped = False
micro = 0
- running_loss = 0.0
+ # Carried over so avg_loss stays an average over the whole run, not just since the resume.
+ running_loss = restored.running_loss if restored is not None else 0.0
peak_gb = 0.0
t_start = time.time()
t_steady = None
- done = 0
- for opt_step in range(cfg.train_steps):
+ # Starts at the resumed step so a no-op resume (nothing left to train) still reports the real step.
+ done = resumed
+
+ def _save_checkpoint(step: int) -> None:
+ # Outcome is reported by write_resume_checkpoint's own checkpoint_saved /
+ # checkpoint_failed events, so a run that crashes after a save is still known to be
+ # resumable (and one whose save failed is still known to be blocked).
+ _written, _error = write_resume_checkpoint(
+ cfg,
+ step = step,
+ model = unet,
+ optimizer = optimizer,
+ lr_scheduler = lr_sched,
+ identity = identity,
+ on_event = on_event,
+ sampler = index_sampler,
+ rng_streams = rng_streams,
+ progress = {"running_loss": running_loss},
+ # NOT discard_existing. A fresh run does own its output dir, but deleting the
+ # previous run's bundles at the FIRST periodic save spends them before this run
+ # has produced anything: "stop without saving" then removes only what this run
+ # wrote, leaves the previous adapter in place, and the run it belonged to is
+ # unresumable -- cancelling a retrain destroyed the thing being retrained. The
+ # clear happens on the completion path instead, once the new adapter is saved.
+ discard_existing = False,
+ # And the bundles that were here before this run: a branched resume must not
+ # prune the higher-numbered checkpoints it did not write.
+ preexisting = preexisting_checkpoints,
+ )
+
+ for opt_step in range(resumed, cfg.train_steps):
optimizer.zero_grad(set_to_none = True)
step_loss = 0.0
for _ in range(cfg.gradient_accumulation_steps):
@@ -550,7 +650,10 @@ def run_diffusion_lora_training(
running_loss += step_loss
done = opt_step + 1
now = time.time()
- if done == 1:
+ # Rates count only the steps THIS process ran, so a run resumed at step 11 does not
+ # divide by 12 steps it never executed.
+ ran_here = done - resumed
+ if ran_here == 1:
# Step 1 pays the one-time costs (cudnn autotune, compile warmup), so the rate starts after it.
t_steady = now
if done % cfg.log_every == 0 or done == cfg.train_steps:
@@ -558,10 +661,12 @@ def run_diffusion_lora_training(
if device == "cuda":
peak_gb = round(torch.cuda.max_memory_allocated() / 1e9, 2)
per_step = cfg.train_batch_size * cfg.gradient_accumulation_steps
- if t_steady is not None and done > 1:
- samples_per_second = round((done - 1) * per_step / max(now - t_steady, 1e-6), 3)
+ if t_steady is not None and ran_here > 1:
+ samples_per_second = round(
+ (ran_here - 1) * per_step / max(now - t_steady, 1e-6), 3
+ )
else:
- samples_per_second = round(done * per_step / max(now - t_start, 1e-6), 3)
+ samples_per_second = round(ran_here * per_step / max(now - t_start, 1e-6), 3)
_emit(
on_event,
"progress",
@@ -575,16 +680,30 @@ def run_diffusion_lora_training(
peak_memory_gb = peak_gb or None,
)
- if _check_stop():
+ stop_now = _check_stop()
+ # Periodic resume point. Skipped on the final step (a finished run has nothing left
+ # to resume) and when stopping, since the stop path writes one at the exact step.
+ if (
+ not stop_now
+ and cfg.save_steps
+ and done % cfg.save_steps == 0
+ and done < cfg.train_steps
+ ):
+ _save_checkpoint(done)
+ if stop_now:
stopped = True
break
# Export the LoRA in diffusers format, unless cancelled with save disabled.
- out_dir = Path(cfg.output_dir).expanduser()
lora_path: Optional[str] = None
catalog_path: Optional[str] = None
if not (stopped and not save_on_stop):
out_dir.mkdir(parents = True, exist_ok = True)
+ # Stopping early is exactly when the run should be resumable, so write the bundle
+ # BEFORE the adapter export: if that export then fails, the run still comes back.
+ # A completed run has nothing left to resume.
+ if stopped and done > 0:
+ _save_checkpoint(done)
unet_lora = convert_state_dict_to_diffusers(get_peft_model_state_dict(unet))
StableDiffusionXLPipeline.save_lora_weights(
save_directory = str(out_dir),
@@ -594,7 +713,36 @@ def run_diffusion_lora_training(
)
lora_path = str(out_dir / DEFAULT_LORA_FILENAME)
# Mirror into loras/diffusion so the Images picker discovers it (its scan skips subdirs).
- catalog_path = _publish_to_lora_catalog(lora_path, cfg)
+ # ``done`` (the step reached), not cfg.train_steps: a stop at 11/500 must not advertise 500.
+ catalog_path = _publish_to_lora_catalog(lora_path, cfg, done)
+ if not stopped:
+ # A COMPLETED run has nothing to resume, and the last iteration deliberately
+ # writes no bundle -- so with save_steps on, the newest thing left in the
+ # directory is checkpoint-400 of a run that finished at 500. The preflight
+ # cannot see the run status, so a later resume with a raised target rolled the
+ # model, optimizer, scheduler, sampler and RNG back and retrained 401-500.
+ # Only this run's own bundles go; an earlier run's stay resumable.
+ retire_own_checkpoints(out_dir, preexisting_checkpoints, resumed_here = resumed_here)
+ elif not resumed_here:
+ # Stopped WITH save on a fresh retrain: the stop bundle is a LOWER step than
+ # the leftovers of the earlier run in this directory, and resume-by-directory
+ # picks the newest by step -- so those would outrank the partial just saved
+ # and continue the wrong training. A resumed run keeps what it found.
+ discard_preexisting_checkpoints(out_dir, preexisting_checkpoints)
+ else:
+ # Discarded: the user asked to throw this run away. Before periodic checkpoints
+ # existed a discard left nothing behind, because the output directory was only
+ # ever created inside this save gate. save_steps now writes bundles as the run
+ # goes, so without this a discard leaves up to save_total_limit copies of the
+ # optimizer state in a directory the user never got an artifact from -- invisible
+ # to every scanner, unresumable (the record is marked discarded), and with no
+ # delete path in the UI.
+ clear_own_checkpoints(out_dir, preexisting_checkpoints)
+ try:
+ out_dir.rmdir()
+ except OSError:
+ # Not ours to remove if anything else is in it (an earlier run's adapter).
+ pass
_emit(
on_event,
"complete",
@@ -605,6 +753,10 @@ def run_diffusion_lora_training(
base_model = cfg.base_model,
stopped = stopped,
steps_run = done if cfg.train_steps else 0,
+ resumed_from_step = resumed or None,
+ # "Stop without saving" discards the run, so its own periodic checkpoints must not
+ # keep offering to continue it.
+ discarded = bool(stopped and not save_on_stop),
)
return str(out_dir)
finally:
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index 75e0b64b81f..2273da37cfa 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -324,6 +324,31 @@ _DIT_TRAIN_FAMILIES = frozenset(
)
+def effective_mixed_precision(cfg: Any) -> str:
+ """The precision the SDXL trainer will actually run in, resolved the same way it resolves it.
+
+ A pre-Ampere card has no native bf16, so a bf16 request silently becomes fp16 there. Recording
+ the REQUEST in a checkpoint's identity let a bundle written in fp16 resume in bf16 on a newer
+ card (and the reverse), continuing restored optimizer moments under different frozen-base
+ numerics while reporting a clean resume. Shared so the start route and the trainer cannot
+ disagree about what a checkpoint was trained as.
+ """
+ import torch # noqa: PLC0415 -- keep the import list light for the training subprocess
+
+ requested = str(getattr(cfg, "mixed_precision", "") or "")
+ if str(getattr(cfg, "resolved_family", "") or "").strip().lower() in _DIT_TRAIN_FAMILIES:
+ # The DiT trainer does not read mixed_precision at all: weight_dtype is bf16 on CUDA and
+ # fp32 otherwise. Recording the REQUEST for those families put "fp16" or "no" in the
+ # identity of a run that executed in bf16, and a later bf16 resume of it was then
+ # rejected as a precision mismatch between two runs that ran identically.
+ return "bf16" if torch.cuda.is_available() else "no"
+ if not torch.cuda.is_available():
+ return "no"
+ if requested == "bf16" and not native_bf16_supported():
+ return "fp16"
+ return requested
+
+
def native_bf16_supported() -> bool:
"""True only when the live CUDA GPU provides NATIVE bf16 compute, not pre-Ampere emulation.
@@ -568,6 +593,14 @@ class DiffusionLoraConfig:
weighting_scheme: str = "none"
# How often to emit a progress event (in optimizer steps).
log_every: int = 1
+ # Periodic resume-checkpoint interval, in optimizer steps. 0 (the default) writes no periodic
+ # checkpoints; a stop-and-save always writes one regardless, so the Resume action stays available.
+ save_steps: int = 0
+ # How many checkpoint-<N> bundles to keep in the output dir; 0 keeps every one.
+ save_total_limit: int = 2
+ # Continue a previous run: the run's output_dir, or one of its checkpoint-<N> directories.
+ # The start route resolves and validates it before the trainer spawns.
+ resume_from_checkpoint: Optional[str] = None
# Optional explicit family override; None = detect from base_model. ``resolved_family`` is filled by normalized() with the trainer family that will run.
model_family: Optional[str] = None
resolved_family: str = "sdxl"
@@ -613,6 +646,25 @@ class DiffusionLoraConfig:
)
if not 1 <= int(self.cache_variants) <= 16:
raise ValueError("cache_variants must be between 1 and 16")
+ # Checkpointing knobs. Rejected here, before the route evicts resident GPU models, rather than deep in the loop.
+ try:
+ save_steps = int(self.save_steps or 0)
+ save_total_limit = int(self.save_total_limit or 0)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(
+ f"save_steps / save_total_limit must be whole numbers, got "
+ f"{self.save_steps!r} / {self.save_total_limit!r}"
+ ) from exc
+ if save_steps < 0:
+ raise ValueError("save_steps must be >= 0 (0 disables periodic checkpoints)")
+ if save_total_limit < 0:
+ raise ValueError("save_total_limit must be >= 0 (0 keeps every checkpoint)")
+ # A blank resume path (the Studio default when the field is present but unset) means "fresh run", not the outputs root.
+ resume_from_checkpoint = (
+ str(self.resume_from_checkpoint).strip()
+ if self.resume_from_checkpoint is not None
+ else ""
+ ) or None
try:
ema_decay = float(self.ema_decay or 0.0)
except (TypeError, ValueError) as exc:
@@ -696,6 +748,11 @@ class DiffusionLoraConfig:
targets = tuple(self.lora_target_modules) or DEFAULT_LORA_TARGETS
# A blank Hub token (the Studio default when none is configured) must load anonymously, not as an explicit empty credential.
token = self.hf_token.strip() if isinstance(self.hf_token, str) else self.hf_token
+ # A blank caption_column means the default, as the start route's own preflight already
+ # assumes ("or 'text'"). Without this the route and the trainer resolve different captions
+ # from a metadata.jsonl, so their dataset fingerprints disagree and a resume that the
+ # route accepted is then refused in the child -- after the GPU residents are freed.
+ caption_column = str(self.caption_column or "").strip() or "text"
return replace(
self,
learning_rate = learning_rate,
@@ -703,8 +760,12 @@ class DiffusionLoraConfig:
lora_target_modules = targets,
max_grad_norm = float(self.max_grad_norm),
hf_token = token or None,
+ caption_column = caption_column,
num_epochs = int(self.num_epochs),
cache_variants = int(self.cache_variants),
+ save_steps = save_steps,
+ save_total_limit = save_total_limit,
+ resume_from_checkpoint = resume_from_checkpoint,
cond_cache_dir = cond_cache_dir,
ema_decay = ema_decay,
compile_transformer = compile_transformer,
@@ -766,6 +827,53 @@ class PermutationBatchSampler:
self._pos += take
return out
+ def state_dict(self) -> dict[str, Any]:
+ """The position inside the current permutation cycle, for a resume checkpoint. The
+ order itself is stored (not just the position): it was drawn from the run's rng, and
+ restoring the rng alone would not reproduce a cycle that was already in progress."""
+ return {"n": self._n, "order": list(self._order), "pos": int(self._pos)}
+
+ def load_state_dict(self, state: Optional[dict[str, Any]]) -> bool:
+ """Restore a cycle saved by ``state_dict``. True when it was restored.
+
+ Refuses a state for a different dataset size (the resume preflight already rejects a
+ changed dataset; this keeps a manually edited checkpoint from indexing out of range)
+ and clamps a bad position. The BOOLEAN matters: silently leaving a fresh sampler in
+ place looks like a clean resume while the RNG -- already restored to a point after this
+ permutation was drawn -- generates a different order, so the run quietly reorders and
+ skips images.
+ """
+ if not isinstance(state, dict) or int(state.get("n") or 0) != self._n:
+ return False
+ order = state.get("order")
+ if not isinstance(order, (list, tuple)):
+ return False
+ try:
+ restored = [int(i) for i in order]
+ except (TypeError, ValueError):
+ return False
+ # A FULL permutation, or the initial empty state. A shortened or duplicate-carrying
+ # order is in range and the same length as nothing in particular: the cycle then
+ # reshuffles early or serves the same image twice, while the RNG has already been
+ # restored to a point after the original draw. That is the silent reorder this
+ # boolean exists to prevent, arriving through a truncated or hand-edited manifest
+ # instead of a missing one.
+ if restored and sorted(restored) != list(range(self._n)):
+ return False
+ self._order = restored
+ try:
+ pos = int(state.get("pos") or 0)
+ except (TypeError, ValueError):
+ return False
+ # A position outside 0..len(order) is not a rounding error, it is a damaged manifest,
+ # and clamping it re-serves the permutation from the top or ends the cycle early --
+ # behind an RNG already restored past the draw. The same silent repeat-or-skip the
+ # order check above refuses, so refuse it rather than quietly correcting it.
+ if not 0 <= pos <= len(self._order):
+ return False
+ self._pos = pos
+ return True
+
def discover_image_caption_pairs(
data_dir: str | os.PathLike[str],
@@ -1036,12 +1144,338 @@ def _assert_trusted_base_model(base_model: str) -> None:
_assert_local_base_is_pipeline(base_model)
-def _publish_to_lora_catalog(lora_path: str, cfg: DiffusionLoraConfig) -> Optional[str]:
+# ── resume checkpoints ────────────────────────────────────────────────────────
+# One writer and one reader for BOTH trainers, so an SDXL and a DiT run resume from the same
+# bundle shape. The family-specific part (the deployable adapter export) stays in the trainers.
+def trainable_state_dict(model: Any) -> dict[str, Any]:
+ """The trainable (LoRA) parameters of ``model``, keyed by parameter name.
+
+ Deliberately NOT the peft/diffusers export format: this is the checkpoint's private
+ copy of exactly the tensors the optimizer holds moments for, so restoring it and the
+ optimizer state together reproduces the run bit-for-bit. Parameter names are stable
+ across a re-attach and across regional torch.compile (which compiles submodules in
+ place without renaming), which is the same assumption ``LoRAEMA`` already makes."""
+ return {name: p.detach() for name, p in model.named_parameters() if p.requires_grad}
+
+
+def load_trainable_state_dict(model: Any, state: Optional[dict[str, Any]]) -> int:
+ """Copy a ``trainable_state_dict`` back into ``model`` in place, returning how many
+ parameters were restored. Copies rather than reassigns, so the optimizer's parameter
+ references (and their loaded moments) stay valid.
+
+ Every saved tensor must land. A partial match means the parameter NAMES moved (a different
+ adapter name, a wrapper that re-prefixes them), and because the optimizer state is keyed by
+ parameter INDEX it would still load cleanly -- leaving restored Adam moments and a restored
+ LR position driving freshly initialised LoRA weights, while the run reports a normal resume.
+ Raise instead."""
+ if not state:
+ return 0
+ import torch
+
+ restored = 0
+ trainable: set[str] = set()
+ with torch.no_grad():
+ for name, p in model.named_parameters():
+ if not p.requires_grad:
+ continue
+ trainable.add(name)
+ saved = state.get(name)
+ if saved is None:
+ continue
+ if tuple(saved.shape) != tuple(p.shape):
+ raise ValueError(
+ f"Checkpoint tensor '{name}' has shape {tuple(saved.shape)} but this run "
+ f"expects {tuple(p.shape)}; the LoRA configuration does not match."
+ )
+ p.copy_(saved.to(device = p.device, dtype = p.dtype))
+ restored += 1
+ # BOTH directions. Counting only the checkpoint's own tensors proves every saved tensor
+ # landed somewhere; it says nothing about a live trainable parameter the checkpoint never
+ # had. A truncated or hand-edited adapter file holding a strict SUBSET therefore passed,
+ # and the full optimizer state was then loaded on top: restored Adam moments driving
+ # freshly initialised weights, while the run reported a clean resume.
+ unsaved = sorted(trainable - set(state))
+ unknown = sorted(set(state) - trainable)
+ if unsaved or unknown:
+ detail = []
+ if unsaved:
+ detail.append(f"{len(unsaved)} not in the checkpoint (e.g. {', '.join(unsaved[:3])})")
+ if unknown:
+ detail.append(f"{len(unknown)} not in this run (e.g. {', '.join(unknown[:3])})")
+ raise ValueError(
+ f"This run has {len(trainable)} trainable tensors and the checkpoint has "
+ f"{len(state)}: {'; '.join(detail)}. The LoRA configuration does not match the one "
+ "it was saved from."
+ )
+ return restored
+
+
+def _json_safe_progress(progress: Optional[dict[str, Any]]) -> dict[str, Any]:
+ """Drop non-finite floats from the manifest's progress block. A diverged run pushes
+ ``running_loss`` to NaN/inf, which json.dumps writes as the JS-only NaN/Infinity tokens --
+ invalid strict JSON that a stricter reader (or a future consumer of these files) rejects."""
+ out: dict[str, Any] = {}
+ for key, value in (progress or {}).items():
+ if isinstance(value, float) and not math.isfinite(value):
+ continue
+ out[key] = value
+ return out
+
+
+def write_resume_checkpoint(
+ cfg: DiffusionLoraConfig,
+ *,
+ step: int,
+ model: Any,
+ optimizer: Any,
+ lr_scheduler: Any,
+ identity: Any,
+ on_event: Optional[EventCb] = None,
+ ema: Any = None,
+ sampler: Any = None,
+ rng_streams: Optional[dict[str, Any]] = None,
+ progress: Optional[dict[str, Any]] = None,
+ discard_existing: bool = False,
+ preexisting: Optional[Any] = None,
+) -> tuple[Optional[str], Optional[str]]:
+ """Write one resume bundle for the run, returning ``(checkpoint_path, error)``.
+
+ Never raises: a checkpoint failure must not lose a training run that is otherwise fine,
+ so the error is returned (and emitted as a warning) for the caller to report as
+ ``resume_blocked_reason``. Used for BOTH the periodic ``save_steps`` saves and the
+ stop-and-save, so the two produce identical state.
+
+ ``discard_existing`` is set on the FIRST write of a run that did not resume, so bundles
+ left in the output dir by an earlier run of the same adapter name cannot outrank it."""
+ from core.training.diffusion_checkpoint import capture_rng_state, save_checkpoint
+ try:
+ path = save_checkpoint(
+ output_dir = cfg.output_dir,
+ step = step,
+ adapter_state = trainable_state_dict(model),
+ identity = identity,
+ target_steps = cfg.train_steps,
+ optimizer = optimizer,
+ lr_scheduler = lr_scheduler,
+ ema_state = ema.state_dict() if ema is not None else None,
+ ema_updates = int(getattr(ema, "updates", 0) or 0) if ema is not None else 0,
+ rng = capture_rng_state(rng_streams),
+ sampler_state = sampler.state_dict() if sampler is not None else None,
+ progress = _json_safe_progress(progress),
+ save_total_limit = int(cfg.save_total_limit or 0),
+ discard_existing = discard_existing,
+ # What this run resumed from, so the "step already written" shortcut can tell
+ # "we are re-saving the bundle we started from" apart from "another run left a
+ # bundle at this number".
+ source_checkpoint = getattr(cfg, "resume_from_checkpoint", None),
+ # Bundles that predated this run are never pruned to make room for its own: a
+ # branched resume beside higher-numbered checkpoints used to delete them on the
+ # first save, irreversibly.
+ preexisting = preexisting,
+ )
+ # Reported per save, not only at the end: a run that later CRASHES must still be known to
+ # have resumable state (and a run whose write failed must still be known to be blocked).
+ _emit(on_event, "checkpoint_saved", checkpoint_path = path, step = step)
+ return path, None
+ except Exception as exc: # noqa: BLE001 -- reported, never fatal to the run
+ message = f"Could not write a resume checkpoint at step {step}: {exc}"
+ _emit(on_event, "checkpoint_failed", step = step, message = message)
+ return None, message
+
+
+def _reapply_lr_schedule(optimizer: Any, lr_scheduler: Any) -> None:
+ """Recompute the learning rate for the NEXT step from the LIVE schedule.
+
+ ``optimizer.load_state_dict`` restores the rate the checkpoint was written with and
+ ``LRScheduler.load_state_dict`` restores only the position, never re-evaluating the lambda,
+ so the first step after a resume runs at the OLD schedule's value. That is invisible while
+ ``train_steps`` is unchanged (the UI always replays it) but wrong the moment the target
+ moves -- continuing a finished cosine run by raising the step count would take its first
+ step at lr 0.0, leaving every parameter untouched.
+
+ Only for the closed-form ``LambdaLR`` diffusers' ``get_scheduler`` returns, and evaluated
+ from its own public ``lr_lambdas`` / ``base_lrs`` / ``last_epoch`` rather than ``get_lr()``
+ (which warns when called outside a step). A chainable scheduler derives its next rate from
+ the current one, so re-applying it there would double-step. Best-effort: a schedule we
+ cannot re-evaluate keeps the restored value."""
+ try:
+ import torch
+
+ if not isinstance(lr_scheduler, torch.optim.lr_scheduler.LambdaLR):
+ return
+ values = [
+ float(base * lmbda(lr_scheduler.last_epoch))
+ for lmbda, base in zip(lr_scheduler.lr_lambdas, lr_scheduler.base_lrs)
+ ]
+ for group, value in zip(optimizer.param_groups, values):
+ group["lr"] = value
+ lr_scheduler._last_lr = values
+ except Exception: # noqa: BLE001 -- keeping the restored rate is a safe fallback
+ pass
+
+
+def restore_resume_state(
+ cfg: DiffusionLoraConfig,
+ *,
+ model: Any,
+ optimizer: Any,
+ lr_scheduler: Any,
+ identity: Any,
+ on_event: Optional[EventCb] = None,
+ ema: Any = None,
+ sampler: Any = None,
+ rng_streams: Optional[dict[str, Any]] = None,
+) -> Any:
+ """Load ``cfg.resume_from_checkpoint`` into a freshly built run.
+
+ Returns the ``LoadedCheckpoint`` (whose ``.step`` is the last COMPLETED optimizer step,
+ so the loop restarts at ``.step``), or None when no resume was requested.
+
+ Re-runs the full preflight in the child: the start route already validated the request
+ before evicting the GPU, but the trainer must not trust a config it did not check
+ itself. Raises ResumeError (a ValueError) on a mismatch, which the process adapter
+ surfaces as the run's error message."""
+ if not cfg.resume_from_checkpoint:
+ return None
+ from core.training.diffusion_checkpoint import (
+ ResumeError,
+ load_checkpoint,
+ optimizer_key,
+ preflight_resume,
+ restore_rng_state,
+ )
+
+ path, step = preflight_resume(
+ cfg.resume_from_checkpoint, identity = identity, target_steps = cfg.train_steps
+ )
+ ckpt = load_checkpoint(path)
+ load_trainable_state_dict(model, ckpt.tensors("adapter"))
+ optimizer_state = ckpt.torch_state("optimizer")
+ if optimizer_state is not None:
+ # The trainers pick their optimizer from the HOST (bitsandbytes present, a fused kernel
+ # available, UNSLOTH_DIFFUSION_FP32_OPTIM), not from the config, so a checkpoint can
+ # legitimately arrive with foreign moments: AdamW8bit stores "state1"/"state2", torch
+ # AdamW stores "exp_avg"/"exp_avg_sq". Shapes and counts match, so load_state_dict
+ # accepts them and the first step dies on a bare KeyError. Refuse with a real reason.
+ saved_optimizer = ckpt.optimizer_class
+ live_optimizer = optimizer_key(optimizer)
+ if not saved_optimizer:
+ # This writer records the class whenever it writes moments, so an optimizer file
+ # with no class beside it is a hand-edited or half-written bundle -- and letting it
+ # through is the same failure the check below exists for: foreign moments load
+ # cleanly (shapes and counts match) and die on the first step, in the child, after
+ # the route preflight has already evicted the resident models.
+ raise ResumeError(
+ "This checkpoint does not record which optimizer wrote its state, so its "
+ "moments cannot be safely restored. Resume from an earlier checkpoint, or "
+ "start a new run."
+ )
+ if saved_optimizer != live_optimizer:
+ raise ResumeError(
+ f"This checkpoint's optimizer state was written by {saved_optimizer}, but this "
+ f"machine builds {live_optimizer}. Install the same optimizer backend (or unset "
+ f"UNSLOTH_DIFFUSION_FP32_OPTIM) to continue this run."
+ )
+ # Optimizer state is keyed by parameter POSITION, so load_state_dict rebinds the saved
+ # moments onto whatever order this process built. The adapter tensors above were restored
+ # by NAME, so a PEFT/diffusers upgrade that changes traversal order while keeping the same
+ # names leaves the two disagreeing: many LoRA projections share a shape, so every moment
+ # loads cleanly onto the wrong tensor and the continued trajectory is silently corrupt.
+ saved_names = ckpt.optimizer_param_names
+ live_names = list(trainable_state_dict(model))
+ if saved_names is not None and saved_names != live_names:
+ raise ResumeError(
+ "This checkpoint's optimizer state was written for a different parameter order "
+ "than this build produces, so its moments cannot be matched to this run's "
+ "tensors. Start a new run, or resume on the version that wrote it."
+ )
+ # load_state_dict replaces the param groups too, so the checkpoint's learning rate wins
+ # over a changed cfg.learning_rate -- the same semantics as HF Trainer's resume, and the
+ # UI only ever replays the original run's config anyway.
+ optimizer.load_state_dict(optimizer_state)
+ elif optimizer is not None:
+ # The bundle lists no optimizer at all. Every bundle this writer produces for a real run
+ # has one, so this is a hand-edited or half-written directory -- and continuing would
+ # restart Adam's moments from zero at step N while reporting a clean resume, which looks
+ # like a resume and trains like a fresh run with a warm LR.
+ raise ResumeError(
+ "This checkpoint carries no optimizer state, so the run cannot be continued from "
+ "it: the moments would restart from zero at the resumed step. Start a new run."
+ )
+ scheduler_state = ckpt.torch_state("scheduler")
+ if scheduler_state is not None:
+ lr_scheduler.load_state_dict(scheduler_state)
+ _reapply_lr_schedule(optimizer, lr_scheduler)
+ elif lr_scheduler is not None:
+ # Same for the schedule: a fresh LambdaLR at step 0 would re-warm the learning rate the
+ # restored optimizer already moved past.
+ raise ResumeError(
+ "This checkpoint carries no learning-rate scheduler state, so the schedule would "
+ "restart from step 0. Start a new run."
+ )
+ if sampler is not None and not sampler.load_state_dict(ckpt.sampler_state):
+ # Every image checkpoint this format writes carries sampler state, so a bundle whose
+ # state is missing or malformed is not one this code wrote. Continuing would leave a
+ # fresh sampler behind an RNG restored to a point AFTER the saved permutation was
+ # drawn, so the next batch is a different order: images silently skipped or repeated,
+ # under a resume that reported success.
+ raise ResumeError(
+ "This checkpoint's dataset sampler state is missing or unreadable, so the image "
+ "order cannot be continued. Start a new run."
+ )
+ if ema is not None:
+ ema_state = ckpt.tensors("ema")
+ if ema_state:
+ missing = ema.missing_from(ema_state)
+ if missing:
+ # A readable but INCOMPLETE shadow set. load_state_dict keeps the freshly
+ # initialised shadow for anything it cannot match, so continuing here would
+ # blend restored EMA weights with initialisation noise for the rest -- and
+ # report a clean resume while doing it. There is no honest way to continue
+ # this run's EMA, so say so instead.
+ named = ", ".join(missing[:3]) + ("..." if len(missing) > 3 else "")
+ raise ResumeError(
+ f"This checkpoint's EMA state is missing or mis-shaped for {len(missing)} "
+ f"of this run's adapter tensors ({named}), so the averaged weights cannot "
+ f"be continued. Resume with EMA disabled, or start a new run."
+ )
+ ema.load_state_dict(ema_state, updates = ckpt.ema_updates)
+ else:
+ # EMA is not part of the validated identity, so a resume may turn it on for a run
+ # that had it off. The EMA object is built BEFORE the adapter is restored, so its
+ # shadow holds freshly initialised LoRA weights and there is nothing saved to
+ # replace them with -- every later update, and the exported EMA adapter, would
+ # blend the restored weights with that initialisation. Start from what was restored.
+ ema.reseed_from(model)
+ restore_rng_state(ckpt.rng_json, ckpt.torch_state("rng"), rng_streams)
+ _emit(
+ on_event,
+ "resumed",
+ checkpoint_path = str(path),
+ step = step,
+ total_steps = cfg.train_steps,
+ # Which bundle THIS is, not just where it sat. Another run can write its own
+ # checkpoint-<N> over the same slot, and the pathname alone would then offer that
+ # replacement back as this run's lineage.
+ source_created_at = ckpt.manifest.get("created_at"),
+ )
+ return ckpt
+
+
+def _publish_to_lora_catalog(
+ lora_path: str,
+ cfg: DiffusionLoraConfig,
+ steps: Optional[int] = None,
+) -> Optional[str]:
"""Best-effort copy of the trained adapter into the Studio diffusion LoRA directory so
the Images LoRA picker (which scans only files directly under ``loras/diffusion``) finds
it without the user moving files. Also writes a ``<alias>.json`` metadata sidecar so the
picker can family-gate the adapter (family, base model, trigger prompt, ...). Returns the
- published path, or None on any failure."""
+ published path, or None on any failure.
+
+ ``steps`` is the step count the run actually REACHED, which is what the sidecar must
+ record: a run stopped at step 11 of 500 published an adapter claiming 500 steps. None
+ keeps the old behaviour for callers that do not know the reached step."""
try:
import shutil
@@ -1066,22 +1500,29 @@ def _publish_to_lora_catalog(lora_path: str, cfg: DiffusionLoraConfig) -> Option
n += 1
if src_resolved != dest.resolve():
shutil.copy2(lora_path, dest)
- _write_lora_sidecar(dest.with_suffix(".json"), cfg)
+ _write_lora_sidecar(dest.with_suffix(".json"), cfg, steps)
return str(dest)
except Exception: # noqa: BLE001 -- the catalog mirror is best-effort, never fatal
return None
-def _write_lora_sidecar(sidecar_path: Path, cfg: DiffusionLoraConfig) -> None:
+def _write_lora_sidecar(
+ sidecar_path: Path,
+ cfg: DiffusionLoraConfig,
+ steps: Optional[int] = None,
+) -> None:
"""Write the adapter metadata sidecar read back by diffusion_lora._scan_local. Best
- effort: a failure here must not fail publishing, so callers wrap it."""
+ effort: a failure here must not fail publishing, so callers wrap it.
+
+ ``steps`` records the step the run REACHED. It used to record ``cfg.train_steps``, the
+ CONFIGURED length, so an adapter saved by stopping at step 11 of 500 advertised 500."""
meta = {
"family": cfg.resolved_family,
"families": [cfg.resolved_family],
"base_model": cfg.base_model,
"lora_rank": cfg.lora_rank,
"lora_alpha": cfg.lora_alpha,
- "steps": cfg.train_steps,
+ "steps": int(steps) if steps is not None else cfg.train_steps,
"resolution": cfg.resolution,
"trigger_prompt": cfg.instance_prompt,
"created_at": time.time(),
diff --git a/studio/backend/core/training/diffusion_train_extras.py b/studio/backend/core/training/diffusion_train_extras.py
index f819faff7c1..dea080f5c25 100644
--- a/studio/backend/core/training/diffusion_train_extras.py
+++ b/studio/backend/core/training/diffusion_train_extras.py
@@ -77,6 +77,24 @@ class LoRAEMA:
shadow.requires_grad = False
self._shadow[name] = shadow
+ def reseed_from(self, model: Any) -> None:
+ """Re-point every shadow at the model's CURRENT trainable weights.
+
+ For a resume that turns EMA on for the first time. The trainer builds the EMA before it
+ restores the adapter, so the shadow holds freshly initialised LoRA weights, and a
+ checkpoint written with EMA off carries no shadow to replace them with -- leaving the
+ exported EMA adapter blending the restored weights with initialisation noise. Starting
+ from the restored weights is what enabling EMA at step N means."""
+ import torch
+
+ with torch.no_grad():
+ for name, p in model.named_parameters():
+ shadow = self._shadow.get(name)
+ if shadow is None or tuple(shadow.shape) != tuple(p.shape):
+ continue
+ shadow.copy_(p.detach().to(device = shadow.device, dtype = shadow.dtype))
+ self.updates = 0
+
def effective_decay(self) -> float:
"""The decay used for the NEXT update (after ``updates`` prior ones)."""
if not self.warmup:
@@ -100,6 +118,43 @@ class LoRAEMA:
def state_dict(self) -> dict[str, Any]:
return {name: t.detach().clone() for name, t in self._shadow.items()}
+ def missing_from(self, state: dict[str, Any]) -> tuple[str, ...]:
+ """Live shadow names a saved EMA state does not cover, by name or by shape.
+
+ ``load_state_dict`` skips those entries by design (a differently-wrapped model should
+ degrade rather than raise), which is exactly why a caller restoring a run has to ask:
+ a partial EMA silently blends restored shadows for some parameters with freshly
+ initialised ones for the rest, and every later update and the exported EMA adapter
+ carry that mixture while the run reports a clean resume."""
+ saved = state or {}
+ missing = []
+ for name, shadow in self._shadow.items():
+ entry = saved.get(name)
+ if entry is None or tuple(entry.shape) != tuple(shadow.shape):
+ missing.append(name)
+ return tuple(missing)
+
+ def load_state_dict(
+ self,
+ state: dict[str, Any],
+ updates: int = 0,
+ ) -> None:
+ """Restore shadows saved by ``state_dict`` (a resume checkpoint), in place.
+
+ ``updates`` restores the warmup ramp position: without it a resumed run would
+ restart the ramp and pull the shadow hard towards the current weights. Entries the
+ live model does not have are ignored, so a checkpoint from a differently-wrapped
+ model degrades to "keep the freshly initialised shadow" instead of raising."""
+ import torch
+
+ with torch.no_grad():
+ for name, shadow in self._shadow.items():
+ saved = (state or {}).get(name)
+ if saved is None or tuple(saved.shape) != tuple(shadow.shape):
+ continue
+ shadow.copy_(saved.to(device = shadow.device, dtype = shadow.dtype))
+ self.updates = max(0, int(updates or 0))
+
def copy_to(self, model: Any) -> dict[str, Any]:
"""Write the shadow values into ``model``'s params, returning the
displaced originals so ``restore`` can undo the swap."""
diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.py
index 2c634a0e360..01782e7f0ce 100644
--- a/studio/backend/core/training/diffusion_training_service.py
+++ b/studio/backend/core/training/diffusion_training_service.py
@@ -103,6 +103,99 @@ def _runs_dir() -> Path:
return d
+def _resume_fields(
+ output_dir: Optional[str],
+ *,
+ status: Optional[str] = None,
+ started_at: Optional[float] = None,
+ ended_at: Optional[float] = None,
+ total_steps: Optional[int] = None,
+ write_error: Optional[str] = None,
+ source_checkpoint: Optional[str] = None,
+ source_created_at: Optional[float] = None,
+) -> dict[str, Any]:
+ """``can_resume`` / ``checkpoint_step`` / ``resume_blocked_reason`` for a run, read from
+ the checkpoints that are actually on disk.
+
+ Derived, not trusted: a persisted record is a snapshot of the moment the run ended, but
+ the user can delete the output folder afterwards. ``started_at`` fences off bundles an
+ EARLIER run of the same adapter name left in the same folder, and ``ended_at`` fences off
+ the ones a LATER run put there after this one finished -- without the upper bound a
+ finished run offers, and resumes, its successor's training state. ``write_error`` is the run's
+ own report that a checkpoint write failed; that is sticky and blocks resume (mirroring the
+ MLX trainer's ``resume_blocked``), because whatever older state is on disk predates the
+ adapter that was published, so continuing from it would silently lose steps. Never raises."""
+ try:
+ from core.training.diffusion_checkpoint import describe_resume_state
+ state = describe_resume_state(
+ output_dir,
+ status = status,
+ started_at = started_at,
+ ended_at = ended_at,
+ total_steps = total_steps,
+ source_checkpoint = source_checkpoint,
+ source_created_at = source_created_at,
+ )
+ except Exception: # noqa: BLE001 -- history must never break on a checkpoint scan
+ state = {}
+ if write_error:
+ return {
+ "can_resume": False,
+ "checkpoint_step": state.get("checkpoint_step"),
+ "checkpoint_path": None,
+ "resume_blocked_reason": write_error,
+ }
+ can_resume = bool(state.get("can_resume"))
+ return {
+ "can_resume": can_resume,
+ "checkpoint_step": state.get("checkpoint_step"),
+ # The EXACT bundle this run would continue, so the client resumes the one it was shown
+ # rather than "whatever is newest in that folder" (which, in a folder two runs share,
+ # can be a different run's).
+ "checkpoint_path": state.get("checkpoint_path") if can_resume else None,
+ "resume_blocked_reason": state.get("resume_blocked_reason"),
+ }
+
+
+def _refresh_resume_state(rec: dict) -> dict:
+ """Re-derive a persisted record's resume fields from the checkpoints on disk, in place.
+
+ Also backfills ``output_dir`` from the stored config for a record written before that field
+ existed: the UI replays that path as ``resume_from_checkpoint``, so reporting ``can_resume``
+ without it would enable an action the client then refuses on its own."""
+ config = rec.get("config")
+ output_dir = rec.get("output_dir") or (
+ config.get("output_dir") if isinstance(config, dict) else None
+ )
+ if output_dir and not rec.get("output_dir"):
+ rec["output_dir"] = str(output_dir)
+ rec.update(
+ _resume_fields(
+ output_dir,
+ status = rec.get("status"),
+ started_at = rec.get("started_at"),
+ ended_at = rec.get("ended_at"),
+ # Same rule as the write side, and via the same helper: a run that died during
+ # model loading never got a "resumed" event to seed total_steps, and zero here
+ # sends the calculation back to the checkpoint manifest's OLDER target. In EPOCH
+ # mode train_steps is the request model's unused default, so recomputing from it
+ # here undid the persisted answer on every read -- a 600-step checkpoint of a run
+ # resolved to 1000 read as 600/500 and Resume was disabled.
+ total_steps = _resolved_total_steps(rec, config if isinstance(config, dict) else {}),
+ write_error = rec.get("checkpoint_write_error"),
+ # What this run itself resumed from, so a resumed run that died before its first
+ # save can still offer the bundle it was validated against.
+ source_checkpoint = (
+ config.get("resume_from_checkpoint") if isinstance(config, dict) else None
+ ),
+ # And WHICH bundle that was, so a slot another run has since rewritten is not
+ # offered back as this run's own lineage.
+ source_created_at = rec.get("resumed_source_created_at"),
+ )
+ )
+ return rec
+
+
def list_diffusion_runs(limit: int = 20) -> list[dict]:
"""Summaries of persisted diffusion runs, newest first. The heavy per-run payload
(metric logs, config) stays in the file; fetch it via ``get_diffusion_run``."""
@@ -121,6 +214,15 @@ def list_diffusion_runs(limit: int = 20) -> list[dict]:
continue
if not (isinstance(rec.get("job_id"), str) and isinstance(rec.get("status"), str)):
continue
+ # Resume state comes from the checkpoints on disk NOW, before the config is dropped.
+ # Per record, because the refresh reads counters straight out of the file: one
+ # hand-edited or older record with a nonnumeric total_steps took the whole endpoint
+ # down, where every other kind of corruption here is skipped.
+ try:
+ _refresh_resume_state(rec)
+ _restate_live_job(rec)
+ except Exception: # noqa: BLE001 -- a record we cannot refresh is still a record
+ continue
rec.pop("metric_history", None)
rec.pop("config", None)
out.append(rec)
@@ -134,9 +236,46 @@ def get_diffusion_run(job_id: str) -> Optional[dict]:
return None
p = _runs_dir() / f"{job_id}.json"
try:
- return json.loads(p.read_text(encoding = "utf-8"))
+ rec = json.loads(p.read_text(encoding = "utf-8"))
except Exception: # noqa: BLE001 -- missing/corrupt record
return None
+ if not isinstance(rec, dict):
+ return rec
+ try:
+ _refresh_resume_state(rec)
+ _restate_live_job(rec)
+ except Exception: # noqa: BLE001 -- the stored record beats a 500
+ return rec
+ return rec
+
+
+def _restate_live_job(rec: dict) -> dict:
+ """Undo the interim record's pessimism for the job that is still running, in place.
+
+ An interim record is written as interrupted because that is the outcome if Studio never
+ comes back. While the process IS still here and still on that job, the honest answer is
+ running -- and reporting it as errored would offer a Resume for a directory the live run is
+ writing into."""
+ global _service
+ service = _service
+ if service is None:
+ return rec
+ try:
+ live = service.status()
+ except Exception: # noqa: BLE001 -- a status we cannot read leaves the record as written
+ return rec
+ if not isinstance(live, dict) or not live.get("job_id"):
+ return rec
+ if rec.get("job_id") == live.get("job_id") and live.get("status") == "running":
+ rec["status"] = "running"
+ rec["message"] = live.get("message") or ""
+ # And nothing resumable, which is what the interim record's error status made
+ # _refresh_resume_state derive a moment ago. _UNRESUMABLE_STATUS rejects a running job
+ # for a reason: its output directory is being written right now, so the only thing a
+ # Resume action there can do is race the live run and 409.
+ rec["can_resume"] = False
+ rec["checkpoint_path"] = None
+ return rec
def _idle_state() -> dict[str, Any]:
@@ -162,6 +301,17 @@ def _idle_state() -> dict[str, Any]:
"base_model": None,
"samples_per_second": None,
"peak_memory_gb": None,
+ # Resume state for this job: where its newest checkpoint-<N> bundle is, the step it holds,
+ # why one could not be written (surfaced as the Resume action's disabled tooltip), and the
+ # step a resumed run picked up from.
+ "checkpoint_path": None,
+ "checkpoint_step": None,
+ "resume_blocked_reason": None,
+ "resumed_from_step": None,
+ # The manifest timestamp of the bundle this run resumed FROM. A pathname is not an
+ # identity: another run can write over the same checkpoint-<N> slot, and the fallback
+ # would then offer that replacement back under this run's lineage.
+ "resumed_source_created_at": None,
"started_at": None,
"updated_at": None,
# Bounded, paired history arrays for the live loss chart (see _append_metric).
@@ -220,6 +370,23 @@ def _append_metric(
gns.append(fgn)
+def _resolved_total_steps(state: dict[str, Any], cfg: dict[str, Any]) -> int:
+ """The step target this run was actually going to reach.
+
+ ``train_steps`` is only meaningful when the run was NOT configured by epochs: the request
+ model defaults it to 500 and ``num_epochs`` overrides it, so falling back to it in epoch
+ mode invents a target the run never had -- a 600-step checkpoint of a run resolved to 1000
+ then reads as 600/500 and the resume is refused. Zero is honest there, and the checkpoint
+ manifest's own target (written with the resolved count) answers instead.
+ """
+ live = int(state.get("total_steps") or 0)
+ if live:
+ return live
+ if int(cfg.get("num_epochs") or 0) > 0:
+ return 0
+ return int(cfg.get("train_steps") or 0)
+
+
class DiffusionTrainingService:
"""One diffusion LoRA training job at a time, spawned as a subprocess."""
@@ -236,6 +403,24 @@ class DiffusionTrainingService:
self._reserved = False
# Dataset mutations in flight. A start refuses while any is open and a mutation refuses once a start is reserved, both under _lock, so neither slips through the other's check-then-act window.
self._dataset_mutations = 0
+ # "Stop without saving" for the CURRENT job, remembered in the parent. The trainer
+ # reports it on its completion event, but a child that is killed or OOMs after the
+ # request never emits one -- and the unexpected-exit path then recorded a resumable
+ # error run, re-offering Resume from the very checkpoint the user asked to discard.
+ self._discard_requested = False
+ # Bundle paths THIS job reported writing, so a discard the child could not carry out
+ # itself removes exactly those and nothing that predated the run.
+ self._own_checkpoints: list[str] = []
+ # Set when the child reported a discarded completion, which it emits only AFTER running
+ # its own clear_own_checkpoints. That helper hands a displaced slot back, so the path
+ # this run wrote to can now hold ANOTHER run's restored bundle -- and the parent-side
+ # cleanup, which knows only pathnames, would delete it.
+ self._child_cleared_own = False
+ # Set by a checkpoint_saved event, cleared once the pump has written the record.
+ self._persist_interim = False
+ # Whether this job has already had a stop signalled. Only the first one reaches the
+ # child, so only the first one may set the parent's disposition.
+ self._stop_signalled = False
# GPU load admissions in flight (a load between its training guard and its arbiter registration). Same two-sided rule as the dataset mutations.
self._gpu_admissions = 0
self._proc: Any = None
@@ -371,6 +556,10 @@ class DiffusionTrainingService:
raise RuntimeError("A diffusion training job is already running.")
job_id = uuid.uuid4().hex
+ self._discard_requested = False
+ self._own_checkpoints = []
+ self._child_cleared_own = False
+ self._stop_signalled = False
event_queue = self._ctx.Queue()
self._stop_queue = self._ctx.Queue()
self._proc = self._ctx.Process(
@@ -404,6 +593,13 @@ class DiffusionTrainingService:
started_at = now,
updated_at = now,
)
+ # AFTER the reset above, which replaces the whole state dict. The route has already
+ # validated and PINNED a source bundle, so its identity is known before the child
+ # runs: recording it here means a resume that dies during the model load -- before
+ # the trainer can emit "resumed" -- still has the timestamp its fallback is checked
+ # against, instead of trusting the pathname and offering back whatever later
+ # occupies that slot.
+ self._seed_source_identity(config)
# Keep the config (minus secrets) for the persisted run record.
self._config = {k: v for k, v in dict(config).items() if k != "hf_token"}
self._pump = threading.Thread(
@@ -420,11 +616,24 @@ class DiffusionTrainingService:
with self._lock:
if self._proc is None or not self._proc.is_alive() or self._stop_queue is None:
return False
+ if self._stop_signalled:
+ # The child consumes the FIRST signal and acts on it. A second one cannot
+ # un-save an adapter it has already exported, so honouring a later
+ # stop-without-saving set a parent discard the child never carried out: the
+ # run was marked discarded and its checkpoints deleted while the adapter and
+ # the catalog entry it published stayed on disk. The disposition is whichever
+ # one the child actually got.
+ return True
try:
# Bare True = older wire format; the dict form carries the no-save cancel flag.
self._stop_queue.put(True if save else {"save": False})
except Exception: # noqa: BLE001
return False
+ self._stop_signalled = True
+ if not save:
+ # Remembered here so a child that dies before its discarded completion still
+ # blocks the resume the user threw away.
+ self._discard_requested = True
self._state["message"] = (
"Stop requested; finishing the current step and saving a partial adapter..."
if save
@@ -465,24 +674,91 @@ class DiffusionTrainingService:
message = "Training process exited unexpectedly.",
updated_at = time.time(),
)
+ discarding = self._discard_requested
+ if discarding:
+ self._apply_discard_intent()
_ = drained
self._persist_run_record()
return
continue
self._apply_event(ev, proc = proc)
+ if self._persist_interim:
+ self._persist_interim = False
+ self._persist_run_record(interim = True)
if ev.get("type") in _TERMINAL:
+ # An exception raised on the current step is a terminal `error`, and the pump
+ # returns here rather than through the dead-process branch -- so the discard the
+ # user asked for has to be applied on this path too.
+ with self._lock:
+ discarding = self._discard_requested and self._proc is proc
+ child_cleared = self._child_cleared_own
+ if discarding:
+ self._apply_discard_intent(delete = not child_cleared)
self._persist_run_record()
return
- def _persist_run_record(self) -> None:
+ def _seed_source_identity(self, config: dict[str, Any]) -> None:
+ """Record which bundle the route accepted, before the child can report it itself."""
+ source = config.get("resume_from_checkpoint")
+ if not source:
+ return
+ try:
+ from core.training.diffusion_checkpoint import read_checkpoint
+ manifest = read_checkpoint(Path(str(source)).expanduser())
+ except Exception: # noqa: BLE001 -- an unreadable bundle simply has no identity here
+ manifest = None
+ if isinstance(manifest, dict):
+ self._state["resumed_source_created_at"] = manifest.get("created_at")
+
+ def _apply_discard_intent(self, *, delete: bool = True) -> None:
+ """Carry out a stop-without-saving the child could not report itself.
+
+ The trainer does this on its own completion path; a child that OOMs, is killed, or dies
+ on the current step never gets there. Blocking the resume is the visible half -- the
+ bundles are the other one, and they hold optimizer and scheduler state, are sizeable,
+ and have no delete path in the UI once the run is marked discarded.
+
+ ``delete`` False is the case where the child DID get there. Its cleanup restores any
+ bundle this run wrote over, so the paths remembered here no longer name this run's
+ bundles -- deleting them then destroys the predecessor that was just handed back, which
+ is another run's resume point. The state half still applies either way.
+ """
+ with self._lock:
+ own = list(self._own_checkpoints) if delete else []
+ self._state["resume_blocked_reason"] = (
+ "This run was stopped without saving, so it was discarded."
+ )
+ self._state["checkpoint_path"] = None
+ self._state["checkpoint_step"] = None
+ self._own_checkpoints = []
+ if not own:
+ return
+ try:
+ from core.training.diffusion_checkpoint import discard_named_checkpoints
+ discard_named_checkpoints(own)
+ except Exception: # noqa: BLE001 -- cleanup must never break the terminal transition
+ pass
+
+ def _persist_run_record(self, *, interim: bool = False) -> None:
"""Best-effort JSON record of the finished run (summary + scrubbed config + the
bounded metric logs) into the studio runs directory. Never fatal: history is a
- convenience, not part of the training contract."""
+ convenience, not part of the training contract.
+
+ ``interim`` writes the same record for a run that is still going, which is what makes a
+ checkpoint survive Studio itself dying: the bundle is on disk but only a terminal event
+ used to write the JSON that Previous runs and its Resume action are built from. The
+ status recorded is the one that is true if nothing else ever happens -- the run was
+ interrupted -- and the terminal write replaces it in place."""
try:
with self._lock:
s = dict(self._state)
cfg = dict(self._config)
- if not s.get("job_id") or s.get("status") not in ("completed", "stopped", "error"):
+ if not s.get("job_id"):
+ return
+ if interim:
+ s["status"] = "error"
+ s["message"] = "Studio exited while this run was training."
+ elif s.get("status") not in ("completed", "stopped", "error"):
return
adapter = s.get("output_dir") or cfg.get("output_dir")
record = {
@@ -508,6 +784,36 @@ class DiffusionTrainingService:
"ema_path": s.get("ema_path"),
"catalog_path": s.get("catalog_path"),
"saved": bool(s.get("lora_path")),
+ # Resume lineage + state. output_dir is what a Resume replays, so it is recorded on
+ # the run rather than only inside the config. can_resume / checkpoint_step are a
+ # snapshot taken now and RE-DERIVED from disk on read, so deleting the checkpoints
+ # later takes the action away instead of leaving a button that 400s.
+ "output_dir": str(adapter) if adapter else None,
+ "resumed_from_job_id": cfg.get("resumed_from_job_id") or None,
+ "resumed_from_step": s.get("resumed_from_step"),
+ "resumed_source_created_at": s.get("resumed_source_created_at"),
+ "checkpoint_write_error": s.get("resume_blocked_reason") or None,
+ **_resume_fields(
+ str(adapter) if adapter else None,
+ status = s.get("status"),
+ started_at = s.get("started_at"),
+ # The REQUESTED target, falling back to the config the start preflight
+ # accepted: total_steps is seeded by the "resumed" event, and a run that
+ # dies during model loading never gets one. Zero there sent the resume
+ # calculation back to the checkpoint manifest's older target, which then
+ # reported "nothing left to train" for a run whose whole point was a
+ # raised target.
+ #
+ # NOT in epoch mode, though: num_epochs overrides train_steps, which then
+ # still carries the Pydantic default of 500. A run resolved to 1000 that
+ # died before its "resumed" event would report a 600-step checkpoint as
+ # 600/500 and refuse the resume. Zero there is honest, and the manifest's
+ # own target (written with the resolved count) is the right answer.
+ total_steps = _resolved_total_steps(s, cfg),
+ write_error = s.get("resume_blocked_reason"),
+ source_checkpoint = cfg.get("resume_from_checkpoint"),
+ source_created_at = s.get("resumed_source_created_at"),
+ ),
"config": cfg,
"metric_history": {
"steps": s.get("metric_steps") or [],
@@ -558,6 +864,54 @@ class DiffusionTrainingService:
elif etype == "warning":
# Non-fatal trainer notes; keep training state, surface the text.
s["message"] = str(ev.get("message", "warning"))
+ elif etype == "resumed":
+ # The trainer restored a checkpoint and is continuing from it. Recorded so the run
+ # history shows lineage instead of an unexplained run that starts mid-way. This is
+ # the step resumed FROM, not a checkpoint this run wrote, so it does not touch
+ # checkpoint_step (which tracks this run's own newest bundle).
+ s.update(
+ resumed_from_step = ev.get("step"),
+ resumed_source_created_at = ev.get("source_created_at"),
+ message = f"Resuming from step {ev.get('step')}...",
+ )
+ # Seed the LIVE counters from the same event. They are what the UI renders and
+ # what an errored run persists, and until the first post-resume progress event
+ # they still read 0/0 -- so a resume of step 400 of 500 shows "0/0", and an OOM
+ # on the first step records a failed run at step 0 with a target of 0.
+ # checkpoint_step stays untouched: this bundle is not one this run wrote.
+ if ev.get("step") is not None:
+ s["step"] = int(ev["step"])
+ if ev.get("total_steps") is not None:
+ s["total_steps"] = int(ev["total_steps"])
+ elif etype == "checkpoint_saved":
+ # Folded as each bundle lands, not only at the end, so a run that later crashes is
+ # still reported as resumable. A good write also clears an earlier write's failure.
+ s.update(
+ checkpoint_path = ev.get("checkpoint_path"),
+ checkpoint_step = ev.get("step"),
+ resume_blocked_reason = None,
+ )
+ written = ev.get("checkpoint_path")
+ if written and written not in self._own_checkpoints:
+ self._own_checkpoints.append(str(written))
+ # The bundle is on disk; the run JSON is not, and only a terminal event writes
+ # one. Studio being killed or shut down after a periodic save therefore left a
+ # resumable checkpoint that Previous runs -- which reads those JSONs and
+ # nothing else -- had no entry for, so the Resume action did not exist. Written
+ # as an interrupted run because that is what it IS until the run ends: the
+ # terminal persist overwrites the same file, and the live job is reported as
+ # running by the reader below.
+ self._persist_interim = True
+ elif etype == "checkpoint_failed":
+ # Sticky: whatever older bundle is on disk predates the work this run did, so
+ # resuming from it would silently lose steps. Mirrors the MLX resume_blocked flag.
+ s["resume_blocked_reason"] = str(ev.get("message", "checkpoint write failed"))
+ # Persisted for the same reason a successful write is. In memory only, a Studio
+ # exit after this left the last record advertising the OLDER checkpoint as
+ # resumable -- the one this service has just decided is stale -- and resuming it
+ # rolls the run back past everything after it. A later checkpoint_saved clears
+ # the reason and replaces the record.
+ self._persist_interim = True
elif etype == "progress":
# Null any non-finite float so the JSON stays strict-parseable; a missing key keeps the last value.
loss = _finite_or_none(ev["loss"]) if "loss" in ev else s["loss"]
@@ -616,6 +970,21 @@ class DiffusionTrainingService:
s["family"] = ev.get("family")
if ev.get("base_model") is not None:
s["base_model"] = ev.get("base_model")
+ # Checkpoint state is folded from the per-save events above; only the lineage is
+ # (re)confirmed here, for a pump that missed the earlier ``resumed`` event.
+ if ev.get("resumed_from_step") is not None:
+ s["resumed_from_step"] = ev.get("resumed_from_step")
+ if ev.get("discarded"):
+ # Cancelled with "stop without saving": the user threw this run away, so its
+ # own periodic checkpoints must not keep offering to continue it.
+ #
+ # The child ran its own cleanup before emitting this, so the parent must not
+ # repeat it by pathname: a slot this run overwrote has been handed back to
+ # the bundle it displaced, and that one belongs to another run.
+ self._child_cleared_own = True
+ s["resume_blocked_reason"] = (
+ "This run was stopped without saving, so it was discarded."
+ )
elif etype == "error":
# Reset in_model_load too: an error during model loading has no model_load_completed.
s.update(
diff --git a/studio/backend/models/training.py b/studio/backend/models/training.py
index fbdd06e61e9..c8fde04d396 100644
--- a/studio/backend/models/training.py
+++ b/studio/backend/models/training.py
@@ -925,6 +925,35 @@ class DiffusionTrainingStartRequest(BaseModel):
"(auto for qwen-image, 1.0 otherwise)."
),
)
+ # ── resume ────────────────────────────────────────────────────────────────
+ save_steps: int = Field(
+ 0,
+ ge = 0,
+ le = 100000,
+ description = (
+ "Write a resumable checkpoint every N optimizer steps. 0 (the default) writes no "
+ "periodic checkpoints; a stop-and-save always writes one, so Resume stays available "
+ "either way."
+ ),
+ )
+ save_total_limit: int = Field(
+ 2, ge = 0, le = 100, description = "How many checkpoints to keep; 0 keeps every one"
+ )
+ resume_from_checkpoint: Optional[str] = Field(
+ None,
+ description = (
+ "Continue a previous run: its output_dir (the newest complete checkpoint inside it "
+ "is used) or one explicit checkpoint-<N> directory. Must resolve inside the Studio "
+ "outputs root, and must match this run's family, base model, dataset, LoRA "
+ "configuration and precision. train_steps is then the TARGET TOTAL, so resuming a "
+ "checkpoint at step 11 with train_steps=500 trains steps 12..500."
+ ),
+ )
+ resumed_from_job_id: Optional[str] = Field(
+ None,
+ pattern = r"^[0-9a-f]{32}$",
+ description = "The run this one continues, recorded in the history for lineage only",
+ )
class DiffusionTrainingStopRequest(BaseModel):
@@ -980,6 +1009,12 @@ class DiffusionTrainingStatusResponse(BaseModel):
# Live throughput + peak VRAM (from the trainer's progress events).
samples_per_second: Optional[float] = None
peak_memory_gb: Optional[float] = None
+ # Resume state for this job: the newest checkpoint bundle written, the step it holds, why one
+ # could not be written (the Resume action's disabled tooltip), and where a resumed run started.
+ checkpoint_path: Optional[str] = None
+ checkpoint_step: Optional[int] = None
+ resume_blocked_reason: Optional[str] = None
+ resumed_from_step: Optional[int] = None
started_at: Optional[float] = None
updated_at: Optional[float] = None
# Bounded step/loss/lr history for the live loss + LR charts.
@@ -1005,6 +1040,20 @@ class DiffusionTrainingRunSummary(BaseModel):
instance_prompt: Optional[str] = None
started_at: Optional[float] = None
ended_at: Optional[float] = None
+ # The run's adapter directory, which is also what a Resume replays as resume_from_checkpoint.
+ output_dir: Optional[str] = None
+ # Whether this run can be continued, re-derived from the checkpoints on disk at read time (not
+ # the value frozen when the run ended), with the step the newest bundle holds. When it cannot,
+ # resume_blocked_reason says why, and the UI shows that as the disabled action's tooltip.
+ can_resume: bool = False
+ checkpoint_step: Optional[int] = None
+ # The exact bundle a resume would continue. Clients send it back as resume_from_checkpoint so
+ # they get the one they were shown, not whatever is newest in a folder two runs may share.
+ checkpoint_path: Optional[str] = None
+ resume_blocked_reason: Optional[str] = None
+ # Lineage: the run this one continued, and the step it picked up from.
+ resumed_from_job_id: Optional[str] = None
+ resumed_from_step: Optional[int] = None
class DiffusionTrainingRunDetail(DiffusionTrainingRunSummary):
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 5fdebb79d57..32890fa127b 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -2649,6 +2649,35 @@ def _resolve_diffusion_data_dir(raw: str) -> Path:
return resolve_dataset_path(raw)
+def _preflight_diffusion_resume(
+ config: dict,
+ identity: Any,
+ target_steps: int,
+ *,
+ pin: bool = True,
+) -> None:
+ """Validate ``config["resume_from_checkpoint"]`` against ``identity``, optionally PINNING it.
+
+ Pinning rewrites the config's resume path to the exact ``checkpoint-<N>`` directory that was
+ accepted, so the trainer subprocess resumes the bundle this preflight approved rather than
+ re-picking "newest" from a directory that could have changed.
+
+ Called twice -- once before the dataset is known, once with its fingerprint -- and both
+ times BEFORE the resident GPU models are freed. The FIRST pass does not pin: its identity
+ has no dataset fingerprint, so that comparison is skipped and it can accept the newest
+ bundle on the strength of a check it did not make. Rewriting the request to that bundle
+ left the dataset-aware pass with nothing to do but reject it, when scanning the original
+ directory would have found an older retained checkpoint matching the current images.
+ Raises ResumeError."""
+ from core.training.diffusion_checkpoint import preflight_resume
+
+ path, _step = preflight_resume(
+ config["resume_from_checkpoint"], identity = identity, target_steps = target_steps
+ )
+ if pin:
+ config["resume_from_checkpoint"] = path
+
+
@router.post("/diffusion/start", response_model = DiffusionTrainingStartResponse)
async def start_diffusion_training(
body: DiffusionTrainingStartRequest,
@@ -2748,6 +2777,48 @@ async def start_diffusion_training(
if _precision_reason:
raise HTTPException(status_code = 400, detail = _precision_reason)
+ # Preflight a resume request in the same place and for the same reason: a checkpoint from a
+ # different family / base / LoRA shape / precision must 400 BEFORE the resident GPU model is
+ # evicted, not fail in the child once the user's Images pipeline is already gone. The dataset
+ # half of the identity needs the discovery pass, so it runs below (still before eviction).
+ from core.training.diffusion_checkpoint import (
+ ResumeError,
+ dataset_fingerprint,
+ identity_for_config,
+ resolve_resume_dir,
+ )
+
+ resuming = bool(normalized_cfg.resume_from_checkpoint)
+ # Only built for a resume: identity_for_config scans the local Hub cache for the base repo's
+ # revision, which a plain start has no use for.
+ resume_identity = identity_for_config(normalized_cfg) if resuming else None
+ if resuming:
+ try:
+ # Resolve + contain it here, like data_dir / output_dir: the trainer subprocess would
+ # otherwise resolve a relative name against its own cwd.
+ config["resume_from_checkpoint"] = str(
+ resolve_resume_dir(normalized_cfg.resume_from_checkpoint)
+ )
+ # In epochs mode the real target is only known once the dataset size is; skip the
+ # "already finished" check here and make it below, with the resolved step count.
+ # Offloaded like the other preflights: validating a bundle parses a safetensors
+ # header and walks two torch-zip pickles, which must not block the event loop.
+ await asyncio.to_thread(
+ _preflight_diffusion_resume,
+ config,
+ resume_identity,
+ # No target either. The "already at the target" refusal is TERMINAL, and this
+ # pass has no dataset fingerprint -- so a newest bundle belonging to a different
+ # dataset, already at the count, aborted the scan before the dataset-aware pass
+ # could find the older checkpoint that does match the requested images.
+ 0,
+ # And leave the request pointing at what the user gave, for the same reason:
+ # that pass is the one that may need to scan the directory.
+ pin = False,
+ )
+ except ResumeError as e:
+ raise HTTPException(status_code = 400, detail = str(e))
+
# Run the trainers' trust gate here too, so an untrusted/typoed base 400s BEFORE freeing GPU residents rather than failing in the child.
from core.training.diffusion_train_common import _assert_trusted_base_model
@@ -2773,7 +2844,7 @@ async def start_diffusion_training(
reserved = True
# Preflight the dataset: a missing/empty/uncaptionable data_dir otherwise fails inside the trainer AFTER eviction. Same discovery the trainer runs, so the two cannot disagree.
try:
- await asyncio.to_thread(
+ pairs = await asyncio.to_thread(
_dtc.discover_image_caption_pairs,
config["data_dir"],
instance_prompt = config.get("instance_prompt") or None,
@@ -2783,6 +2854,18 @@ async def start_diffusion_training(
)
except (FileNotFoundError, ValueError) as e:
raise HTTPException(status_code = 400, detail = str(e))
+ if resuming:
+ # The dataset half of the resume identity, now that the images are known -- and the
+ # step target, which epochs mode only resolves here. Still before the GPU teardown.
+ try:
+ await asyncio.to_thread(
+ _preflight_diffusion_resume,
+ config,
+ resume_identity.with_dataset(dataset_fingerprint(pairs)),
+ _dtc.resolve_train_steps(normalized_cfg, len(pairs)),
+ )
+ except ResumeError as e:
+ raise HTTPException(status_code = 400, detail = str(e))
# Free resident GPU workloads before the trainer loads its own pipeline. Offloaded: the teardown blocks on generation locks and a subprocess join.
await asyncio.to_thread(_free_gpu_for_diffusion_training)
job_id = service.start(config)
@@ -2847,8 +2930,11 @@ async def list_diffusion_training_runs(
per-run records. Summaries only; fetch one run for its config + metric logs."""
from core.training.diffusion_training_service import list_diffusion_runs
+ # Offloaded: each record's can_resume is re-derived by validating the checkpoint bundles on
+ # disk (safetensors header + torch-zip pickle walk per file), which must not block the loop.
+ records = await asyncio.to_thread(list_diffusion_runs, limit = limit)
summaries: list[DiffusionTrainingRunSummary] = []
- for r in list_diffusion_runs(limit = limit):
+ for r in records:
# list_diffusion_runs skips non-dict / missing-id records, but a wrong-typed field would still raise here; catch per record so one bad file never breaks the panel.
try:
summaries.append(DiffusionTrainingRunSummary(**r))
@@ -2865,7 +2951,8 @@ async def get_diffusion_training_run(
step/loss/grad-norm logs (for re-plotting a past run's charts)."""
from core.training.diffusion_training_service import get_diffusion_run
- rec = get_diffusion_run(job_id)
+ # Offloaded for the same reason as the listing: the read re-validates the run's checkpoints.
+ rec = await asyncio.to_thread(get_diffusion_run, job_id)
# A valid-JSON file that is not an object makes DiffusionTrainingRunDetail(**rec) raise TypeError, not the ValidationError caught below. Treat any non-dict record as absent.
if not isinstance(rec, dict):
raise HTTPException(status_code = 404, detail = "No such training run.")
diff --git a/studio/backend/tests/test_diffusion_checkpoint_resume.py b/studio/backend/tests/test_diffusion_checkpoint_resume.py
new file mode 100644
index 00000000000..7b3818d7306
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_checkpoint_resume.py
@@ -0,0 +1,2967 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""CPU-only tests for diffusion training resume.
+
+A stop-and-save used to leave only the adapter, so restarting the same configuration began
+again at step 1. These cover the pieces that fix it: the atomically written checkpoint
+bundle, the optimizer / scheduler / RNG round-trip, the loop resuming at N+1 up to the same
+TARGET total, the identity gate that rejects a mismatched checkpoint before the resident GPU
+model is evicted, the ``can_resume`` reported for stopped / completed / errored runs, and the
+LoRA sidecar recording the step actually reached.
+
+No GPU and no diffusers/peft: the trainers' family-specific halves are exercised elsewhere,
+while everything here runs against a two-parameter ``torch.nn.Linear`` through the same
+shared helpers both trainers call. The one bitsandbytes case skips without CUDA.
+"""
+
+from __future__ import annotations
+
+import ast
+import time
+import os
+import json
+from pathlib import Path
+
+import pytest
+import torch
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import authenticated_via_api_key, get_current_subject
+from core.training import diffusion_checkpoint as dc
+from core.training.diffusion_train_common import (
+ DiffusionLoraConfig,
+ PermutationBatchSampler,
+ restore_resume_state,
+ write_resume_checkpoint,
+)
+from routes.training import router as training_router
+
+
+# ── fixtures / doubles ────────────────────────────────────────────────────────
+def _identity(**overrides) -> dc.CheckpointIdentity:
+ fields = {
+ "family": "sdxl",
+ "base_model": "stabilityai/sdxl-turbo",
+ "lora_target_modules": ("to_k", "to_q", "to_v", "to_out.0"),
+ "lora_rank": 16,
+ "lora_alpha": 16,
+ "precision": "bf16",
+ "base_precision": "nf4",
+ "resolution": 1024,
+ "base_revision": "rev-deadbeef",
+ "dataset_fingerprint": "ds-3-cafe",
+ }
+ fields.update(overrides)
+ return dc.CheckpointIdentity(**fields)
+
+
+class _Run:
+ """A minimal stand-in for a trainer: one trainable tensor, a real optimizer, a real LR
+ schedule and the shared permutation sampler, wired exactly as both trainers wire them so
+ the resume helpers are exercised on the real objects rather than mocks."""
+
+ def __init__(
+ self,
+ output_dir: Path,
+ *,
+ seed: int = 0,
+ **cfg_overrides,
+ ):
+ torch.manual_seed(seed)
+ self.model = torch.nn.Linear(4, 4, bias = False)
+ self.optimizer = torch.optim.AdamW(self.model.parameters(), lr = 1e-3)
+ # A decaying lambda so a wrong schedule position shows up as a different LR.
+ self.lr_sched = torch.optim.lr_scheduler.LambdaLR(
+ self.optimizer, lr_lambda = lambda step: 1.0 / (1.0 + 0.01 * step)
+ )
+ self.loop_rng = __import__("random").Random(seed)
+ self.variant_rng = __import__("random").Random(seed + 1)
+ self.sampler = PermutationBatchSampler(7, self.loop_rng)
+ self.cfg = DiffusionLoraConfig(
+ base_model = "stabilityai/sdxl-turbo",
+ data_dir = "unused",
+ output_dir = str(output_dir),
+ train_steps = 500,
+ **cfg_overrides,
+ )
+ self.identity = _identity()
+ self.streams = {"loop": self.loop_rng, "variant": self.variant_rng}
+
+ def step_once(self, grad_scale: float) -> None:
+ self.optimizer.zero_grad(set_to_none = True)
+ self.model.weight.grad = torch.full_like(self.model.weight, grad_scale)
+ self.optimizer.step()
+ self.lr_sched.step()
+
+ def save(self, step: int, **kw):
+ return write_resume_checkpoint(
+ self.cfg,
+ step = step,
+ model = self.model,
+ optimizer = self.optimizer,
+ lr_scheduler = self.lr_sched,
+ identity = self.identity,
+ sampler = self.sampler,
+ rng_streams = self.streams,
+ **kw,
+ )
+
+ def restore(self):
+ return restore_resume_state(
+ self.cfg,
+ model = self.model,
+ optimizer = self.optimizer,
+ lr_scheduler = self.lr_sched,
+ identity = self.identity,
+ sampler = self.sampler,
+ rng_streams = self.streams,
+ )
+
+
+def run_dir(tmp_path, monkeypatch):
+ """A run output directory inside the (per-test) Studio outputs root, since the resume
+ path resolver refuses anything outside it."""
+ from utils.paths import outputs_root
+
+ d = outputs_root() / "my-lora-run"
+ d.mkdir(parents = True, exist_ok = True)
+ return d
+
+
+# ── atomic write ──────────────────────────────────────────────────────────────
+def test_kill_mid_write_leaves_no_valid_looking_checkpoint(run_dir, monkeypatch):
+ # Simulate a hard kill between "everything written" and the atomic promote: rmtree is
+ # neutralised so the staging directory survives untouched, exactly as SIGKILL would leave it.
+ run = _Run(run_dir)
+ monkeypatch.setattr(dc.shutil, "rmtree", lambda *a, **k: None)
+ monkeypatch.setattr(dc, "_promote", lambda *a, **k: (_ for _ in ()).throw(SystemExit(1)))
+ with pytest.raises(SystemExit):
+ dc.save_checkpoint(
+ output_dir = str(run_dir),
+ step = 11,
+ adapter_state = {"weight": run.model.weight.detach()},
+ identity = run.identity,
+ target_steps = 500,
+ optimizer = run.optimizer,
+ lr_scheduler = run.lr_sched,
+ )
+
+ # The staging directory really does hold a COMPLETE bundle, so this is a faithful mid-write kill...
+ staged = list(run_dir.glob(".tmp-checkpoint-*"))
+ assert staged and (staged[0] / dc.TRAINER_STATE_FILENAME).is_file()
+ # ...and yet nothing that any scanner would offer as resumable exists.
+ assert dc.list_checkpoints(run_dir) == []
+ assert dc.latest_valid_checkpoint(run_dir) is None
+ assert dc.describe_resume_state(str(run_dir))["can_resume"] is False
+ assert not list(run_dir.glob("checkpoint-*"))
+
+
+def _STREAMS() -> dict:
+ """The two random.Random streams both trainers own. A bundle without them cannot restore the
+ crop/flip and variant draws, and the preflight refuses it."""
+ import random as _random
+ return {"loop": _random.Random(0), "variant": _random.Random(1)}
+
+
+def test_a_failed_promotion_puts_the_old_checkpoint_back(run_dir, monkeypatch):
+ """Re-saving an OCCUPIED step swaps the old bundle out to make room. If the rename that
+ puts the new one in place then fails, the slot is empty and the only copy of the run's
+ last resumable state is the hidden stale directory -- which the next _prune_staging
+ deletes. A resumed run overwriting checkpoint-N would lose its resume point outright."""
+ run = _Run(run_dir)
+ first, error = run.save(4)
+ assert error is None and first is not None
+ before = (Path(first) / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+
+ real_replace = dc.os.replace
+
+ def _fail_the_promotion(src, dst):
+ # Only the staging -> slot rename. The swap-aside and the rescue that puts the old
+ # bundle back both move a "stale" directory and have to be allowed through.
+ if Path(dst).name == "checkpoint-4" and not any(
+ tag in Path(src).name for tag in ("stale", "replaced")
+ ):
+ raise OSError("promotion failed")
+ return real_replace(src, dst)
+
+ monkeypatch.setattr(dc.os, "replace", _fail_the_promotion)
+ second, error = run.save(4)
+ monkeypatch.undo()
+
+ assert error is not None, "the failure has to be reported, not swallowed"
+ restored = run_dir / "checkpoint-4"
+ assert restored.is_dir(), "the old bundle must be handed back to its slot"
+ assert (restored / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8") == before
+ assert dc.latest_valid_checkpoint(run_dir) is not None
+
+
+def test_a_kill_between_the_swap_and_the_rename_does_not_lose_the_checkpoint(run_dir, monkeypatch):
+ """Same window, harder ending: the process dies after the old bundle is moved aside. The
+ orphan is the run's last resumable state, so the next save must hand it back rather than
+ sweep it up as abandoned staging."""
+ run = _Run(run_dir)
+ first, error = run.save(4)
+ assert error is None and first is not None
+ stale = run_dir / f"{dc._STAGING_PREFIX}stale-4-deadbeef"
+ dc.os.replace(run_dir / "checkpoint-4", stale)
+ assert not (run_dir / "checkpoint-4").exists()
+
+ dc._prune_staging(run_dir)
+
+ assert (run_dir / "checkpoint-4" / dc.TRAINER_STATE_FILENAME).is_file()
+ assert not stale.exists()
+ assert dc.latest_valid_checkpoint(run_dir) is not None
+
+
+def test_failed_write_cleans_up_and_next_save_clears_stale_staging(run_dir, monkeypatch):
+ run = _Run(run_dir)
+ # A failure BEFORE the manifest (a full disk mid-optimizer-write) unwinds its own staging dir,
+ # and the shared wrapper turns it into a reported reason instead of killing the training run.
+ monkeypatch.setattr(
+ dc, "_torch_save", lambda *a, **k: (_ for _ in ()).throw(OSError("no space left"))
+ )
+ path, error = run.save(5)
+ assert path is None and "no space left" in error
+ assert list(run_dir.glob(".tmp-checkpoint-*")) == []
+ assert dc.list_checkpoints(run_dir) == []
+ monkeypatch.undo()
+
+ # A stale staging directory left by an earlier killed process is swept by the next good save.
+ stale = run_dir / f"{dc._STAGING_PREFIX}9-abcd1234"
+ stale.mkdir()
+ (stale / "junk").write_text("x", encoding = "utf-8")
+ path, error = run.save(6)
+ assert error is None and path is not None
+ assert not stale.exists()
+ assert dc.latest_valid_checkpoint(run_dir)[1]["global_step"] == 6
+
+
+def test_a_real_fsync_failure_fails_the_save_but_an_unsupported_one_does_not(run_dir, monkeypatch):
+ # fsync is where delayed-allocation ENOSPC and writeback EIO surface, and the validator only
+ # parses a safetensors HEADER, so a bundle whose bytes never reached the device would be
+ # promoted and later read as valid. But Windows' _commit and several network filesystems
+ # refuse the flush outright, which says nothing about the write and must not fail the run.
+ run = _Run(run_dir)
+ real_fsync = dc.os.fsync
+
+ monkeypatch.setattr(dc.os, "fsync", lambda fd: (_ for _ in ()).throw(OSError(28, "ENOSPC")))
+ path, error = run.save(1)
+ assert path is None and "ENOSPC" in error
+ assert dc.list_checkpoints(run_dir) == []
+
+ monkeypatch.setattr(dc.os, "fsync", lambda fd: (_ for _ in ()).throw(OSError(1, "EPERM")))
+ path, error = run.save(2)
+ assert error is None and path is not None
+ monkeypatch.setattr(dc.os, "fsync", real_fsync)
+ assert dc.read_checkpoint(run_dir / "checkpoint-2") is not None
+
+
+def test_re_saving_the_bundle_this_run_resumed_from_keeps_it(run_dir):
+ # Resuming at N and stopping before N+1 re-saves byte-identical state, so keeping what is
+ # there avoids _promote's one destructive branch (swapping a good bundle out to make room),
+ # where a kill would leave the slot empty.
+ run = _Run(run_dir)
+ first, _ = run.save(9)
+ before = (run_dir / "checkpoint-9" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ resumed = _Run(run_dir, resume_from_checkpoint = str(run_dir / "checkpoint-9"))
+ second, error = resumed.save(9)
+ assert error is None and second == first
+ assert (run_dir / "checkpoint-9" / dc.TRAINER_STATE_FILENAME).read_text(
+ encoding = "utf-8"
+ ) == before
+
+
+def test_a_same_step_bundle_from_another_run_is_overwritten(run_dir):
+ # The dangerous half of the same arithmetic: resume checkpoint-10 in a folder that also
+ # holds checkpoint-15 and stop at 15. The old shortcut saw "step 15 already exists" and
+ # returned it, so checkpoint_saved named a bundle whose optimizer, scheduler, sampler and
+ # RNG were from the EARLIER run and this run's state was dropped on the floor.
+ seeded = _Run(run_dir)
+ seeded.save(10)
+ seeded.step_once(0.5)
+ seeded.save(15)
+ stale = (run_dir / "checkpoint-15" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+
+ resumed = _Run(run_dir, seed = 7, resume_from_checkpoint = str(run_dir / "checkpoint-10"))
+ resumed.step_once(1.5)
+ path, error = resumed.save(15)
+
+ assert error is None and path == str(run_dir / "checkpoint-15")
+ written = dc.read_checkpoint(run_dir / "checkpoint-15")
+ assert written is not None
+ # It is this run's state now, not the one that was sitting there.
+ assert (run_dir / "checkpoint-15" / dc.TRAINER_STATE_FILENAME).read_text(
+ encoding = "utf-8"
+ ) != stale
+ from safetensors.torch import load_file
+
+ restored = load_file(run_dir / "checkpoint-15" / dc.ADAPTER_FILENAME)
+ assert torch.allclose(restored["weight"], resumed.model.weight)
+
+
+def test_incomplete_or_inconsistent_bundles_are_rejected(run_dir):
+ run = _Run(run_dir)
+ run.save(4)
+ good = run_dir / "checkpoint-4"
+ assert dc.read_checkpoint(good) is not None
+
+ # No manifest at all (the completion marker) -> not a checkpoint.
+ (good / dc.TRAINER_STATE_FILENAME).unlink()
+ assert dc.read_checkpoint(good) is None
+ assert dc.latest_valid_checkpoint(run_dir) is None
+
+ # A manifest whose step disagrees with its directory name is a rename, not a checkpoint.
+ run.save(5)
+ manifest_path = run_dir / "checkpoint-5" / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest["global_step"] = 4
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+ assert dc.read_checkpoint(run_dir / "checkpoint-5") is None
+
+ # A truncated tensor file fails the state-file probe even with a perfect manifest.
+ run.save(6)
+ (run_dir / "checkpoint-6" / dc.ADAPTER_FILENAME).write_bytes(b"")
+ assert dc.read_checkpoint(run_dir / "checkpoint-6") is None
+ state = dc.describe_resume_state(str(run_dir))
+ assert state["can_resume"] is False
+ assert "incomplete or corrupt" in state["resume_blocked_reason"]
+
+
+def test_a_fresh_run_discards_an_earlier_runs_checkpoints(run_dir):
+ # Training a NEW run into an output dir a previous run already used (same adapter name) must
+ # not leave the old, higher-numbered bundles behind: latest_valid_checkpoint would pick one of
+ # them and a later Resume would silently continue the wrong training.
+ old = _Run(run_dir)
+ old.save(40)
+ assert dc.latest_valid_checkpoint(run_dir)[1]["global_step"] == 40
+
+ fresh = _Run(run_dir, seed = 7)
+ fresh.save(5, discard_existing = True)
+ assert [p.name for p in dc.list_checkpoints(run_dir)] == ["checkpoint-5"]
+ assert dc.describe_resume_state(str(run_dir))["checkpoint_step"] == 5
+
+
+def test_a_checkpoint_with_no_adapter_tensors_is_refused(run_dir):
+ # An empty safetensors file has no keys, so the bundle would fail its own validation and read
+ # as "no checkpoint": a run that thinks it saved but cannot be resumed.
+ with pytest.raises(ValueError, match = "no adapter tensors"):
+ dc.save_checkpoint(
+ output_dir = str(run_dir),
+ step = 1,
+ adapter_state = {},
+ identity = _identity(),
+ target_steps = 10,
+ )
+ assert dc.list_checkpoints(run_dir) == []
+
+
+def test_non_finite_progress_is_dropped_from_the_manifest(run_dir):
+ run = _Run(run_dir)
+ run.save(2, progress = {"running_loss": float("nan"), "kept": 1.5})
+ manifest = dc.read_checkpoint(run_dir / "checkpoint-2")
+ assert manifest["progress"] == {"kept": 1.5}
+ # And the file is strict JSON (no bare NaN token that a stricter parser would reject).
+ raw = (run_dir / "checkpoint-2" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ assert "NaN" not in raw and "Infinity" not in raw
+ assert dc.load_checkpoint(run_dir / "checkpoint-2").running_loss == 0.0
+
+
+def test_save_total_limit_keeps_only_the_newest_bundles(run_dir):
+ run = _Run(run_dir, save_total_limit = 2)
+ for step in (1, 2, 3, 4):
+ run.save(step)
+ kept = sorted(p.name for p in dc.list_checkpoints(run_dir))
+ assert kept == ["checkpoint-3", "checkpoint-4"]
+
+
+# ── state round-trip ──────────────────────────────────────────────────────────
+def test_bundle_round_trips_optimizer_scheduler_sampler_and_rng(run_dir):
+ reference = _Run(run_dir, seed = 3)
+ for i in range(11):
+ reference.step_once(0.01 * (i + 1))
+ reference.sampler.next_batch(2)
+ path, error = reference.save(11)
+ assert error is None and Path(path).name == "checkpoint-11"
+
+ # Keep training the reference, and separately resume a fresh run from the bundle.
+ resumed = _Run(run_dir, seed = 999) # a different seed: everything must come from the file
+ resumed.cfg = __import__("dataclasses").replace(
+ resumed.cfg, resume_from_checkpoint = str(run_dir)
+ )
+ loaded = resumed.restore()
+ assert loaded is not None and loaded.step == 11
+
+ # Adapter weights, LR-schedule position and sampler cycle all match immediately.
+ assert torch.equal(resumed.model.weight, reference.model.weight)
+ assert resumed.lr_sched.get_last_lr() == reference.lr_sched.get_last_lr()
+ assert resumed.sampler.state_dict() == reference.sampler.state_dict()
+ # ... and so do the RNG streams, which decide the next batch and the next noise draw.
+ assert resumed.loop_rng.random() == reference.loop_rng.random()
+ assert resumed.variant_rng.random() == reference.variant_rng.random()
+
+ # The optimizer MOMENTS are what a naive "reload the adapter" resume loses: the same
+ # gradient must therefore move both models to the same place, not just start from it.
+ for i in range(11, 16):
+ grad = 0.01 * (i + 1)
+ reference.step_once(grad)
+ resumed.step_once(grad)
+ assert torch.allclose(resumed.model.weight, reference.model.weight, atol = 0, rtol = 0)
+ assert resumed.lr_sched.get_last_lr() == reference.lr_sched.get_last_lr()
+
+
+def test_a_foreign_optimizers_state_is_refused_instead_of_key_erroring(run_dir):
+ # The trainers choose their optimizer from the HOST (bitsandbytes present, a fused kernel
+ # available, UNSLOTH_DIFFUSION_FP32_OPTIM), not the config, so a checkpoint can arrive with
+ # moments from a different implementation. Shapes and counts match, so load_state_dict
+ # accepts them and the first step dies on a bare KeyError deep in the optimizer.
+ run = _Run(run_dir)
+ run.save(3)
+ manifest_path = run_dir / "checkpoint-3" / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ assert manifest["optimizer_class"] == "torch.optim.adamw.AdamW"
+ manifest["optimizer_class"] = "bitsandbytes.optim.adamw.AdamW8bit"
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ fresh = _Run(run_dir)
+ fresh.cfg = __import__("dataclasses").replace(fresh.cfg, resume_from_checkpoint = str(run_dir))
+ with pytest.raises(dc.ResumeError, match = "AdamW8bit"):
+ fresh.restore()
+
+
+def test_a_partial_adapter_restore_is_refused(run_dir):
+ # A name mismatch would otherwise leave restored optimizer moments and a restored LR position
+ # driving freshly initialised LoRA weights, while the run reports a normal resume.
+ run = _Run(run_dir)
+ run.save(3)
+ from safetensors.torch import save_file
+
+ adapter = run_dir / "checkpoint-3" / dc.ADAPTER_FILENAME
+ save_file(
+ {"weight": torch.zeros(4, 4), "renamed.weight": torch.zeros(4, 4)},
+ str(adapter),
+ )
+ # Rewriting a bundle by hand changes the adapter's size, which read_checkpoint now checks
+ # against the manifest. Keep it honest, or this exercises the truncation guard instead of
+ # the name-mismatch guard it is here for.
+ manifest_path = run_dir / "checkpoint-3" / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest["file_sizes"]["adapter"] = adapter.stat().st_size
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ fresh = _Run(run_dir)
+ fresh.cfg = __import__("dataclasses").replace(fresh.cfg, resume_from_checkpoint = str(run_dir))
+ with pytest.raises(ValueError, match = "not in this run"):
+ fresh.restore()
+
+
+def test_resuming_reapplies_the_live_lr_schedule(run_dir):
+ # load_state_dict restores the rate the checkpoint was written with and never re-evaluates
+ # the lambda, so without the re-apply the first resumed step runs at the OLD schedule's
+ # value -- lr 0.0 when continuing a finished cosine run by raising the step count.
+ from diffusers.optimization import get_scheduler
+
+ def build(total: int):
+ torch.manual_seed(0)
+ model = torch.nn.Linear(4, 4, bias = False)
+ optimizer = torch.optim.AdamW(model.parameters(), lr = 1e-3)
+ return (
+ model,
+ optimizer,
+ get_scheduler(
+ "cosine", optimizer = optimizer, num_warmup_steps = 0, num_training_steps = total
+ ),
+ )
+
+ model, optimizer, lr_sched = build(6)
+ for _ in range(6):
+ model.weight.grad = torch.full_like(model.weight, 0.01)
+ optimizer.step()
+ lr_sched.step()
+ assert lr_sched.get_last_lr()[0] == pytest.approx(0.0, abs = 1e-12)
+ dc.save_checkpoint(
+ output_dir = str(run_dir),
+ step = 6,
+ adapter_state = {"weight": model.weight.detach()},
+ identity = _identity(),
+ target_steps = 6,
+ optimizer = optimizer,
+ lr_scheduler = lr_sched,
+ # A real bundle carries both, and the preflight now insists on them.
+ rng = dc.capture_rng_state(_STREAMS()),
+ sampler_state = {"n": 1, "order": [0], "pos": 0},
+ )
+
+ # Continue the same run with a raised target: the rate must come from the NEW 12-step curve.
+ model2, optimizer2, lr_sched2 = build(12)
+ cfg = DiffusionLoraConfig(
+ base_model = "stabilityai/sdxl-turbo",
+ data_dir = "unused",
+ output_dir = str(run_dir),
+ train_steps = 12,
+ resume_from_checkpoint = str(run_dir),
+ )
+ restored = restore_resume_state(
+ cfg,
+ model = model2,
+ optimizer = optimizer2,
+ lr_scheduler = lr_sched2,
+ identity = _identity(),
+ )
+ assert restored.step == 6
+ reference = build(12)[2]
+ for _ in range(6):
+ reference.step()
+ assert optimizer2.param_groups[0]["lr"] == pytest.approx(reference.get_last_lr()[0])
+ assert optimizer2.param_groups[0]["lr"] > 0.0
+
+
+def test_torch_rng_state_is_restored(run_dir):
+ run = _Run(run_dir, seed = 5)
+ run.save(1)
+ expected = torch.randn(8)
+
+ torch.manual_seed(12345) # move the global RNG somewhere else entirely
+ fresh = _Run(run_dir, seed = 5)
+ fresh.cfg = __import__("dataclasses").replace(fresh.cfg, resume_from_checkpoint = str(run_dir))
+ fresh.restore()
+ assert torch.equal(torch.randn(8), expected)
+
+
[email protected](not torch.cuda.is_available(), reason = "bitsandbytes AdamW8bit needs CUDA")
+def test_bitsandbytes_adamw8bit_state_round_trips(run_dir):
+ # The default diffusion optimizer is bnb AdamW8bit, whose moments are quantized uint8 plus
+ # their maps. torch.save/load must carry them exactly, or a "resumed" run silently restarts
+ # Adam from zero moments and spikes the loss.
+ bnb = pytest.importorskip("bitsandbytes")
+ if not isinstance(getattr(bnb.optim, "AdamW8bit", None), type):
+ # unsloth_zoo replaces bitsandbytes with a raising stub on hosts without it; the suite
+ # imports unsloth first, so that stub can be live even where real bnb is installed.
+ pytest.skip("bitsandbytes is stubbed out in this environment")
+
+ torch.manual_seed(0)
+ # Above bitsandbytes' min_8bit_size (4096): a smaller parameter gets plain fp32 moments, so
+ # the quantized state -- the part that actually needs a round-trip -- would never be written.
+ param = torch.nn.Parameter(torch.randn(128, 64, device = "cuda"))
+ optimizer = bnb.optim.AdamW8bit([param], lr = 1e-3)
+ for i in range(4):
+ param.grad = torch.full_like(param, 0.01 * (i + 1))
+ optimizer.step()
+ quant = next(iter(optimizer.state.values()))
+ quant = quant.get("__bnb_optimizer_quant_state__", quant)
+ assert any(getattr(v, "dtype", None) is torch.uint8 for v in quant.values())
+
+ dc.save_checkpoint(
+ output_dir = str(run_dir),
+ step = 4,
+ adapter_state = {"w": param.detach()},
+ identity = _identity(),
+ target_steps = 10,
+ optimizer = optimizer,
+ )
+ loaded = dc.load_checkpoint(run_dir / "checkpoint-4")
+
+ clone = torch.nn.Parameter(param.detach().clone())
+ restored = bnb.optim.AdamW8bit([clone], lr = 1e-3)
+ restored.load_state_dict(loaded.torch_state("optimizer"))
+ for i in range(4, 8):
+ grad = torch.full_like(param, 0.01 * (i + 1))
+ param.grad = grad.clone()
+ optimizer.step()
+ clone.grad = grad.clone()
+ restored.step()
+ assert torch.equal(clone, param)
+
+
+# ── the loop resumes at N+1 up to the same TARGET ─────────────────────────────
+def _loop(run: _Run, *, stop_at: int | None = None) -> tuple[list[int], int]:
+ """The exact shape of both trainers' loops: restore, then ``range(resumed, train_steps)``
+ with ``done = opt_step + 1``."""
+ restored = run.restore()
+ resumed = restored.step if restored is not None else 0
+ done = resumed
+ seen: list[int] = []
+ for opt_step in range(resumed, run.cfg.train_steps):
+ run.step_once(0.001)
+ run.sampler.next_batch(2)
+ done = opt_step + 1
+ seen.append(done)
+ if stop_at is not None and done == stop_at:
+ break
+ return seen, done
+
+
+def test_resume_at_step_11_with_target_500_runs_steps_12_to_500(run_dir):
+ first = _Run(run_dir, seed = 1)
+ seen, done = _loop(first, stop_at = 11)
+ assert seen == list(range(1, 12)) and done == 11
+ # Stop-and-save writes the bundle at the step actually reached.
+ path, error = first.save(done)
+ assert error is None and Path(path).name == "checkpoint-11"
+
+ second = _Run(run_dir, seed = 1)
+ second.cfg = __import__("dataclasses").replace(second.cfg, resume_from_checkpoint = str(run_dir))
+ seen, done = _loop(second)
+ # train_steps is the TARGET TOTAL, not an extra budget: 12..500, then the run is finished.
+ assert seen[0] == 12
+ assert seen[-1] == 500
+ assert seen == list(range(12, 501))
+ assert done == 500
+ assert len(seen) == 489
+
+
+def test_resume_of_a_finished_checkpoint_is_refused(run_dir):
+ run = _Run(run_dir)
+ run.save(500)
+ with pytest.raises(dc.ResumeError, match = "already at step 500 of 500"):
+ dc.preflight_resume(str(run_dir), identity = run.identity, target_steps = 500)
+
+
+def test_both_trainers_loop_from_the_resumed_step():
+ # The two real loops are GPU-only, so guard their bound structurally: a regression back to
+ # ``range(cfg.train_steps)`` would silently retrain steps the checkpoint already covered.
+ backend = Path(__file__).resolve().parent.parent
+ for name in ("diffusion_lora_trainer.py", "diffusion_dit_trainer.py"):
+ source = (backend / "core" / "training" / name).read_text(encoding = "utf-8")
+ loops = [
+ ast.unparse(node.iter)
+ for node in ast.walk(ast.parse(source))
+ if isinstance(node, ast.For)
+ and isinstance(node.target, ast.Name)
+ and node.target.id == "opt_step"
+ ]
+ assert loops == ["range(resumed, cfg.train_steps)"], f"{name}: {loops}"
+
+
+# ── the identity gate ─────────────────────────────────────────────────────────
+ ("overrides", "expected"),
+ [
+ ({"family": "flux.1"}, "different model family"),
+ ({"base_model": "black-forest-labs/FLUX.1-dev"}, "different base model"),
+ ({"lora_rank": 32}, "different LoRA rank"),
+ ({"lora_alpha": 8}, "different LoRA alpha"),
+ ({"lora_target_modules": ("to_q",)}, "different LoRA target modules"),
+ ({"precision": "fp16"}, "different mixed precision"),
+ ({"base_precision": "bf16"}, "different base precision"),
+ ({"kind": "video"}, "different training type"),
+ ({"dataset_fingerprint": "ds-4-beef"}, "training images have changed"),
+ ],
+)
+def test_identity_mismatches_are_rejected_with_a_clear_reason(run_dir, overrides, expected):
+ run = _Run(run_dir)
+ run.save(3)
+ with pytest.raises(dc.ResumeError, match = expected):
+ dc.preflight_resume(str(run_dir), identity = _identity(**overrides), target_steps = 500)
+ # The matching identity still passes, so the rejection is the mismatch and nothing else.
+ path, step = dc.preflight_resume(str(run_dir), identity = _identity(), target_steps = 500)
+ assert step == 3 and Path(path).name == "checkpoint-3"
+
+
+def test_unknown_revision_or_dataset_on_either_side_is_not_a_mismatch(run_dir):
+ # source_revision() reads "unresolved" for a repo that is not in the local Hub cache, and the
+ # start route computes the identity before it has walked the dataset. Neither may look like a
+ # changed base model / changed images, or every first resume would be refused.
+ run = _Run(run_dir)
+ run.identity = _identity(base_revision = "unresolved")
+ run.save(3)
+ dc.preflight_resume(
+ str(run_dir), identity = _identity(base_revision = "rev-something"), target_steps = 500
+ )
+ dc.preflight_resume(
+ str(run_dir), identity = _identity(dataset_fingerprint = None), target_steps = 500
+ )
+
+
+def test_resume_path_must_stay_inside_the_outputs_root(tmp_path):
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ with pytest.raises(dc.ResumeError, match = "inside Unsloth outputs"):
+ dc.resolve_resume_dir(str(outside))
+
+
+def test_resume_of_a_run_without_checkpoints_is_refused(run_dir):
+ with pytest.raises(dc.ResumeError, match = "No complete training checkpoint"):
+ dc.preflight_resume(str(run_dir), identity = _identity(), target_steps = 500)
+
+
+# ── route preflight: reject BEFORE evicting the GPU ───────────────────────────
+class _FakeService:
+ def __init__(self):
+ self.calls: list[str] = []
+ self.started_with: dict | None = None
+
+ def reserve(self):
+ self.calls.append("reserve")
+
+ def unreserve(self):
+ self.calls.append("unreserve")
+
+ def is_active(self):
+ return False
+
+ def start(self, config):
+ self.calls.append("start")
+ self.started_with = config
+ return "job-123"
+
+
+class _FakeLLMBackend:
+ def is_training_active(self):
+ return False
+
+
+_PAIRS = [("img.png", "a caption")]
+
+
+def client(monkeypatch):
+ import routes.training as tr
+
+ fake = _FakeService()
+ freed: list[str] = []
+ monkeypatch.setattr(
+ "core.training.diffusion_training_service.get_diffusion_training_service", lambda: fake
+ )
+ monkeypatch.setattr(tr, "get_training_backend", lambda: _FakeLLMBackend())
+ monkeypatch.setattr(tr, "_free_gpu_for_diffusion_training", lambda: freed.append("freed"))
+ monkeypatch.setattr(
+ "core.training.diffusion_train_common.discover_image_caption_pairs",
+ lambda data_dir, **kw: list(_PAIRS),
+ )
+ app = FastAPI()
+ app.include_router(training_router, prefix = "/api/train")
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ app.dependency_overrides[authenticated_via_api_key] = lambda: False
+ c = TestClient(app)
+ c._fake = fake # type: ignore[attr-defined]
+ c._freed = freed # type: ignore[attr-defined]
+ return c
+
+
+def _request_identity(**overrides) -> dc.CheckpointIdentity:
+ """The identity the start route computes for ``_RESUME_BODY`` + the stubbed dataset."""
+ return _identity(
+ **{
+ "base_revision": "unresolved",
+ "dataset_fingerprint": dc.dataset_fingerprint(_PAIRS),
+ **overrides,
+ }
+ )
+
+
+_RESUME_BODY = {
+ "base_model": "stabilityai/sdxl-turbo",
+ "data_dir": "uploads/my-images",
+ "output_dir": "my-lora-run",
+ "train_steps": 500,
+ "resume_from_checkpoint": "my-lora-run",
+}
+
+
+def _write_bundle(run_dir: Path, step: int, identity: dc.CheckpointIdentity) -> None:
+ # A real bundle carries optimizer and scheduler state, and the route preflight now insists
+ # on it, so the fixture has to be a bundle the trainer would actually accept.
+ param = torch.nn.Parameter(torch.zeros(2, 2))
+ optimizer = torch.optim.AdamW([param], lr = 1e-3)
+ dc.save_checkpoint(
+ output_dir = str(run_dir),
+ step = step,
+ adapter_state = {"w": torch.zeros(2, 2)},
+ identity = identity,
+ target_steps = 500,
+ optimizer = optimizer,
+ lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda _: 1.0),
+ rng = dc.capture_rng_state(_STREAMS()),
+ sampler_state = {"n": 1, "order": [0], "pos": 0},
+ )
+
+
+def test_route_resume_accepts_a_matching_checkpoint_and_pins_it(client, run_dir):
+ _write_bundle(run_dir, 11, _request_identity())
+ r = client.post("/api/train/diffusion/start", json = _RESUME_BODY)
+ assert r.status_code == 200, r.text
+ # The exact bundle the preflight accepted is what the trainer gets, not "whatever is newest
+ # in that folder by the time the child runs".
+ pinned = Path(client._fake.started_with["resume_from_checkpoint"])
+ assert pinned == run_dir / "checkpoint-11"
+ assert client._freed == ["freed"]
+
+
+def test_route_resume_mismatch_400s_without_evicting_the_gpu(client, run_dir):
+ _write_bundle(run_dir, 11, _request_identity(family = "flux.1"))
+ r = client.post("/api/train/diffusion/start", json = _RESUME_BODY)
+ assert r.status_code == 400, r.text
+ assert "different model family" in r.json()["detail"]
+ # The whole point of preflighting here: the user's loaded Images pipeline survives a refusal.
+ assert client._freed == []
+ assert "start" not in client._fake.calls
+
+
+def test_route_resume_dataset_change_400s_without_evicting_the_gpu(client, run_dir):
+ # The dataset half of the identity is only knowable after discovery, which the route runs
+ # inside the reservation -- still before the GPU teardown.
+ _write_bundle(run_dir, 11, _request_identity(dataset_fingerprint = "ds-9-other"))
+ r = client.post("/api/train/diffusion/start", json = _RESUME_BODY)
+ assert r.status_code == 400, r.text
+ assert "training images have changed" in r.json()["detail"]
+ assert client._freed == []
+ assert "start" not in client._fake.calls
+ # The reservation is always released, so the next start is not locked out by the refusal.
+ assert client._fake.calls.count("unreserve") == 1
+
+
+def test_route_resume_missing_checkpoint_400s(client, run_dir):
+ r = client.post("/api/train/diffusion/start", json = _RESUME_BODY)
+ assert r.status_code == 400, r.text
+ assert "No complete training checkpoint" in r.json()["detail"]
+ assert client._freed == []
+
+
+def test_route_resume_outside_outputs_400s(client, tmp_path):
+ body = {**_RESUME_BODY, "resume_from_checkpoint": str(tmp_path / "escape")}
+ r = client.post("/api/train/diffusion/start", json = body)
+ assert r.status_code == 400, r.text
+ assert client._freed == []
+
+
+def test_route_start_without_resume_is_unchanged(client, run_dir):
+ body = {k: v for k, v in _RESUME_BODY.items() if k != "resume_from_checkpoint"}
+ r = client.post("/api/train/diffusion/start", json = body)
+ assert r.status_code == 200, r.text
+ assert client._fake.started_with.get("resume_from_checkpoint") is None
+
+
+# ── can_resume in the run history ─────────────────────────────────────────────
+def runs_dir(tmp_path, monkeypatch):
+ import core.training.diffusion_training_service as dts
+
+ d = tmp_path / "runs" / "diffusion"
+ d.mkdir(parents = True, exist_ok = True)
+ monkeypatch.setattr(dts, "_runs_dir", lambda: d)
+ return d
+
+
+def _persist(job_id: str, status: str, output_dir: Path, **state):
+ from core.training.diffusion_training_service import DiffusionTrainingService, _idle_state
+
+ service = DiffusionTrainingService()
+ snapshot = _idle_state()
+ snapshot.update(
+ job_id = job_id,
+ status = status,
+ output_dir = str(output_dir),
+ lora_path = str(output_dir / "pytorch_lora_weights.safetensors"),
+ step = 11,
+ total_steps = 500,
+ **state,
+ )
+ service._state = snapshot
+ service._config = {"output_dir": str(output_dir), "base_model": "stabilityai/sdxl-turbo"}
+ service._persist_run_record()
+
+
+def test_can_resume_is_reported_per_run_state(runs_dir, run_dir):
+ from core.training.diffusion_training_service import get_diffusion_run, list_diffusion_runs
+
+ stopped_dir = run_dir
+ _write_bundle(stopped_dir, 11, _identity())
+ _persist("a" * 32, "stopped", stopped_dir)
+
+ # A completed run reached its target, so it is never resumable -- even though a periodic
+ # bundle from partway through is still sitting in its folder.
+ from utils.paths import outputs_root
+
+ completed_dir = outputs_root() / "done-run"
+ completed_dir.mkdir(parents = True, exist_ok = True)
+ _write_bundle(completed_dir, 450, _identity())
+ _persist("b" * 32, "completed", completed_dir)
+
+ # An errored run that DID reach a periodic checkpoint is exactly the case worth resuming.
+ errored_dir = outputs_root() / "crashed-run"
+ errored_dir.mkdir(parents = True, exist_ok = True)
+ _write_bundle(errored_dir, 40, _identity())
+ _persist("c" * 32, "error", errored_dir)
+
+ # A stop whose checkpoint write FAILED must stay blocked, with the writer's reason shown,
+ # even though an older bundle is still on disk (resuming it would silently lose steps).
+ blocked_dir = outputs_root() / "blocked-run"
+ blocked_dir.mkdir(parents = True, exist_ok = True)
+ _write_bundle(blocked_dir, 7, _identity())
+ _persist(
+ "d" * 32,
+ "stopped",
+ blocked_dir,
+ resume_blocked_reason = "Could not write a resume checkpoint at step 11: disk full",
+ )
+
+ by_id = {r["job_id"]: r for r in list_diffusion_runs(limit = 20)}
+ assert by_id["a" * 32]["can_resume"] is True
+ assert by_id["a" * 32]["checkpoint_step"] == 11
+ assert by_id["a" * 32]["output_dir"] == str(stopped_dir)
+
+ assert by_id["b" * 32]["can_resume"] is False
+ assert "nothing left to train" in by_id["b" * 32]["resume_blocked_reason"]
+
+ assert by_id["c" * 32]["can_resume"] is True
+ assert by_id["c" * 32]["checkpoint_step"] == 40
+
+ assert by_id["d" * 32]["can_resume"] is False
+ assert "disk full" in by_id["d" * 32]["resume_blocked_reason"]
+
+ # The detail endpoint agrees, and re-derives from disk: deleting the bundle takes the action
+ # away rather than leaving a button that would 400.
+ assert get_diffusion_run("a" * 32)["can_resume"] is True
+ dc.shutil.rmtree(stopped_dir / "checkpoint-11")
+ refreshed = get_diffusion_run("a" * 32)
+ assert refreshed["can_resume"] is False
+ assert "no resume checkpoint" in refreshed["resume_blocked_reason"]
+
+
+def test_can_resume_is_false_when_the_output_folder_is_gone(runs_dir, run_dir):
+ from core.training.diffusion_training_service import list_diffusion_runs
+
+ _write_bundle(run_dir, 11, _identity())
+ _persist("e" * 32, "stopped", run_dir)
+ dc.shutil.rmtree(run_dir)
+ (record,) = list_diffusion_runs(limit = 5)
+ assert record["can_resume"] is False
+ assert "no longer exists" in record["resume_blocked_reason"]
+
+
+def test_lineage_is_recorded(runs_dir, run_dir):
+ from core.training.diffusion_training_service import get_diffusion_run
+
+ _write_bundle(run_dir, 20, _identity())
+ from core.training.diffusion_training_service import DiffusionTrainingService, _idle_state
+
+ service = DiffusionTrainingService()
+ snapshot = _idle_state()
+ snapshot.update(
+ job_id = "f" * 32,
+ status = "stopped",
+ output_dir = str(run_dir),
+ lora_path = str(run_dir / "pytorch_lora_weights.safetensors"),
+ resumed_from_step = 11,
+ )
+ service._state = snapshot
+ service._config = {"output_dir": str(run_dir), "resumed_from_job_id": "a" * 32}
+ service._persist_run_record()
+
+ record = get_diffusion_run("f" * 32)
+ assert record["resumed_from_job_id"] == "a" * 32
+ assert record["resumed_from_step"] == 11
+
+
+def test_service_folds_the_resumed_and_checkpoint_events(runs_dir):
+ from core.training.diffusion_training_service import DiffusionTrainingService
+
+ service = DiffusionTrainingService()
+ service._apply_event({"type": "resumed", "step": 11, "checkpoint_path": "/x/checkpoint-11"})
+ snapshot = service.status()
+ # The step resumed FROM is lineage, not a bundle this run wrote.
+ assert snapshot["resumed_from_step"] == 11
+ assert snapshot["checkpoint_step"] is None
+
+ # Folded as each bundle lands, so a run that CRASHES after one is still known to be resumable.
+ service._apply_event(
+ {"type": "checkpoint_saved", "step": 40, "checkpoint_path": "/x/checkpoint-40"}
+ )
+ snapshot = service.status()
+ assert snapshot["checkpoint_step"] == 40
+ assert snapshot["checkpoint_path"] == "/x/checkpoint-40"
+ assert snapshot["resume_blocked_reason"] is None
+
+ # A failed write is sticky: the older bundle predates the work this run did.
+ service._apply_event({"type": "checkpoint_failed", "step": 50, "message": "disk full"})
+ assert service.status()["resume_blocked_reason"] == "disk full"
+ # ...and a later good write clears it again.
+ service._apply_event(
+ {"type": "checkpoint_saved", "step": 60, "checkpoint_path": "/x/checkpoint-60"}
+ )
+ assert service.status()["resume_blocked_reason"] is None
+
+ service._apply_event(
+ {
+ "type": "complete",
+ "stopped": True,
+ "output_dir": "/x",
+ "lora_path": "/x/pytorch_lora_weights.safetensors",
+ "resumed_from_step": 11,
+ }
+ )
+ snapshot = service.status()
+ assert snapshot["checkpoint_step"] == 60
+ assert snapshot["resumed_from_step"] == 11
+ assert snapshot["status"] == "stopped"
+
+
+def test_a_checkpoint_write_failure_blocks_resume_on_a_crashed_run(runs_dir, run_dir):
+ # The failure arrives on its own event, so it survives a run that ends in `error` rather than
+ # `complete` -- the case where an older bundle is most likely to still be lying around.
+ from core.training.diffusion_training_service import DiffusionTrainingService, get_diffusion_run
+
+ _write_bundle(run_dir, 7, _identity())
+ service = DiffusionTrainingService()
+ service._state.update(job_id = "1" * 32, started_at = 0.0, total_steps = 500)
+ service._config = {"output_dir": str(run_dir)}
+ service._apply_event({"type": "checkpoint_failed", "step": 20, "message": "disk full"})
+ service._apply_event({"type": "error", "message": "CUDA out of memory"})
+ service._persist_run_record()
+
+ record = get_diffusion_run("1" * 32)
+ assert record["status"] == "error"
+ assert record["can_resume"] is False
+ assert record["resume_blocked_reason"] == "disk full"
+
+
+def test_an_earlier_runs_checkpoints_are_not_offered_to_a_later_run(runs_dir, run_dir):
+ # Two runs can share an output dir (same adapter name trained twice) and the EARLIER one's
+ # bundles can carry higher step numbers. A later run must not advertise, and then resume,
+ # another run's training state.
+ import time as _time
+
+ from core.training.diffusion_training_service import get_diffusion_run
+
+ _write_bundle(run_dir, 400, _identity())
+ later_start = _time.time() + 1.0
+ _persist("2" * 32, "stopped", run_dir, started_at = later_start)
+
+ record = get_diffusion_run("2" * 32)
+ assert record["can_resume"] is False
+ assert "left by an earlier run" in record["resume_blocked_reason"]
+
+ # The run that actually wrote it still sees it.
+ _persist("3" * 32, "stopped", run_dir, started_at = later_start - 60.0)
+ assert get_diffusion_run("3" * 32)["checkpoint_step"] == 400
+
+
+# ── the sidecar records the step actually reached ─────────────────────────────
+def test_lora_sidecar_records_the_reached_step(tmp_path, monkeypatch):
+ from core.inference import diffusion_lora as dl
+ from core.training.diffusion_train_common import _publish_to_lora_catalog
+
+ loras = tmp_path / "loras"
+ loras.mkdir()
+ monkeypatch.setattr(dl, "loras_dir", lambda: loras)
+
+ source = tmp_path / "run" / "pytorch_lora_weights.safetensors"
+ source.parent.mkdir(parents = True)
+ source.write_bytes(b"weights")
+ cfg = DiffusionLoraConfig(
+ base_model = "stabilityai/sdxl-turbo",
+ data_dir = "unused",
+ output_dir = str(tmp_path / "run"),
+ train_steps = 500,
+ ).normalized()
+
+ # Stopped at step 11 of a 500-step run: the sidecar used to advertise the CONFIGURED 500.
+ published = _publish_to_lora_catalog(str(source), cfg, 11)
+ sidecar = json.loads(Path(published).with_suffix(".json").read_text(encoding = "utf-8"))
+ assert sidecar["steps"] == 11
+
+ # Omitted, it still falls back to train_steps for callers that do not know the reached step.
+ fallback = _publish_to_lora_catalog(str(source), cfg)
+ meta = json.loads(Path(fallback).with_suffix(".json").read_text(encoding = "utf-8"))
+ assert meta["steps"] == 500
+
+
+# ── config validation ─────────────────────────────────────────────────────────
+def test_checkpoint_config_is_validated_and_normalized():
+ def build(**kw):
+ return DiffusionLoraConfig(
+ base_model = "stabilityai/sdxl-turbo",
+ data_dir = "unused",
+ output_dir = "run",
+ **kw,
+ )
+
+ # Off by default: no periodic checkpoints unless asked for.
+ assert build().normalized().save_steps == 0
+ assert build(save_steps = 50).normalized().save_steps == 50
+ with pytest.raises(ValueError, match = "save_steps must be >= 0"):
+ build(save_steps = -1).normalized()
+ with pytest.raises(ValueError, match = "save_total_limit must be >= 0"):
+ build(save_total_limit = -2).normalized()
+ # A blank resume path is "fresh run", not the outputs root.
+ assert build(resume_from_checkpoint = " ").normalized().resume_from_checkpoint is None
+ assert (
+ build(resume_from_checkpoint = " outputs/run ").normalized().resume_from_checkpoint
+ == "outputs/run"
+ )
+
+
+def test_sampler_state_round_trips_and_rejects_a_foreign_dataset_size():
+ import random
+
+ reference = PermutationBatchSampler(7, random.Random(0))
+ reference.next_batch(5)
+ state = reference.state_dict()
+ # The two indices left in the current cycle. Beyond them the sampler reshuffles from its rng,
+ # which the RNG snapshot restores separately, so this asserts only what the state owns.
+ expected = reference.next_batch(2)
+
+ # A sampler seeded differently still continues the SAME cycle once the state is loaded: the
+ # order is stored, not just the position, so a partly consumed permutation is reproduced.
+ clone = PermutationBatchSampler(7, random.Random(99))
+ clone.load_state_dict(state)
+ assert clone.next_batch(2) == expected
+
+ # A state for a different dataset size is ignored rather than indexing out of range.
+ other = PermutationBatchSampler(3, random.Random(0))
+ other.load_state_dict(state)
+ assert all(0 <= i < 3 for i in other.next_batch(10))
+
+
+# ── the header parse is not a load ────────────────────────────────────────────
+
+
+def test_a_truncated_tensor_storage_is_refused(run_dir):
+ """The state-file validator walks a torch zip's pickle to STOP and wants one non-empty
+ ``data/`` member. Truncating the moment STORAGES leaves both intact, and ``torch.load``
+ then hands back uninitialized memory -- non-finite, order 1e22 -- which a resume feeds
+ into the optimizer as Adam moments. The run diverges on its first step and reports a
+ clean resume while doing it. The recorded size is what catches this."""
+ import zipfile
+
+ run = _Run(run_dir)
+ run.step_once(0.5)
+ run.save(2)
+ optimizer_pt = run_dir / "checkpoint-2" / dc.OPTIMIZER_FILENAME
+ assert dc.read_checkpoint(run_dir / "checkpoint-2") is not None
+
+ with zipfile.ZipFile(optimizer_pt) as src:
+ members = [(i, src.read(i.filename)) for i in src.infolist()]
+ with zipfile.ZipFile(optimizer_pt, "w") as dst:
+ for info, blob in members:
+ # Every tensor storage clipped to one byte; the pickle and the header survive.
+ if "/data/" in info.filename and len(blob) > 1:
+ blob = blob[:1]
+ dst.writestr(info.filename, blob)
+
+ assert dc.read_checkpoint(run_dir / "checkpoint-2") is None
+ fresh = _Run(run_dir)
+ fresh.cfg = __import__("dataclasses").replace(fresh.cfg, resume_from_checkpoint = str(run_dir))
+ with pytest.raises(dc.ResumeError):
+ fresh.restore()
+
+
+def test_a_bundle_torch_load_refuses_is_rejected_by_the_preflight(run_dir):
+ """A ``.pt`` carrying a global outside the ``weights_only`` allowlist walks to STOP like
+ any other, so the header check passes it. Before the preflight actually loaded, the start
+ route returned 200, evicted the resident GPU model, and only then did the child die on a
+ raw UnpicklingError -- exactly what the preflight exists to prevent."""
+ run = _Run(run_dir)
+ run.save(2)
+ checkpoint = run_dir / "checkpoint-2"
+ # eval is not in the weights_only allowlist; the zip still parses.
+ torch.save({"boom": eval}, str(checkpoint / dc.SCHEDULER_FILENAME), pickle_protocol = 2)
+ manifest_path = checkpoint / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest["file_sizes"]["scheduler"] = (checkpoint / dc.SCHEDULER_FILENAME).stat().st_size
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ # The cheap gate still passes it -- that is the point.
+ assert dc.read_checkpoint(checkpoint) is not None
+ with pytest.raises(dc.ResumeError, match = "scheduler"):
+ dc.preflight_resume(str(checkpoint), identity = _identity(), target_steps = 500)
+
+
+# ── two runs sharing an output directory ──────────────────────────────────────
+
+
+def test_a_finished_run_does_not_offer_its_successors_checkpoint(run_dir):
+ """``not_before`` fences off an EARLIER run's bundles. Without the matching upper fence a
+ finished run still sees every bundle a LATER run wrote into the shared folder and offers
+ the newest of them as its own. The identity gate cannot catch it -- same family, base,
+ dataset and LoRA shape -- so the earlier run would resume its successor's optimizer
+ moments, LR position and RNG under its own config."""
+ early = _Run(run_dir)
+ early.save(10)
+ early_manifest = json.loads(
+ (run_dir / "checkpoint-10" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ )
+ early_created = early_manifest["created_at"]
+ early_started = early_created - 1.0
+
+ later = _Run(run_dir)
+ later.save(50)
+ later_created = json.loads(
+ (run_dir / "checkpoint-50" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ )["created_at"]
+ assert later_created > early_created, "fixture did not order the two runs"
+ # The first run ended between the two saves.
+ early_ended = (early_created + later_created) / 2.0
+
+ fenced = dc.describe_resume_state(
+ str(run_dir), status = "stopped", started_at = early_started, ended_at = early_ended
+ )
+ assert fenced["checkpoint_step"] == 10
+ assert fenced["checkpoint_path"].endswith("checkpoint-10")
+
+ # The later run, with no upper fence of its own yet, still sees its own newest.
+ live = dc.describe_resume_state(
+ str(run_dir), status = "stopped", started_at = early_ended, ended_at = None
+ )
+ assert live["checkpoint_step"] == 50
+
+
+def test_a_bundle_with_no_created_at_survives_the_upper_fence(run_dir):
+ """An older bundle predates ``created_at`` and reads 0.0. Fencing it out by an end time
+ would make every pre-existing run unresumable, which is the opposite of the point."""
+ run = _Run(run_dir)
+ run.save(4)
+ manifest_path = run_dir / "checkpoint-4" / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ del manifest["created_at"]
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ found = dc.latest_valid_checkpoint(run_dir, not_after = 1.0)
+ assert found is not None and dc.checkpoint_step(found[0]) == 4
+
+
+# ── RNG restore across a change in visible devices ────────────────────────────
+
+
+def test_cuda_rng_restores_the_devices_the_bundle_covers(monkeypatch):
+ """A bundle written with one device visible, restored where two are.
+
+ ``set_rng_state_all`` needs one state per visible device, and guarding that with
+ all-or-nothing meant this case restored NOTHING -- including cuda:0, the only device the
+ trainer touches. Every other part of the resume looked correct, so the run finished
+ healthy and silently wrong: on a real B200 SDXL run all 192 LoRA tensors diverged from
+ the uninterrupted control. The trainer is a spawned child inheriting
+ CUDA_VISIBLE_DEVICES, so a change to the mask between the run and the Resume click was
+ enough to trigger it."""
+ restored: list[tuple[int, bytes]] = []
+
+ fake_cuda = type(
+ "FakeCuda",
+ (),
+ {
+ "is_available": staticmethod(lambda: True),
+ "device_count": staticmethod(lambda: 2),
+ "set_rng_state": staticmethod(
+ lambda state, index: restored.append((index, bytes(state.tolist())))
+ ),
+ "set_rng_state_all": staticmethod(
+ lambda states: pytest.fail("must not need every device")
+ ),
+ },
+ )()
+ monkeypatch.setattr(torch, "cuda", fake_cuda)
+
+ only_device_zero = torch.tensor([7, 8, 9], dtype = torch.uint8)
+ dc.restore_rng_state({}, {"torch_cuda_0": only_device_zero})
+
+ assert restored == [(0, bytes([7, 8, 9]))], "cuda:0 was not restored"
+
+
+def test_a_checkpoint_missing_a_live_tensor_is_refused():
+ """The other direction, which the count alone could not see.
+
+ Matching the number restored against the checkpoint's own key count proves every SAVED
+ tensor landed somewhere. It says nothing about a live trainable parameter the checkpoint
+ never had: a truncated or hand-edited adapter holding a strict SUBSET passed, and the full
+ optimizer state was then loaded on top, so restored Adam moments drove freshly initialised
+ weights while the run reported a clean resume.
+ """
+ from core.training.diffusion_train_common import (
+ load_trainable_state_dict,
+ trainable_state_dict,
+ )
+
+ model = torch.nn.Sequential(torch.nn.Linear(4, 4, bias = False), torch.nn.Linear(4, 4))
+ for param in model.parameters():
+ param.requires_grad_(True)
+ full = trainable_state_dict(model)
+ assert len(full) >= 2
+
+ # Everything the checkpoint holds still lands, so the old count check was satisfied.
+ partial = {k: v for k, v in full.items() if k != sorted(full)[0]}
+ with pytest.raises(ValueError, match = "not in the checkpoint"):
+ load_trainable_state_dict(model, partial)
+
+ # ...and the complete set is still accepted, so the guard is not simply refusing everything.
+ assert load_trainable_state_dict(model, full) == len(full)
+
+
+# ── the writer must not destroy what it is replacing ──────────────────────────
+
+
+def test_the_bundle_just_written_survives_pruning(run_dir):
+ """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 still 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 and the run's own start fence stops those
+ older bundles from making it resumable."""
+ seed = _Run(run_dir, save_total_limit = 0)
+ for step in (10, 20, 30):
+ seed.save(step)
+
+ run = _Run(run_dir, save_total_limit = 2)
+ written, error = run.save(15)
+
+ assert error is None, error
+ assert Path(written).is_dir(), "the checkpoint this call reported was pruned by the same call"
+ assert dc.read_checkpoint(Path(written)) is not None
+ kept = {p.name for p in dc.list_checkpoints(run_dir)}
+ assert "checkpoint-15" in kept
+ assert len(kept) == 2, kept
+
+
+def test_a_failed_write_leaves_the_previous_checkpoints_alone(run_dir, monkeypatch):
+ """discard_existing cleared the directory BEFORE staging anything. A kill or an I/O error
+ mid-write then left the new run with no checkpoint and every earlier run sharing the folder
+ with none either -- the opposite of what this writer promises."""
+ run = _Run(run_dir, save_total_limit = 0)
+ run.save(7)
+
+ def _boom(*_a, **_k):
+ raise OSError("no space left on device")
+
+ monkeypatch.setattr(dc, "_save_tensors", _boom)
+ # write_resume_checkpoint reports rather than raises, so the run survives a bad disk.
+ written, error = run.save(1, discard_existing = True)
+ assert written is None and error
+
+ survivors = {p.name for p in dc.list_checkpoints(run_dir)}
+ assert survivors == {"checkpoint-7"}, (
+ "the pre-existing bundle was deleted before the replacement was written, so a write "
+ f"failure lost it: {survivors}"
+ )
+ assert dc.read_checkpoint(run_dir / "checkpoint-7") is not None
+
+
+def test_a_successful_discarding_write_still_replaces_the_old_bundles(run_dir):
+ """The other half: deferring the delete must not turn discard_existing into a no-op."""
+ run = _Run(run_dir, save_total_limit = 0)
+ run.save(7)
+ written, error = run.save(1, discard_existing = True)
+
+ assert error is None, error
+ assert {p.name for p in dc.list_checkpoints(run_dir)} == {"checkpoint-1"}
+ assert Path(written).name == "checkpoint-1"
+
+
+# ── a discard must not take the source checkpoint with it ─────────────────────
+
+
+def test_clearing_this_runs_checkpoints_spares_the_one_it_resumed_from(run_dir):
+ """A resumed run writes into the directory its source lives in, so a blanket clear on
+ "stop without saving" deletes the bundle the user resumed from: an accidental resume
+ followed by a discard leaves the ORIGINAL stopped run unresumable."""
+ source = _Run(run_dir, save_total_limit = 0)
+ source.save(11)
+ preexisting = dc.list_checkpoints(run_dir)
+
+ resumed = _Run(run_dir, save_total_limit = 0)
+ resumed.save(14)
+ resumed.save(17)
+
+ dc.clear_own_checkpoints(run_dir, preexisting)
+
+ survivors = {p.name for p in dc.list_checkpoints(run_dir)}
+ assert survivors == {
+ "checkpoint-11"
+ }, f"the discard removed the source bundle as well as its own: {survivors}"
+
+
+# ── EMA turned on by the resume ───────────────────────────────────────────────
+
+
+def test_enabling_ema_on_a_resume_starts_from_the_restored_weights():
+ """EMA is not part of the validated identity, so a resume can turn it on for a run that had
+ it off. The trainer builds the EMA before restoring the adapter, so its shadow holds freshly
+ initialised LoRA weights and the checkpoint carries no shadow to replace them -- every later
+ update, and the exported EMA adapter, would blend the restored weights with that noise."""
+ from core.training.diffusion_train_extras import LoRAEMA
+
+ model = torch.nn.Linear(4, 4, bias = False)
+ ema = LoRAEMA(model, decay = 0.99)
+ initial = ema.state_dict()["weight"].clone()
+
+ # ...the adapter is restored afterwards, exactly as the trainer orders it.
+ with torch.no_grad():
+ model.weight.copy_(torch.full_like(model.weight, 3.0))
+ assert not torch.allclose(ema.state_dict()["weight"], model.weight)
+
+ ema.reseed_from(model)
+
+ assert torch.allclose(ema.state_dict()["weight"], model.weight)
+ assert not torch.allclose(ema.state_dict()["weight"], initial)
+ assert ema.updates == 0, "the warmup ramp restarts with the shadow"
+
+
+# ── a run directory that happens to look like a bundle ────────────────────────
+
+
+def test_an_output_directory_named_like_a_checkpoint_is_still_scanned(tmp_path, monkeypatch):
+ """An adapter can legitimately be called "checkpoint-2026". Its output directory then
+ matches the bundle pattern while holding checkpoint-11 rather than a trainer_state.json of
+ its own, and the documented resume API rejected it with the real checkpoint sitting inside."""
+ from utils.paths import outputs_root
+
+ weird = outputs_root() / "checkpoint-2026"
+ weird.mkdir(parents = True, exist_ok = True)
+ run = _Run(weird, save_total_limit = 0)
+ run.save(11)
+
+ path, step = dc.preflight_resume(str(weird), identity = _identity(), target_steps = 500)
+
+ assert Path(path).name == "checkpoint-11"
+ assert step == 11
+
+
+def test_an_image_replaced_in_place_changes_the_dataset_fingerprint(tmp_path):
+ """Same filename, same caption, same byte length, different picture. On size alone the
+ preflight accepted the dataset and the restored optimizer and scheduler carried an old
+ experiment on against different training images, which is exactly what the fingerprint
+ exists to refuse."""
+ image = tmp_path / "cat.png"
+ image.write_bytes(b"A" * 4096)
+ entries = [(str(image), "a cat")]
+ before = dc.dataset_fingerprint(entries)
+
+ replaced = b"B" * 4096
+ image.write_bytes(replaced)
+ assert image.stat().st_size == 4096, "the fixture must keep the length identical"
+
+ assert dc.dataset_fingerprint(entries) != before
+
+ # ...and it is stable when nothing changed, or a resume would never be offered at all.
+ assert dc.dataset_fingerprint(entries) == dc.dataset_fingerprint(entries)
+
+
+def test_the_fingerprint_probe_does_not_read_whole_images(tmp_path):
+ """It runs on the route thread before the resident model is evicted, so it must not scale
+ with the dataset. Head and tail only, whatever the file size."""
+ import time
+
+ small = tmp_path / "small.png"
+ small.write_bytes(b"\0" * (2 * dc._PROBE_BYTES))
+ big = tmp_path / "big.png"
+ # Distinct bytes throughout, so a whole-file read could not be optimised away.
+ big.write_bytes(bytes(range(256)) * (64 * 1024 // 256) * 128)
+ assert big.stat().st_size >= 64 * 1024 * 128
+
+ def _elapsed(path):
+ started = time.perf_counter()
+ for _ in range(20):
+ dc.dataset_fingerprint([(str(path), "caption")])
+ return time.perf_counter() - started
+
+ # A whole-file hash would scale with the 128x size difference; head+tail does not.
+ assert _elapsed(big) < 8 * max(
+ _elapsed(small), 1e-4
+ ), "the probe appears to scale with file size, so it is reading more than head and tail"
+
+ # The direct statement of the same thing: two files that differ only in the middle, past
+ # the probe window on both ends, are indistinguishable -- which is the documented tradeoff.
+ a, b = tmp_path / "a.bin", tmp_path / "b.bin"
+ body = b"\0" * (4 * dc._PROBE_BYTES)
+ a.write_bytes(body)
+ b.write_bytes(body[: 2 * dc._PROBE_BYTES] + b"X" + body[2 * dc._PROBE_BYTES + 1 :])
+ assert dc._content_probe(a) == dc._content_probe(b)
+
+
+def test_a_mid_sized_image_is_covered_end_to_end(tmp_path):
+ """A file between one and two probe windows is read IN FULL, not head-only.
+
+ The old gate only sampled a tail past 2 x _PROBE_BYTES, so anything from 64 KiB to
+ 128 KiB -- which is most JPEGs in a LoRA dataset -- contributed its first 64 KiB and
+ nothing else. A same-length replacement sharing that head kept the fingerprint intact
+ and the preflight accepted changed training images.
+ """
+ path = tmp_path / "mid.jpg"
+ head = b"H" * dc._PROBE_BYTES
+ path.write_bytes(head + b"A" * (dc._PROBE_BYTES // 2))
+ entries = [(str(path), "a cat")]
+ before = dc.dataset_fingerprint(entries)
+
+ path.write_bytes(head + b"B" * (dc._PROBE_BYTES // 2))
+ assert path.stat().st_size == dc._PROBE_BYTES + dc._PROBE_BYTES // 2
+ assert dc.dataset_fingerprint(entries) != before
+
+
+def test_a_failed_first_save_does_not_retire_the_discard(run_dir, monkeypatch):
+ """A run that has written nothing yet still owns its output directory.
+
+ A transient failure at the first save_steps interval used to flip wrote_checkpoint
+ anyway, so the next successful save ran with discard_existing=False and an earlier run's
+ higher-numbered bundle survived beside it -- and a later Resume by output directory
+ picked that stale bundle over this run's state.
+ """
+ import core.training.diffusion_train_common as dtc
+
+ # An earlier run of the same adapter name left a bundle behind, at a higher step.
+ stale = _Run(run_dir)
+ stale.save(40)
+ assert (run_dir / "checkpoint-40").is_dir()
+
+ wrote_checkpoint = False
+ run = _Run(run_dir)
+ failing = {"n": 1}
+ real_save = dc.save_checkpoint
+
+ def _save(**kwargs):
+ if failing["n"] > 0:
+ failing["n"] -= 1
+ raise OSError(28, "No space left on device")
+ return real_save(**kwargs)
+
+ monkeypatch.setattr(dc, "save_checkpoint", _save)
+
+ def _attempt(step):
+ nonlocal wrote_checkpoint
+ written, _error = dtc.write_resume_checkpoint(
+ run.cfg,
+ step = step,
+ model = run.model,
+ optimizer = run.optimizer,
+ lr_scheduler = run.lr_sched,
+ identity = run.identity,
+ sampler = run.sampler,
+ rng_streams = run.streams,
+ discard_existing = not wrote_checkpoint,
+ )
+ if written:
+ wrote_checkpoint = True
+ return written
+
+ assert _attempt(5) is None # ENOSPC: nothing was written
+ assert wrote_checkpoint is False
+ assert _attempt(6) is not None
+
+ # The stale higher-numbered bundle is gone, so a Resume by output directory picks step 6.
+ assert not (run_dir / "checkpoint-40").exists()
+ latest = dc.latest_valid_checkpoint(run_dir)
+ assert latest is not None and dc.checkpoint_step(latest[0]) == 6
+
+
+def test_a_partial_ema_shadow_is_refused_rather_than_half_restored():
+ """A readable EMA file covering only SOME of the live shadows is not a resumable EMA.
+
+ load_state_dict skips what it cannot match by design, so continuing here averages
+ restored shadows for some parameters against freshly initialised ones for the rest --
+ for every later update and for the exported EMA adapter -- while the run reports a
+ clean resume.
+ """
+ from core.training.diffusion_train_extras import LoRAEMA
+
+ model = torch.nn.Sequential(torch.nn.Linear(4, 4, bias = False), torch.nn.Linear(4, 4))
+ ema = LoRAEMA(model, decay = 0.99)
+ full = ema.state_dict()
+ assert len(full) > 1
+
+ complete = ema.missing_from(full)
+ assert complete == ()
+
+ partial = {next(iter(full)): next(iter(full.values()))}
+ missing = ema.missing_from(partial)
+ assert missing and len(missing) == len(full) - 1
+
+ # A shape change counts too: load_state_dict skips those on the same branch.
+ mangled = {name: tensor[:1].clone() for name, tensor in full.items()}
+ assert len(ema.missing_from(mangled)) == len(full)
+
+
+def test_a_resume_refuses_a_checkpoint_whose_ema_is_incomplete(run_dir):
+ """The end of the same fence, on the real restore path: the run stops with a reason
+ rather than continuing on a half-restored average."""
+ from core.training.diffusion_checkpoint import ResumeError
+ from core.training.diffusion_train_extras import LoRAEMA
+ from safetensors.torch import save_file
+
+ run = _Run(run_dir)
+ ema = LoRAEMA(run.model, decay = 0.99)
+ path, error = run.save(3, ema = ema)
+ assert error is None and path is not None
+
+ # A wider model on the resume side: the saved shadow covers only part of it, which is the
+ # shape a re-wrap (or a hand-edited bundle) produces.
+ save_file(
+ {"weight": torch.zeros(4, 4)},
+ str(Path(path) / dc.EMA_FILENAME),
+ )
+ resumed = _Run(run_dir, resume_from_checkpoint = path)
+ resumed.model = torch.nn.Sequential(
+ torch.nn.Linear(4, 4, bias = False), torch.nn.Linear(4, 4, bias = False)
+ )
+ wider = LoRAEMA(resumed.model, decay = 0.99)
+
+ with pytest.raises(ResumeError) as excinfo:
+ restore_resume_state(
+ resumed.cfg,
+ model = run.model,
+ optimizer = resumed.optimizer,
+ lr_scheduler = resumed.lr_sched,
+ identity = resumed.identity,
+ sampler = resumed.sampler,
+ rng_streams = resumed.streams,
+ ema = wider,
+ )
+ assert "EMA state is missing or mis-shaped" in str(excinfo.value)
+
+
+def test_the_sdxl_trainer_binds_its_output_dir_before_scanning_checkpoints():
+ """`out_dir` was assigned only inside two early-return branches and at export time, so the
+ pre-run checkpoint snapshot read it before any binding existed: every normal SDXL run raised
+ UnboundLocalError after the whole model and cache setup, fresh and resumed alike. The loop
+ needs a GPU to drive, so the ordering is checked against the source."""
+ import inspect
+
+ from core.training import diffusion_lora_trainer
+
+ source = inspect.getsource(diffusion_lora_trainer).splitlines()
+ scan = next(i for i, line in enumerate(source) if "snapshot_checkpoints(out_dir)" in line)
+ # The binding that covers it has to be at the loop's own indentation -- one nested inside an
+ # `if` that returns does not run on the normal path.
+ scan_indent = len(source[scan]) - len(source[scan].lstrip())
+ bound = [
+ i
+ for i, line in enumerate(source[:scan])
+ if line.strip().startswith("out_dir = ") and len(line) - len(line.lstrip()) <= scan_indent
+ ]
+ assert bound, "snapshot_checkpoints(out_dir) is reached before out_dir is bound"
+
+
+def test_a_bundle_overwritten_by_this_run_is_discarded_with_it(run_dir):
+ """Ownership by pathname alone kept a bundle this run REPLACED.
+
+ Resume checkpoint-10 in a folder that also holds checkpoint-15, periodically save at 15
+ (which overwrites it), then discard: the original is already gone, and matching on the name
+ preserved the replacement as though it were the bundle it destroyed.
+ """
+ seeded = _Run(run_dir)
+ seeded.save(10)
+ seeded.step_once(0.5)
+ seeded.save(15)
+ preexisting = dc.snapshot_checkpoints(run_dir)
+ assert {p.name for p, _ in preexisting} == {"checkpoint-10", "checkpoint-15"}
+
+ resumed = _Run(run_dir, seed = 3, resume_from_checkpoint = str(run_dir / "checkpoint-10"))
+ resumed.step_once(1.5)
+ path, error = resumed.save(15)
+ assert error is None and path == str(run_dir / "checkpoint-15")
+
+ replacement = (run_dir / "checkpoint-15" / dc.TRAINER_STATE_FILENAME).read_text(
+ encoding = "utf-8"
+ )
+ dc.clear_own_checkpoints(run_dir, preexisting)
+
+ survivors = {p.name for p in dc.list_checkpoints(run_dir)}
+ # Both come back: the replacement written by the discarded run is gone, and the bundle it
+ # displaced is handed back to its slot rather than dying with the run that overwrote it.
+ assert survivors == {"checkpoint-10", "checkpoint-15"}, survivors
+ settled = (run_dir / "checkpoint-15" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ assert settled != replacement, "the discarded run's bundle is still sitting in the slot"
+ assert (
+ dc._bundle_identity(run_dir / "checkpoint-15")
+ == dict(preexisting)[run_dir / "checkpoint-15"]
+ )
+ # And nothing is left hidden in the directory afterwards.
+ assert list(run_dir.glob(f"{dc._STAGING_PREFIX}*")) == []
+
+
+def test_resuming_into_another_directory_is_not_treated_as_owning_it(run_dir, tmp_path):
+ from utils.paths import outputs_root
+
+ elsewhere = outputs_root() / "other-run"
+ elsewhere.mkdir(parents = True, exist_ok = True)
+ source = _Run(elsewhere)
+ source.save(20)
+
+ same_dir = _Run(run_dir, resume_from_checkpoint = str(run_dir / "checkpoint-3"))
+ assert dc.resumed_into_this_dir(same_dir.cfg, run_dir) is True
+ by_folder = _Run(run_dir, resume_from_checkpoint = str(run_dir))
+ assert dc.resumed_into_this_dir(by_folder.cfg, run_dir) is True
+
+ # ...but a bundle from ANOTHER directory says nothing about what is in this one.
+ cross = _Run(run_dir, resume_from_checkpoint = str(elsewhere / "checkpoint-20"))
+ assert dc.resumed_into_this_dir(cross.cfg, run_dir) is False
+ fresh = _Run(run_dir)
+ assert dc.resumed_into_this_dir(fresh.cfg, run_dir) is False
+
+
+def test_a_bundle_without_optimizer_state_is_refused(run_dir):
+ """Loading only the adapter and calling it a resume restarts Adam's moments from zero at
+ step N while reporting a clean continue -- a fresh run with a warm learning rate."""
+ from core.training.diffusion_checkpoint import ResumeError
+
+ run = _Run(run_dir)
+ path, error = run.save(4)
+ assert error is None and path is not None
+ (Path(path) / dc.OPTIMIZER_FILENAME).unlink()
+ manifest_path = Path(path) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest["files"].pop("optimizer", None)
+ manifest.get("file_sizes", {}).pop(dc.OPTIMIZER_FILENAME, None)
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ resumed = _Run(run_dir, resume_from_checkpoint = path)
+ # Refused by the ROUTE preflight, before the resident GPU model is evicted. It used to get
+ # through here (the preflight only opened the roles the manifest listed) and fail in the
+ # child, having already torn down the pipeline the refusal exists to protect.
+ with pytest.raises(ResumeError, match = "missing the optimizer moments"):
+ dc.preflight_resume(path, identity = run.identity, target_steps = 10)
+ with pytest.raises(ResumeError):
+ resumed.restore()
+
+
+def test_a_shortened_or_repeating_permutation_is_refused(run_dir):
+ """An order that is in range and the right length is not necessarily a permutation.
+
+ A shortened or duplicate-carrying one makes the cycle reshuffle early or serve the same
+ image twice, while the RNG has already been restored to a point AFTER the original draw.
+ That is the silent reorder the boolean exists to prevent, arriving through a truncated
+ manifest instead of a missing one."""
+ rng = __import__("random").Random(0)
+ sampler = PermutationBatchSampler(4, rng)
+ assert sampler.load_state_dict({"n": 4, "order": [0, 1, 2, 3], "pos": 2}) is True
+ assert sampler.load_state_dict({"n": 4, "order": [], "pos": 0}) is True
+ # Right size, wrong contents: index 1 twice and index 3 never.
+ assert sampler.load_state_dict({"n": 4, "order": [0, 1, 1, 2], "pos": 0}) is False
+ # Short: the cycle would reshuffle a batch early.
+ assert sampler.load_state_dict({"n": 4, "order": [0, 1, 2], "pos": 0}) is False
+ # And a position outside the permutation is a damaged manifest, not a rounding error:
+ # clamping it re-serves the order from the top or ends the cycle early, behind the same
+ # already-restored RNG.
+ assert sampler.load_state_dict({"n": 4, "order": [0, 1, 2, 3], "pos": 9}) is False
+ assert sampler.load_state_dict({"n": 4, "order": [0, 1, 2, 3], "pos": -1}) is False
+ assert sampler.load_state_dict({"n": 4, "order": [0, 1, 2, 3], "pos": "two"}) is False
+ # The two ends of the range are both legitimate: 0 is untouched, len(order) is exhausted.
+ assert sampler.load_state_dict({"n": 4, "order": [0, 1, 2, 3], "pos": 4}) is True
+
+
+def test_optimizer_moments_with_no_class_beside_them_are_refused(run_dir):
+ """This writer records the class whenever it writes moments, so an optimizer file with
+ none is hand-edited -- and foreign moments load cleanly (shapes and counts match) then
+ die on the first step, in the child, after the route has evicted the resident models."""
+ from core.training.diffusion_checkpoint import ResumeError
+
+ run = _Run(run_dir)
+ path, error = run.save(4)
+ assert error is None and path is not None
+ manifest_path = Path(path) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest.pop("optimizer_class", None)
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ resumed = _Run(run_dir, resume_from_checkpoint = path)
+ with pytest.raises(ResumeError, match = "does not record which optimizer"):
+ resumed.restore()
+
+
+def test_a_bundle_with_no_sampler_or_rng_state_is_refused_before_teardown(run_dir):
+ """Both are mandatory for an image run and both were checked only in the child: the
+ sampler by restore_resume_state, the RNG not at all (restore_rng_state silently leaves
+ the generator at its fresh seed, and every latent, noise and timestep comes from it)."""
+ from core.training.diffusion_checkpoint import ResumeError
+ for drop, expected in (
+ ("sampler", "dataset sampler position"),
+ ("rng", "random-number generator state"),
+ ):
+ run = _Run(run_dir)
+ path, error = run.save(4)
+ assert error is None and path is not None
+ manifest_path = Path(path) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ if drop == "sampler":
+ manifest["sampler"] = None
+ else:
+ manifest["files"].pop("rng", None)
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ with pytest.raises(ResumeError, match = expected):
+ dc.preflight_resume(path, identity = run.identity, target_steps = 10)
+ dc.shutil.rmtree(path)
+
+
+def test_an_rng_file_with_no_torch_state_is_refused(run_dir):
+ from core.training.diffusion_checkpoint import ResumeError
+
+ run = _Run(run_dir)
+ path, error = run.save(4)
+ assert error is None and path is not None
+ rng_file = Path(path) / dc.RNG_FILENAME
+ torch.save({"cuda": {}}, rng_file)
+ # Keep the recorded size honest, so the bundle fails on its CONTENTS rather than on the
+ # cheap size check that would have caught this edit and hidden the real gap.
+ manifest_path = Path(path) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest["file_sizes"]["rng"] = rng_file.stat().st_size
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ with pytest.raises(ResumeError, match = "no torch random-number state"):
+ dc.preflight_resume(path, identity = run.identity, target_steps = 10)
+
+
+def test_the_identity_covers_cfg_dropout(run_dir):
+ """The DiT loop asks rng.random() once per sample when caption dropout is on and swaps
+ in the empty prompt on a hit, so changing it across a resume diverges the restored RNG
+ stream on the next step and changes the objective, under a clean-looking continue."""
+ run = _Run(run_dir, cfg_dropout = 0.1)
+ changed = _Run(run_dir, cfg_dropout = 0.3)
+ reason = dc.identity_for_config(run.cfg).mismatch_reason(dc.identity_for_config(changed.cfg))
+ assert reason is not None and "caption dropout" in reason
+ # The same value still resumes.
+ same = _Run(run_dir, cfg_dropout = 0.1)
+ assert dc.identity_for_config(run.cfg).mismatch_reason(dc.identity_for_config(same.cfg)) is None
+ # An identity from before the field existed reads as unknown, not as a mismatch.
+ older = dc.CheckpointIdentity.from_dict(
+ {**dc.identity_for_config(run.cfg).as_dict(), "cfg_dropout": None}
+ )
+ assert older is not None
+ assert older.mismatch_reason(dc.identity_for_config(changed.cfg)) is None
+ # But a manifest that DOES record it must read it back, or the optional-field rule turns
+ # every saved identity into "cannot tell" and the gate never fires on a real change.
+ saved = dc.CheckpointIdentity.from_dict(dc.identity_for_config(run.cfg).as_dict())
+ assert saved is not None and saved.cfg_dropout == 0.1
+ assert "caption dropout" in (saved.mismatch_reason(dc.identity_for_config(changed.cfg)) or "")
+
+
+def test_the_identity_covers_the_trajectory_knobs(run_dir):
+ """Each of these is read from the INCOMING config while the moments and the scheduler
+ position come from the bundle, so changing one continues a run whose objective or
+ learning-rate curve is no longer the one those moments were produced under."""
+ base = _Run(run_dir)
+ for field, value, label in (
+ ("flow_shift", 3.0, "timestep shift"),
+ ("weighting_scheme", "logit_normal", "loss weighting scheme"),
+ ("snr_gamma", 1.0, "min-SNR gamma"),
+ ("lr_scheduler", "cosine", "learning-rate schedule"),
+ ("lr_warmup_steps", 25, "learning-rate warmup"),
+ ):
+ changed = _Run(run_dir, **{field: value})
+ reason = dc.identity_for_config(base.cfg).mismatch_reason(
+ dc.identity_for_config(changed.cfg)
+ )
+ assert reason is not None and label in reason, field
+ # A manifest from before the field was recorded reads unknown, not mismatched.
+ older = dc.CheckpointIdentity.from_dict(
+ {**dc.identity_for_config(base.cfg).as_dict(), field: None}
+ )
+ assert older is not None
+ assert older.mismatch_reason(dc.identity_for_config(changed.cfg)) is None, field
+ # And an unchanged config still resumes.
+ assert (
+ dc.identity_for_config(base.cfg).mismatch_reason(dc.identity_for_config(_Run(run_dir).cfg))
+ is None
+ )
+
+
+def test_disabling_min_snr_is_a_mismatch_not_an_unknown(run_dir):
+ """None is the documented way to DISABLE min-SNR, so a float field could not tell
+ "trained with it off" from "written before the field existed", and the optional rule
+ skipped the comparison for both -- letting a run continue under a different objective."""
+ on = _Run(run_dir, snr_gamma = 5.0)
+ off = _Run(run_dir, snr_gamma = None)
+ reason = dc.identity_for_config(on.cfg).mismatch_reason(dc.identity_for_config(off.cfg))
+ assert reason is not None and "min-SNR gamma" in reason
+ assert dc.identity_for_config(off.cfg).snr_gamma == "off"
+ # Only a manifest that never recorded the field is unknown.
+ older = dc.CheckpointIdentity.from_dict(
+ {**dc.identity_for_config(on.cfg).as_dict(), "snr_gamma": None}
+ )
+ assert older is not None
+ assert older.mismatch_reason(dc.identity_for_config(off.cfg)) is None
+
+
+def test_the_identity_covers_the_input_stream(run_dir):
+ """Both trainers build the latent cache and the crop/flip variant plan from these BEFORE
+ restore_resume_state puts the RNG back, so changing one continues the old optimizer and
+ sampler against a different sequence of images."""
+ import dataclasses
+
+ base = _Run(run_dir)
+ for field, value, label in (
+ # seed goes through dataclasses.replace: _Run takes its own seed argument for
+ # torch.manual_seed and does not forward it to the config.
+ ("seed", 1234, "random seed"),
+ ("cache_latents", False, "latent caching"),
+ ("cache_variants", 8, "cached crop variants"),
+ ("center_crop", True, "centre cropping"),
+ ("random_flip", False, "random flipping"),
+ ):
+ changed_cfg = dataclasses.replace(base.cfg, **{field: value})
+ reason = dc.identity_for_config(base.cfg).mismatch_reason(
+ dc.identity_for_config(changed_cfg)
+ )
+ assert reason is not None and label in reason, field
+ older = dc.CheckpointIdentity.from_dict(
+ {**dc.identity_for_config(base.cfg).as_dict(), field: None}
+ )
+ assert older is not None
+ assert older.mismatch_reason(dc.identity_for_config(changed_cfg)) is None, field
+ # False is a VALUE, not an unknown: the flags are recorded as on/off for exactly that.
+ flipped = dataclasses.replace(base.cfg, random_flip = False)
+ assert dc.identity_for_config(flipped).random_flip == "off"
+
+
+def test_the_identity_covers_the_update_shape_and_the_resolution(run_dir):
+ """The batch and accumulation counts decide how many samples an optimizer step consumes,
+ the clip norm is applied to the restored moments on the very next update, and the
+ resolution decides what the images are cropped to before the restored sampler sees them.
+ All four were loadable-but-different resumes reported as clean."""
+ import dataclasses
+
+ base = _Run(run_dir)
+ for field, value, label in (
+ ("train_batch_size", 4, "batch size"),
+ ("gradient_accumulation_steps", 2, "gradient accumulation"),
+ ("max_grad_norm", 0.0, "gradient clipping"),
+ ("resolution", 768, "training resolution"),
+ ):
+ changed_cfg = dataclasses.replace(base.cfg, **{field: value})
+ reason = dc.identity_for_config(base.cfg).mismatch_reason(
+ dc.identity_for_config(changed_cfg)
+ )
+ assert reason is not None and label in reason, field
+ # 0.0 disables clipping and is a real value, so it is recorded as text rather than as a
+ # float that the optional rule would read as "not recorded".
+ disabled = dataclasses.replace(base.cfg, max_grad_norm = 0.0)
+ assert dc.identity_for_config(disabled).max_grad_norm == "0.0"
+ # resolution is NOT optional: every bundle has recorded it from the first version, so an
+ # unknown there would be a manifest we cannot trust anyway.
+ assert "resolution" not in dc._OPTIONAL_IDENTITY_FIELDS
+
+
+def test_pruning_spares_the_bundle_the_run_resumed_from(run_dir):
+ """A resumed run writes into the directory it resumed FROM, so with the default keep=2 a
+ resume of checkpoint-10 that saves 20 and 30 prunes 10 -- and "stop without saving" then
+ removes only what this run wrote, leaving the ORIGINAL stopped run with no resume point."""
+ source = _Run(run_dir)
+ origin, error = source.save(10)
+ assert error is None and origin is not None
+
+ run = _Run(run_dir, resume_from_checkpoint = origin)
+ for step in (20, 30):
+ _path, error = run.save(step)
+ assert error is None, step
+
+ assert Path(origin).is_dir(), "the source bundle is not this run's to spend"
+ assert (run_dir / "checkpoint-30").is_dir()
+
+
+def test_the_resolved_cache_path_is_recorded_not_the_request(run_dir):
+ """UNSLOTH_DIFFUSION_NO_LATENT_CACHE and the over-budget fallback both turn the cache off
+ behind the request, and the two paths draw crops and flips from different RNG streams, so
+ a bundle written on one and resumed on the other restores a state that no longer
+ reproduces the run."""
+ base = dc.identity_for_config(_Run(run_dir).cfg)
+ cached = dc.with_cache_mode(base, True)
+ in_loop = dc.with_cache_mode(base, False)
+
+ assert cached.cache_mode == "cached" and in_loop.cache_mode == "in-loop"
+ reason = cached.mismatch_reason(in_loop)
+ assert reason is not None and "latent cache path" in reason
+ # The start route builds its identity before the loop decides, so it stays unknown there
+ # and the pre-eviction preflight is unaffected.
+ assert base.cache_mode is None
+ assert base.mismatch_reason(in_loop) is None
+ assert cached.mismatch_reason(base) is None
+
+ # And both trainers record it.
+ trainers = Path(dc.__file__).parent
+ for name in ("diffusion_lora_trainer.py", "diffusion_dit_trainer.py"):
+ source = (trainers / name).read_text(encoding = "utf-8")
+ assert "with_cache_mode(identity, latent_cache is not None)" in source, name
+
+
+def test_a_first_periodic_save_does_not_spend_the_previous_runs_bundles(run_dir):
+ """Deleting them at the first save spends them before this run has produced anything: a
+ later "stop without saving" removes only what this run wrote, leaves the previous adapter
+ in place, and the run it belonged to is unresumable -- cancelling a retrain destroyed the
+ thing being retrained."""
+ earlier = _Run(run_dir)
+ kept, error = earlier.save(9)
+ assert error is None and kept is not None
+
+ fresh = _Run(run_dir)
+ mine, error = fresh.save(1)
+ assert error is None and mine is not None
+ assert Path(kept).is_dir(), "the previous run's bundle survives the first periodic save"
+
+ # It goes on the COMPLETION path instead, once this run's adapter is actually saved.
+ dc.retire_own_checkpoints(run_dir, [], resumed_here = False)
+ assert dc.list_checkpoints(run_dir) == []
+
+ trainers = Path(dc.__file__).parent
+ for name in ("diffusion_lora_trainer.py", "diffusion_dit_trainer.py"):
+ source = (trainers / name).read_text(encoding = "utf-8")
+ assert "discard_existing = False," in source, name
+
+
+def test_both_trainers_honour_the_fp32_optimizer_override(run_dir):
+ """The preflight refuses 8-bit moments when the override is set, which is only sound if
+ every trainer actually obeys it -- otherwise DiT checkpoints written on this host become
+ unresumable on the same host."""
+ trainers = Path(dc.__file__).parent
+ for name in ("diffusion_lora_trainer.py", "diffusion_dit_trainer.py"):
+ source = (trainers / name).read_text(encoding = "utf-8")
+ marker = source.find("def _make_optimizer")
+ if marker < 0:
+ marker = source.find("def _make_lora_optimizer")
+ assert marker > 0, name
+ body = source[marker : marker + 1200]
+ # The env READ, not a mention of it in prose.
+ read = 'os.environ.get("UNSLOTH_DIFFUSION_FP32_OPTIM"'
+ assert read in body, name
+ assert body.index(read) < body.index("AdamW8bit"), name
+
+
+def test_a_completed_run_does_not_leave_its_periodic_bundles_behind(run_dir):
+ """The last iteration deliberately writes no bundle, so with save_steps on the newest
+ thing left is the run's own checkpoint-400 of a run that finished at 500. The preflight
+ cannot see the run status, so a later resume rolled everything back and retrained 401-500."""
+ earlier = _Run(run_dir)
+ kept, error = earlier.save(3)
+ assert error is None and kept is not None
+ preexisting = dc.snapshot_checkpoints(run_dir)
+
+ run = _Run(run_dir)
+ mine, error = run.save(7)
+ assert error is None and mine is not None
+
+ dc.retire_own_checkpoints(run_dir, preexisting, resumed_here = True)
+
+ assert not Path(mine).exists(), "the completed run's own bundle must go"
+ assert Path(kept).exists(), "a resumed run leaves its source directory's bundle alone"
+
+ # A FRESH run in a reused directory takes the earlier bundles with it: the adapter they
+ # belonged to has just been overwritten, and with the default save_steps=0 the run never
+ # writes one of its own, so nothing else ever clears them and a later resume by output
+ # directory continues the previous run's optimizer and RNG into the reused folder.
+ dc.retire_own_checkpoints(run_dir, [], resumed_here = False)
+ assert dc.list_checkpoints(run_dir) == []
+
+ # And both trainers actually call it on the success path. Running either end to end needs a
+ # GPU and a multi-GB base, so the call site is checked in the source: the helper being
+ # correct is no use if nothing invokes it.
+ trainers = Path(dc.__file__).parent
+ for name in ("diffusion_lora_trainer.py", "diffusion_dit_trainer.py"):
+ source = (trainers / name).read_text(encoding = "utf-8")
+ marker = source.find("retire_own_checkpoints(")
+ assert marker > 0, name
+ # With the resumption flag, or a fresh run in a reused directory keeps the previous
+ # run's bundles and a later resume by output directory continues them.
+ assert "resumed_here = resumed_here" in source[marker : marker + 200], name
+ guard = source.rfind("if not stopped:", 0, marker)
+ assert (
+ guard > 0 and marker - guard < 700
+ ), f"{name} must retire its bundles only on a completed run"
+
+
+def test_a_swap_aside_orphan_is_found_by_the_resume_scan(run_dir):
+ """_prune_staging can hand the orphan back, but it runs only after a later successful
+ save -- which a user told "there is nothing to resume" will never reach. The read path
+ that makes that call has to repair first."""
+ run = _Run(run_dir)
+ path, error = run.save(4)
+ assert error is None and path is not None
+ stale = run_dir / f"{dc._STAGING_PREFIX}stale-4-cafebabe"
+ dc.os.replace(run_dir / "checkpoint-4", stale)
+ assert dc.list_checkpoints(run_dir) == []
+
+ found = dc.latest_valid_checkpoint(run_dir)
+
+ assert found is not None, "the complete bundle is still on disk"
+ assert found[0] == run_dir / "checkpoint-4"
+ assert not stale.exists()
+
+
+def test_eight_bit_moments_are_refused_when_the_host_cannot_build_them(run_dir, monkeypatch):
+ """The child's own check fires after the route has evicted the resident models and loaded
+ a multi-GB base, for a run guaranteed to terminate without training."""
+ from core.training.diffusion_checkpoint import ResumeError
+
+ run = _Run(run_dir)
+ path, error = run.save(4)
+ assert error is None and path is not None
+ manifest_path = Path(path) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest["optimizer_class"] = "bitsandbytes.optim.adamw.AdamW8bit"
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ # The one direction that cannot be wrong: the override forces plain torch AdamW.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_FP32_OPTIM", "1")
+ with pytest.raises(ResumeError, match = "8-bit optimizer state"):
+ dc.preflight_resume(path, identity = run.identity, target_steps = 10)
+
+ # Without it, an installed bitsandbytes is not refused here -- an installed-but-broken
+ # wheel is the child's call, where the real optimizer object exists.
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_FP32_OPTIM")
+ import importlib.util
+
+ if importlib.util.find_spec("bitsandbytes") is not None:
+ assert dc.preflight_resume(path, identity = run.identity, target_steps = 10)[1] == 4
+
+
+def test_the_identity_covers_lora_dropout(run_dir):
+ """Both trainers pass lora_dropout to the LoRA constructor, so it changes the stochastic
+ forward the restored moments were produced against."""
+ run = _Run(run_dir, lora_dropout = 0.0)
+ path, error = run.save(5)
+ assert error is None
+
+ changed = _Run(run_dir, lora_dropout = 0.15, resume_from_checkpoint = path)
+ reason = dc.identity_for_config(run.cfg).mismatch_reason(dc.identity_for_config(changed.cfg))
+ assert reason is not None and "dropout" in reason.lower()
+
+ # An identity from before the field existed reads as unknown, which must not be a mismatch.
+ older = dc.CheckpointIdentity.from_dict(
+ {**dc.identity_for_config(run.cfg).as_dict(), "lora_dropout": None}
+ )
+ assert older is not None
+ assert older.mismatch_reason(dc.identity_for_config(changed.cfg)) is None
+
+
+def test_the_resumed_event_seeds_the_live_counters(runs_dir):
+ """Until the first post-resume progress event, step and total_steps stayed at their idle
+ values: the UI showed 0/0 after restoring step 400 of 500, and an OOM on the first step
+ persisted an errored run with both recorded as zero. The event carries them."""
+ from core.training.diffusion_training_service import DiffusionTrainingService
+
+ service = DiffusionTrainingService()
+ service._apply_event(
+ {
+ "type": "resumed",
+ "step": 400,
+ "total_steps": 500,
+ "checkpoint_path": "/x/checkpoint-400",
+ }
+ )
+ snapshot = service.status()
+ assert snapshot["step"] == 400
+ assert snapshot["total_steps"] == 500
+ # ...and still not a bundle this run wrote.
+ assert snapshot["resumed_from_step"] == 400
+ assert snapshot["checkpoint_step"] is None
+
+
+# ── round 6: the resume must not overstate what it can honour ─────────────────
+
+
+def test_a_resume_into_a_new_folder_that_died_first_is_still_resumable(run_dir, tmp_path):
+ """An OOM on the first restored step leaves the new output dir nonexistent.
+
+ The bundle it was validated against is still sitting in the source dir, and continuing from
+ it is the obvious retry -- but the missing-folder refusal returned before the source
+ fallback could be consulted, so the run read as unresumable."""
+ from utils.paths import outputs_root
+
+ source = _Run(run_dir)
+ source.save(10)
+ never_created = outputs_root() / "resumed-run-that-died"
+ assert not never_created.exists()
+
+ state = dc.describe_resume_state(
+ str(never_created),
+ status = "error",
+ source_checkpoint = str(run_dir / "checkpoint-10"),
+ )
+ assert state["can_resume"] is True
+ assert state["checkpoint_step"] == 10
+ assert state["checkpoint_path"].endswith("checkpoint-10")
+
+ # With no source to fall back to, the missing folder is still the answer.
+ blocked = dc.describe_resume_state(str(never_created), status = "error")
+ assert blocked["can_resume"] is False
+ assert "no longer exists" in blocked["resume_blocked_reason"]
+
+
+def test_a_checkpoint_with_no_sampler_state_is_refused(run_dir):
+ """The RNG is restored to a point AFTER the saved permutation was drawn, so a fresh sampler
+ generates a different order: images silently skipped or repeated under a resume that
+ reported success. Every bundle this format writes carries sampler state."""
+ run = _Run(run_dir)
+ run.step_once(0.1)
+ run.save(3)
+ bundle = run_dir / "checkpoint-3"
+ manifest_path = bundle / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest["sampler"] = {"n": 999, "order": [1, 2, 3], "pos": 0} # not this dataset
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ resumed = _Run(run_dir)
+ resumed.cfg = type(resumed.cfg)(
+ **{**resumed.cfg.__dict__, "resume_from_checkpoint": str(bundle)}
+ )
+ with pytest.raises(dc.ResumeError, match = "sampler"):
+ resumed.restore()
+
+
+def test_the_sampler_reports_whether_it_restored():
+ sampler = PermutationBatchSampler(4, __import__("random").Random(0))
+ saved = sampler.state_dict()
+ assert PermutationBatchSampler(4, __import__("random").Random(1)).load_state_dict(saved) is True
+ for bad in (None, {}, {"n": 4, "order": "nope", "pos": 0}, {"n": 9, "order": [0], "pos": 0}):
+ assert (
+ PermutationBatchSampler(4, __import__("random").Random(1)).load_state_dict(bad) is False
+ )
+
+
+def test_the_identity_records_the_precision_the_run_will_actually_use(monkeypatch, run_dir):
+ """A pre-Ampere card resolves a bf16 request to fp16. Recording the REQUEST let an fp16
+ bundle resume in bf16 on a newer card, continuing restored moments under different
+ frozen-base numerics and calling it a clean resume."""
+ from core.training import diffusion_train_common as dtc
+
+ cfg = _Run(run_dir).cfg
+ import torch as _torch
+
+ monkeypatch.setattr(_torch.cuda, "is_available", lambda: True)
+
+ monkeypatch.setattr(dtc, "native_bf16_supported", lambda: False)
+ old_card = dc.identity_for_config(cfg)
+ monkeypatch.setattr(dtc, "native_bf16_supported", lambda: True)
+ new_card = dc.identity_for_config(cfg)
+
+ assert old_card.precision == "fp16" and new_card.precision == "bf16"
+ assert (
+ old_card.mismatch_reason(new_card) is not None
+ ), "moving the same request between the two cards must not read as the same run"
+
+
+def test_the_revision_is_pinned_once_the_base_is_on_disk(monkeypatch, run_dir):
+ """The identity is built before the multi-GB load, so the first run of an uncached repo
+ records "unresolved" and the bundle can never enforce which commit it trained on."""
+ from core.training import diffusion_train_extras as dte
+
+ cfg = _Run(run_dir).cfg
+ monkeypatch.setattr(dte, "source_revision", lambda ref: "unresolved")
+ unresolved = dc.identity_for_config(cfg)
+ assert unresolved.base_revision == "unresolved"
+
+ monkeypatch.setattr(dte, "source_revision", lambda ref: "rev-abc123")
+ pinned = dc.with_resolved_revision(unresolved, cfg.base_model)
+ assert pinned.base_revision == "rev-abc123"
+
+ # Already pinned, or still unresolvable: left exactly as it was.
+ monkeypatch.setattr(dte, "source_revision", lambda ref: "rev-def456")
+ # A pinned revision is RE-READ, not trusted: the local ref can still report the old commit
+ # before the load and be refreshed by from_pretrained itself, and a resume that compared the
+ # pre-load value against itself restored the adapter and the moments onto different weights.
+ assert dc.with_resolved_revision(pinned, cfg.base_model).base_revision == "rev-def456"
+ monkeypatch.setattr(dte, "source_revision", lambda ref: "unresolved")
+ assert dc.with_resolved_revision(unresolved, cfg.base_model).base_revision == "unresolved"
+
+
+def test_both_trainers_pin_the_revision_after_the_load():
+ """Source-ordered: the loop needs a GPU, so this asserts the call sits after the load event
+ and before the restore that validates against it."""
+ for name in ("diffusion_lora_trainer", "diffusion_dit_trainer"):
+ src = (Path(dc.__file__).resolve().parent / f"{name}.py").read_text(encoding = "utf-8")
+ pin = src.index("identity = with_resolved_revision(")
+ load = src.index('"model_load_completed"')
+ restore = src.index("restore_resume_state(")
+ assert load < pin < restore, f"{name}: the revision must be pinned between the two"
+
+
+def test_a_raised_target_survives_a_run_that_died_before_the_resumed_event(run_dir):
+ """Raise the target to continue a checkpoint already at its original one, then die during
+ model loading. total_steps is seeded by the "resumed" event, which never arrived, so zero
+ sent the calculation back to the manifest's older target and the run reported that there
+ was nothing left to train -- for the one request that had something left."""
+ from core.training import diffusion_training_service as svc
+
+ run = _Run(run_dir)
+ run.save(500)
+
+ record = {
+ "status": "error",
+ "output_dir": str(run_dir),
+ "config": {"output_dir": str(run_dir), "train_steps": 800},
+ }
+ refreshed = svc._refresh_resume_state(dict(record))
+ assert refreshed["can_resume"] is True, refreshed["resume_blocked_reason"]
+ assert refreshed["checkpoint_step"] == 500
+
+ # And the original target still stops at the top, so this is not a blanket "always resumable".
+ at_target = svc._refresh_resume_state(
+ {**record, "config": {"output_dir": str(run_dir), "train_steps": 500}}
+ )
+ assert at_target["can_resume"] is False
+ assert "nothing left to train" in at_target["resume_blocked_reason"]
+
+
+def test_a_swap_aside_that_cannot_run_fails_the_save_and_keeps_the_old_bundle(run_dir, monkeypatch):
+ """Re-saving an OCCUPIED step has to move the old bundle out of the way first. When that
+ rename cannot run at all -- Windows holding a file open, a cross-device oddity -- deleting
+ the occupant to free the slot was the old way out, and a delete that then failed part-way
+ could fail the promotion too, with no copy left to restore. Fail the save instead: the
+ existing bundle is untouched and the run keeps the resume point it already had."""
+ run = _Run(run_dir)
+ first, error = run.save(4)
+ assert error is None and first is not None
+ before = (Path(first) / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+
+ real_replace = dc.os.replace
+
+ def _refuse_the_swap(src, dst):
+ if "replaced" in Path(dst).name:
+ raise OSError("the directory is in use by another process")
+ return real_replace(src, dst)
+
+ monkeypatch.setattr(dc.os, "replace", _refuse_the_swap)
+ run.step_once(0.5)
+ second, error = run.save(4)
+ monkeypatch.undo()
+
+ assert second is None and error is not None, "an unwritable slot must be reported"
+ kept = run_dir / "checkpoint-4"
+ assert kept.is_dir(), "the existing bundle must survive a save that could not displace it"
+ assert (kept / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8") == before
+ assert dc.latest_valid_checkpoint(run_dir) is not None
+
+
+def test_a_bundle_that_lost_its_random_streams_is_refused(run_dir):
+ """The torch generator lives in the rng FILE; the two random.Random streams the trainers own
+ live in the manifest beside it. restore_rng_state is per-part best-effort, so a bundle that
+ keeps the file and loses the streams restored torch and left the crop/flip and variant draws
+ at their fresh seeds -- a divergence on the first step, under a resume reporting success."""
+ run = _Run(run_dir)
+ path, error = run.save(4)
+ assert error is None and path is not None
+ assert dc.preflight_resume(path, identity = run.identity, target_steps = 500)[1] == 4
+
+ state = Path(path) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(state.read_text(encoding = "utf-8"))
+ manifest["rng"].pop("streams")
+ state.write_text(json.dumps(manifest), encoding = "utf-8")
+ with pytest.raises(dc.ResumeError, match = "random-number streams"):
+ dc.preflight_resume(path, identity = run.identity, target_steps = 500)
+
+ # And losing only ONE of them is the same failure: the variant stream drives the latent
+ # cache's crop and flip picks on its own.
+ manifest["rng"]["streams"] = {"loop": manifest["rng"].get("streams", {}).get("loop")}
+ state.write_text(json.dumps(manifest), encoding = "utf-8")
+ with pytest.raises(dc.ResumeError, match = "random-number streams"):
+ dc.preflight_resume(path, identity = run.identity, target_steps = 500)
+
+
+def test_optimizer_moments_are_refused_when_the_parameter_order_moved(run_dir):
+ """Optimizer state is keyed by parameter POSITION while the adapter is restored by NAME. A
+ PEFT/diffusers upgrade that reorders traversal without renaming anything therefore rebinds
+ every Adam moment to a different tensor -- and LoRA projections share shapes, so it loads
+ cleanly and silently corrupts the continued trajectory."""
+ run = _Run(run_dir)
+ run.step_once(0.5)
+ path, error = run.save(4)
+ assert error is None and path is not None
+
+ state = Path(path) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(state.read_text(encoding = "utf-8"))
+ assert manifest["optimizer_param_names"] == ["weight"], manifest["optimizer_param_names"]
+ manifest["optimizer_param_names"] = ["some.other.lora_A.weight"]
+ state.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ resumed = _Run(run_dir, resume_from_checkpoint = path)
+ with pytest.raises(dc.ResumeError, match = "different parameter order"):
+ resumed.restore()
+
+
+ "module",
+ ["core.training.diffusion_lora_trainer", "core.training.diffusion_dit_trainer"],
+)
+def test_every_completion_reports_whether_the_run_was_discarded(module):
+ """A stop with save=false is a DISCARD however early it lands.
+
+ Both trainers leave early when the stop arrives during the base-model load or the latent
+ cache build, and those completions omitted `discarded`. The service then never marked the
+ attempt discarded, and describe_resume_state's source fallback offered the bundle the run
+ had been validated against -- so the UI showed Resume for an attempt the user had explicitly
+ thrown away."""
+ import builtins
+ import importlib
+ from pathlib import Path as _Path
+
+ source = _Path(importlib.import_module(module).__file__).read_text(encoding = "utf-8")
+ tree = ast.parse(source)
+ completions = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "_emit"
+ and any(isinstance(arg, ast.Constant) and arg.value == "complete" for arg in node.args)
+ ]
+ assert completions, f"{module} must emit a completion"
+ # Every name the discarded expression reads has to be bound in the function it sits in (or
+ # in an enclosing one). Passing `save_on_stop` inside a helper whose flag is really the
+ # caller's `_save_on_stop` accessor is a NameError raised INSTEAD of the terminal stopped
+ # event, which the service then records as a training failure for a user-requested stop.
+ scopes: dict[ast.AST, set[str]] = {}
+ for func in ast.walk(tree):
+ if not isinstance(func, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ bound = {a.arg for a in func.args.args + func.args.kwonlyargs}
+ bound |= {a.arg for a in (func.args.posonlyargs or [])}
+ for node in ast.walk(func):
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
+ bound.add(node.id)
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ bound.add(node.name)
+ elif isinstance(node, (ast.Global, ast.Nonlocal)):
+ bound.update(node.names)
+ scopes[func] = bound
+ # TOP-LEVEL only: a name assigned inside some other function is not visible here, and
+ # walking the whole tree for them is exactly what would hide the bug this checks for.
+ module_level: set[str] = set()
+ for node in tree.body:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ module_level.add(node.name)
+ elif isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.For, ast.With)):
+ module_level |= {
+ n.id
+ for n in ast.walk(node)
+ if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)
+ }
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
+ module_level |= {(a.asname or a.name).split(".")[0] for a in node.names}
+ elif isinstance(node, ast.Try):
+ module_level |= {
+ n.id
+ for n in ast.walk(node)
+ if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)
+ }
+ module_level |= {
+ (a.asname or a.name).split(".")[0]
+ for imp in ast.walk(node)
+ if isinstance(imp, (ast.Import, ast.ImportFrom))
+ for a in imp.names
+ }
+
+ def _visible(call):
+ seen = set(module_level)
+ for func, bound in scopes.items():
+ if any(node is call for node in ast.walk(func)):
+ seen |= bound
+ return seen
+
+ for call in completions:
+ keyword = next((kw for kw in call.keywords if kw.arg == "discarded"), None)
+ assert keyword is not None, (
+ f"a completion in {module} at line {call.lineno} does not say whether the run was "
+ "discarded"
+ )
+ visible = _visible(call) | set(dir(builtins))
+ for name in {n.id for n in ast.walk(keyword.value) if isinstance(n, ast.Name)}:
+ assert name in visible, (
+ f"the completion in {module} at line {call.lineno} reads '{name}', which is not "
+ "bound in any function it sits in -- a NameError instead of a terminal event"
+ )
+
+
+def test_a_branched_resume_does_not_prune_the_bundles_it_found(run_dir):
+ """The supported explicit-checkpoint flow: continue checkpoint-10 while 20 and 30 are still
+ in the directory. Saving 15 with the default limit of 2 pinned 10 and 15, dropped keep to
+ zero and deleted 20 and 30 outright -- bundles this run never wrote and a later
+ stop-without-saving cannot bring back."""
+ # keep-all while seeding, so the three bundles the branch has to survive are really there.
+ seeded = _Run(run_dir, save_total_limit = 0)
+ for step in (10, 20, 30):
+ seeded.step_once(0.5)
+ seeded.save(step)
+ preexisting = dc.snapshot_checkpoints(run_dir)
+ assert {p.name for p, _ in preexisting} == {
+ "checkpoint-10",
+ "checkpoint-20",
+ "checkpoint-30",
+ }
+
+ resumed = _Run(run_dir, resume_from_checkpoint = str(run_dir / "checkpoint-10"))
+ resumed.step_once(1.5)
+ path, error = resumed.save(15, preexisting = preexisting)
+ assert error is None and path == str(run_dir / "checkpoint-15")
+
+ survivors = {p.name for p in dc.list_checkpoints(run_dir)}
+ assert survivors == {
+ "checkpoint-10",
+ "checkpoint-15",
+ "checkpoint-20",
+ "checkpoint-30",
+ }, survivors
+
+
+def test_the_tf32_setting_is_part_of_the_identity(run_dir):
+ """_apply_perf_flags routes CUDA matmuls through TF32 or strict fp32 from this flag, so a
+ resume that silently defaults it back on continues the restored moments under different
+ numeric kernels -- and undoes the strict-reproducibility mode the user asked for. The API
+ field is optional, so omitting it on the resume request is the ordinary way to hit this."""
+ import dataclasses
+
+ strict = _Run(run_dir)
+ strict.cfg = dataclasses.replace(strict.cfg, enable_tf32 = False)
+ strict.identity = dc.identity_for_config(strict.cfg)
+ assert strict.identity.enable_tf32 == "off"
+ path, error = strict.save(4)
+ assert error is None and path is not None
+
+ default = dc.identity_for_config(dataclasses.replace(strict.cfg, enable_tf32 = True))
+ assert default.enable_tf32 == "on"
+ with pytest.raises(dc.ResumeError, match = "TF32"):
+ dc.preflight_resume(path, identity = default, target_steps = 500)
+ # And the matching setting still resumes.
+ assert dc.preflight_resume(path, identity = strict.identity, target_steps = 500)[1] == 4
+
+
+def test_a_stopped_retrain_fences_the_older_runs_checkpoints(run_dir):
+ """A fresh retrain into a directory that still holds an earlier run's higher-step bundle,
+ stopped WITH save. The stop bundle is a lower step, resume-by-directory picks the newest by
+ step, and the leftovers therefore outranked the partial the user had just saved -- a Resume
+ continued the wrong training. A run that RESUMED here keeps what it found; this one does
+ not, because it has just overwritten the adapter those bundles belong to."""
+ earlier = _Run(run_dir, save_total_limit = 0)
+ for step in (20, 30):
+ earlier.step_once(0.5)
+ earlier.save(step)
+ preexisting = dc.snapshot_checkpoints(run_dir)
+
+ retrain = _Run(run_dir, seed = 7)
+ retrain.step_once(1.5)
+ stop_bundle, error = retrain.save(5, preexisting = preexisting)
+ assert error is None and stop_bundle is not None
+
+ dc.discard_preexisting_checkpoints(run_dir, preexisting)
+
+ survivors = {p.name for p in dc.list_checkpoints(run_dir)}
+ assert survivors == {"checkpoint-5"}, survivors
+ assert dc.latest_valid_checkpoint(run_dir)[0].name == "checkpoint-5"
+
+
+def test_the_fencing_keeps_a_bundle_this_run_wrote_over_an_old_one(run_dir):
+ """Identity, not pathname. A retrain that saves at a step an earlier run already used owns
+ the bundle now sitting there, and deleting it by name would throw away the stop checkpoint
+ the user asked for."""
+ earlier = _Run(run_dir, save_total_limit = 0)
+ earlier.step_once(0.5)
+ earlier.save(5)
+ preexisting = dc.snapshot_checkpoints(run_dir)
+
+ retrain = _Run(run_dir, seed = 7)
+ retrain.step_once(1.5)
+ retrain.save(5, preexisting = preexisting)
+ mine = (run_dir / "checkpoint-5" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+
+ dc.discard_preexisting_checkpoints(run_dir, preexisting)
+
+ assert (run_dir / "checkpoint-5").is_dir(), "the run's own stop bundle must survive"
+ assert (run_dir / "checkpoint-5" / dc.TRAINER_STATE_FILENAME).read_text(
+ encoding = "utf-8"
+ ) == mine
+
+
+def test_directory_resume_falls_back_past_a_bundle_that_fails_full_validation(run_dir):
+ """read_checkpoint is a header scan; the preflight's own checks (a real torch.load, the
+ required state) are stricter. Stopping at the newest bundle it accepted meant one unloadable
+ optimizer file left the run unresumable with the retained older copy intact beside it --
+ which is the whole point of keeping two."""
+ run = _Run(run_dir, save_total_limit = 0)
+ good, error = run.save(4)
+ assert error is None and good is not None
+ run.step_once(0.5)
+ newest, error = run.save(8)
+ assert error is None and newest is not None
+
+ # Structurally present, semantically gone: the manifest still lists the rng file and the
+ # header still parses, but the streams it must restore are missing.
+ state = Path(newest) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(state.read_text(encoding = "utf-8"))
+ manifest["rng"].pop("streams")
+ state.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ path, step = dc.preflight_resume(str(run_dir), identity = run.identity, target_steps = 500)
+ assert Path(path).name == "checkpoint-4" and step == 4
+
+ # An EXPLICIT bundle has no alternatives, so its failure is still the answer.
+ with pytest.raises(dc.ResumeError, match = "random-number streams"):
+ dc.preflight_resume(newest, identity = run.identity, target_steps = 500)
+
+
+def test_a_replaced_source_bundle_is_not_offered_back(run_dir):
+ """A resumed run that dies before its first save falls back to the bundle it was validated
+ against. Identified by pathname alone, another run writing its own checkpoint-<N> over the
+ same slot was handed back under the failed run's lineage -- a different branch's adapter and
+ moments, with a matching identity so nothing else would catch it."""
+ seeded = _Run(run_dir, save_total_limit = 0)
+ source, error = seeded.save(10)
+ assert error is None and source is not None
+ original_created = json.loads(
+ (Path(source) / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ )["created_at"]
+
+ state = dc.describe_resume_state(
+ str(run_dir / "nonexistent"),
+ source_checkpoint = source,
+ source_created_at = original_created,
+ )
+ assert state["can_resume"] is True and state["checkpoint_step"] == 10
+
+ # Another run rewrites the same slot.
+ other = _Run(run_dir, seed = 9, save_total_limit = 0)
+ other.step_once(2.0)
+ other.save(10)
+ replaced = dc.describe_resume_state(
+ str(run_dir / "nonexistent"),
+ source_checkpoint = source,
+ source_created_at = original_created,
+ )
+ assert replaced["can_resume"] is False, replaced
+ # And with no recorded timestamp (a record from before this existed) the fallback still works.
+ legacy = dc.describe_resume_state(str(run_dir / "nonexistent"), source_checkpoint = source)
+ assert legacy["can_resume"] is True
+
+
+def test_a_source_fallback_bundle_is_held_to_the_same_load_gate(run_dir):
+ """The source fallback pins its path exactly as the directory scan does, so it needs the
+ same _fully_loadable gate. On read_checkpoint's header scan alone, a source whose required
+ state had gone advertised a Resume that the start route then refused on the first click."""
+ seeded = _Run(run_dir, save_total_limit = 0)
+ source, error = seeded.save(10)
+ assert error is None and source is not None
+
+ healthy = dc.describe_resume_state(str(run_dir / "nonexistent"), source_checkpoint = source)
+ assert healthy["can_resume"] is True and healthy["checkpoint_step"] == 10
+
+ # Structurally present, semantically gone: the header still parses and the recorded sizes
+ # still match, but the streams a resume must restore are no longer listed.
+ state = Path(source) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(state.read_text(encoding = "utf-8"))
+ manifest["rng"].pop("streams")
+ state.write_text(json.dumps(manifest), encoding = "utf-8")
+ assert dc.read_checkpoint(Path(source)) is not None # the header scan still accepts it
+
+ # Both fallback routes: the run's own output dir gone, and present but holding nothing of
+ # this run's.
+ for answer in (
+ dc.describe_resume_state(str(run_dir / "nonexistent"), source_checkpoint = source),
+ dc.describe_resume_state(
+ str(run_dir), started_at = time.time() + 60, source_checkpoint = source
+ ),
+ ):
+ assert answer["can_resume"] is False, answer
+ assert answer["checkpoint_path"] is None, answer
+
+ # And the start route agrees, which is what makes advertising it a dead action.
+ with pytest.raises(dc.ResumeError, match = "random-number streams"):
+ dc.preflight_resume(source, identity = seeded.identity, target_steps = 500)
+
+
+def test_a_dit_family_records_the_bf16_it_actually_runs_in(run_dir):
+ """The DiT trainer never reads mixed_precision: weight_dtype is bf16 on CUDA. Recording the
+ REQUEST put fp16 or "no" in the identity of a run that executed in bf16, and a later bf16
+ resume of it was rejected as a precision mismatch between two runs that ran identically."""
+ import dataclasses
+
+ import torch
+
+ base = _Run(run_dir)
+ for requested in ("fp16", "no", "bf16"):
+ cfg = dataclasses.replace(base.cfg, resolved_family = "flux.1", mixed_precision = requested)
+ expected = "bf16" if torch.cuda.is_available() else "no"
+ assert dc.identity_for_config(cfg).precision == expected, requested
+ # SDXL keeps its own resolution: the request is what that trainer honours.
+ sdxl = dataclasses.replace(base.cfg, resolved_family = "sdxl", mixed_precision = "fp16")
+ assert dc.identity_for_config(sdxl).precision == ("fp16" if torch.cuda.is_available() else "no")
+
+
+def test_a_checkpoint_at_the_target_does_not_roll_back_to_an_older_one(run_dir):
+ """The directory scan walks past a bundle it cannot USE. "Already at the target" is not
+ that: nothing is wrong with the newest bundle, and falling past it returned checkpoint-400
+ of a run that finished at 500 -- rolling the model, optimizer, scheduler and RNG back and
+ retraining completed work, which is the exact rollback the fence exists to prevent."""
+ run = _Run(run_dir, save_total_limit = 0)
+ run.step_once(0.5)
+ run.save(400)
+ run.step_once(0.5)
+ run.save(500)
+
+ with pytest.raises(dc.ResumeError, match = "already at step 500"):
+ dc.preflight_resume(str(run_dir), identity = run.identity, target_steps = 500)
+
+ # Raising the target continues the newest, as before.
+ path, step = dc.preflight_resume(str(run_dir), identity = run.identity, target_steps = 800)
+ assert Path(path).name == "checkpoint-500" and step == 500
+
+
+def test_the_latest_displaced_bundle_is_the_one_restored(run_dir):
+ """Replacements stack. A run that crashed after displacing checkpoint-15 leaves its copy
+ behind, and a later run displacing the same slot leaves another; restoring whichever sorted
+ first by NAME (a uuid) resurrected an older branch's state instead of the predecessor that
+ was actually in the slot."""
+ first = _Run(run_dir, save_total_limit = 0)
+ first.save(15)
+ original = (run_dir / "checkpoint-15" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+
+ # A middle run displaces it and then dies, leaving its own replaced- orphan behind.
+ middle = _Run(run_dir, seed = 5, save_total_limit = 0)
+ middle.step_once(1.0)
+ middle.save(15)
+ displaced_by_middle = (run_dir / "checkpoint-15" / dc.TRAINER_STATE_FILENAME).read_text(
+ encoding = "utf-8"
+ )
+ assert displaced_by_middle != original
+
+ preexisting = dc.snapshot_checkpoints(run_dir)
+ last = _Run(run_dir, seed = 9, save_total_limit = 0)
+ last.step_once(2.0)
+ last.save(15, preexisting = preexisting)
+
+ orphans = list(run_dir.glob(f"{dc._STAGING_PREFIX}replaced-15-*"))
+ assert len(orphans) == 2, "the stacked case needs both copies on disk"
+
+ dc.clear_own_checkpoints(run_dir, preexisting)
+
+ settled = (run_dir / "checkpoint-15" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ assert settled == displaced_by_middle, "the predecessor in the slot is what comes back"
+ assert list(run_dir.glob(f"{dc._STAGING_PREFIX}*")) == []
+
+
+def test_the_first_preflight_does_not_pin_the_bundle_it_accepted(run_dir):
+ """The pre-dataset pass has no fingerprint, so that comparison is SKIPPED and it can accept
+ the newest bundle on the strength of a check it did not make. Rewriting the request to that
+ bundle left the dataset-aware pass able only to reject it, when scanning the original
+ directory would have found an older retained checkpoint matching the current images."""
+ import inspect
+
+ from routes.training import _preflight_diffusion_resume
+
+ run = _Run(run_dir, save_total_limit = 0)
+ run.save(4)
+
+ config = {"resume_from_checkpoint": str(run_dir)}
+ _preflight_diffusion_resume(config, run.identity, 500, pin = False)
+ assert config["resume_from_checkpoint"] == str(run_dir), "the directory must survive"
+
+ # The dataset-aware pass still pins, so the trainer resumes exactly what was approved.
+ _preflight_diffusion_resume(config, run.identity, 500)
+ assert Path(config["resume_from_checkpoint"]).name == "checkpoint-4"
+
+ # And the start route asks for it that way round: no pin AND no target, since the
+ # target refusal is terminal and this pass cannot yet tell whose dataset the newest
+ # bundle belongs to.
+ start = inspect.getsource(__import__("routes.training", fromlist = ["x"]))
+ call = start.index(
+ "_preflight_diffusion_resume,\n config,\n resume_identity,"
+ )
+ window = start[call : call + 900]
+ assert "pin = False" in window
+ assert "normalized_cfg.train_steps" not in window, "the first pass must carry no target"
+
+
+def test_a_read_does_not_undo_a_promotion_in_flight(run_dir):
+ """_promote leaves the slot empty for the instant between the swap-aside and the rename. A
+ history or detail read landing there used to hand the displaced bundle back, and the
+ writer's own os.replace then failed against a directory that had reappeared -- losing the
+ periodic or stop-and-save checkpoint and marking the run unresumable from its latest work."""
+ run = _Run(run_dir, save_total_limit = 0)
+ run.save(4)
+ # The exact mid-swap state: the old bundle moved aside, the slot empty, moments ago.
+ in_flight = run_dir / f"{dc._STAGING_PREFIX}replaced-4-cafebabe"
+ dc.os.replace(run_dir / "checkpoint-4", in_flight)
+
+ dc._recover_orphaned_slots(run_dir)
+
+ assert in_flight.is_dir(), "a live replacement must be left to its writer"
+ assert not (run_dir / "checkpoint-4").exists()
+
+ # Once it is plainly not in flight any more, the same read repairs it.
+ old = time.time() - (dc._LIVE_REPLACEMENT_GRACE_SECONDS + 60)
+ os.utime(in_flight, (old, old))
+ dc._recover_orphaned_slots(run_dir)
+ assert (run_dir / "checkpoint-4").is_dir()
+ assert not in_flight.exists()
+
+
+def test_read_side_recovery_restores_the_newest_stacked_bundle(run_dir):
+ """Filesystem order would restore whichever hidden bundle appeared first. With otherwise
+ identical identities the resume scan then accepts an older branch's adapter, optimizer,
+ scheduler and RNG instead of the one that was in the slot immediately before the crash."""
+ run = _Run(run_dir, save_total_limit = 0)
+ run.save(6)
+ older = run_dir / f"{dc._STAGING_PREFIX}replaced-6-aaaaaaaa"
+ dc.os.replace(run_dir / "checkpoint-6", older)
+ older_state = (older / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+
+ run.step_once(1.0)
+ run.save(6)
+ newer = run_dir / f"{dc._STAGING_PREFIX}replaced-6-bbbbbbbb"
+ dc.os.replace(run_dir / "checkpoint-6", newer)
+ newer_state = (newer / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ assert newer_state != older_state
+
+ # Both plainly abandoned, and the newer one really is newer on disk.
+ stale = time.time() - (dc._LIVE_REPLACEMENT_GRACE_SECONDS + 600)
+ os.utime(older, (stale, stale))
+ os.utime(newer, (stale + 60, stale + 60))
+
+ dc._recover_orphaned_slots(run_dir)
+
+ settled = (run_dir / "checkpoint-6" / dc.TRAINER_STATE_FILENAME).read_text(encoding = "utf-8")
+ assert settled == newer_state, "the bundle that was in the slot last is the one to restore"
+
+
+def test_a_checkpoint_with_no_rng_state_is_not_written(run_dir, monkeypatch):
+ """capture_rng_state never raises -- it returns what it managed to read -- so a torch
+ generator it could not snapshot produced a bundle with no rng file. The write returned
+ happily, the service emitted checkpoint_saved, and the history advertised a resumable stop
+ that the preflight then refuses the moment the user clicks Resume."""
+ run = _Run(run_dir)
+ monkeypatch.setattr(dc, "capture_rng_state", lambda streams = None: {"json": {}, "tensors": {}})
+
+ path, error = run.save(4)
+
+ assert path is None, "an unresumable bundle must not be advertised as saved"
+ assert error is not None and "random-number state" in error
+ assert dc.list_checkpoints(run_dir) == []
+ assert list(run_dir.glob(f"{dc._STAGING_PREFIX}*")) == []
+
+
+def test_a_cuda_capture_that_half_failed_is_not_a_capture(run_dir, monkeypatch):
+ """A secondary visible device erroring left the CPU half in place, so the result was
+ non-empty, the write-time check accepted it, and the preflight -- which only requires
+ torch_cpu -- offered it. The restore then left the CUDA generator at its freshly seeded
+ position, silently changing every latent, noise and timestep draw after the resume."""
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+
+ def _boom():
+ raise RuntimeError("CUDA error: device-side assert triggered")
+
+ monkeypatch.setattr(torch.cuda, "get_rng_state_all", _boom)
+
+ captured = dc.capture_rng_state(_STREAMS())
+ assert captured["tensors"] == {}, "a partial capture must not look like a capture"
+
+ # And the write refuses it rather than advertising an unresumable bundle.
+ run = _Run(run_dir)
+ path, error = run.save(4)
+ assert path is None and error is not None and "random-number state" in error
+
+
+def test_the_resume_action_names_a_bundle_that_actually_loads(run_dir):
+ """read_checkpoint is a header scan, so the newest bundle can pass it and still fail the
+ required-state or torch.load checks. Naming THAT one pinned it: the UI sends the exact
+ checkpoint_path back, the preflight treats it as explicit and cannot scan past it, and the
+ directory fallback built for exactly this case never runs."""
+ run = _Run(run_dir, save_total_limit = 0)
+ run.save(4)
+ run.step_once(0.5)
+ newest, error = run.save(8)
+ assert error is None and newest is not None
+
+ state = Path(newest) / dc.TRAINER_STATE_FILENAME
+ manifest = json.loads(state.read_text(encoding = "utf-8"))
+ manifest["rng"].pop("streams")
+ state.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ described = dc.describe_resume_state(str(run_dir))
+
+ assert described["can_resume"] is True
+ assert Path(described["checkpoint_path"]).name == "checkpoint-4"
+ assert described["checkpoint_step"] == 4
+ # And the path it names really does resume.
+ path, step = dc.preflight_resume(
+ described["checkpoint_path"], identity = run.identity, target_steps = 500
+ )
+ assert Path(path).name == "checkpoint-4" and step == 4
+
+
+def test_a_displaced_bundle_is_stamped_when_it_is_moved_aside(run_dir):
+ """os.replace does NOT restamp the directory -- the inode keeps the mtime the bundle was
+ written with. An old checkpoint moved aside therefore looked long-abandoned the instant it
+ arrived, and a concurrent read handed it back into the slot the writer was about to fill."""
+ run = _Run(run_dir, save_total_limit = 0)
+ written, error = run.save(4)
+ assert error is None and written is not None
+ # Make the bundle plainly old, the way a checkpoint from an earlier session is.
+ old = time.time() - 3600
+ os.utime(written, (old, old))
+
+ run.step_once(1.0)
+ preexisting = dc.snapshot_checkpoints(run_dir)
+ run.save(4, preexisting = preexisting)
+
+ displaced = list(run_dir.glob(f"{dc._STAGING_PREFIX}replaced-4-*"))
+ assert len(displaced) == 1
+ age = time.time() - displaced[0].stat().st_mtime
+ assert (
+ age < dc._LIVE_REPLACEMENT_GRACE_SECONDS
+ ), "the swap-aside must stamp the entry, or the grace protects nothing"
+
+
+def test_an_overwritten_startup_slot_counts_toward_the_limit(run_dir):
+ """The exclusion is about bundles this run did not write. A save at a step whose directory
+ was already there REPLACES it, and the bundle occupying that path afterwards is this run's,
+ so excluding it by pathname let the limit be exceeded once per overwritten slot -- real disk
+ on a long run."""
+ seeded = _Run(run_dir, save_total_limit = 0)
+ seeded.step_once(0.5)
+ seeded.save(10)
+ preexisting = dc.snapshot_checkpoints(run_dir)
+ assert {p.name for p, _ in preexisting} == {"checkpoint-10"}
+
+ run = _Run(run_dir, save_total_limit = 2)
+ for step in (10, 20, 30):
+ run.step_once(1.5)
+ path, error = run.save(step, preexisting = preexisting)
+ assert error is None and path is not None
+
+ survivors = {p.name for p in dc.list_checkpoints(run_dir)}
+ assert survivors == {"checkpoint-20", "checkpoint-30"}, survivors
+
+
+def test_the_resolved_base_precision_is_part_of_the_identity(run_dir):
+ """_apply_fp8_training and _apply_mxfp8_training can fail on the host and both fall back to
+ bf16 with only a warning. A bundle requested as fp8 recorded fp8 while its moments were
+ produced against bf16 linears, so resuming on a host where the conversion does take
+ restored them onto an fp8 frozen base and called it a clean continue."""
+ fell_back = _Run(run_dir)
+ fell_back.identity = dc.with_resolved_base_precision(fell_back.identity, "bf16")
+ assert fell_back.identity.base_precision_effective == "bf16"
+ path, error = fell_back.save(4)
+ assert error is None and path is not None
+
+ took = dc.with_resolved_base_precision(fell_back.identity, "fp8")
+ with pytest.raises(dc.ResumeError, match = "base precision"):
+ dc.preflight_resume(path, identity = took, target_steps = 500)
+ # The same resolution still resumes...
+ assert dc.preflight_resume(path, identity = fell_back.identity, target_steps = 500)[1] == 4
+ # ...and a side that never resolved one reads as "cannot tell" rather than as a mismatch,
+ # which is what keeps the route's pre-eviction preflight and the SDXL trainer unaffected.
+ import dataclasses
+
+ unknown = dataclasses.replace(fell_back.identity, base_precision_effective = None)
+ assert dc.preflight_resume(path, identity = unknown, target_steps = 500)[1] == 4
+
+
+def test_the_ema_decay_is_part_of_the_identity(run_dir):
+ """restore_resume_state loads the old shadow tensors and update count while the trainer
+ builds LoRAEMA from the INCOMING decay, so resuming with a different nonzero decay applies
+ a new coefficient to an average produced under the old one. The exported EMA adapter is a
+ hybrid, and the resume reports success."""
+ import dataclasses
+
+ slow = _Run(run_dir)
+ slow.cfg = dataclasses.replace(slow.cfg, ema_decay = 0.999)
+ slow.identity = dc.identity_for_config(slow.cfg)
+ assert slow.identity.ema_decay == "0.999"
+ path, error = slow.save(4)
+ assert error is None and path is not None
+
+ fast = dc.identity_for_config(dataclasses.replace(slow.cfg, ema_decay = 0.9))
+ with pytest.raises(dc.ResumeError, match = "EMA decay"):
+ dc.preflight_resume(path, identity = fast, target_steps = 500)
+ # Off is a value too, not the same as the request being absent.
+ off = dc.identity_for_config(dataclasses.replace(slow.cfg, ema_decay = 0.0))
+ assert off.ema_decay == "0.0"
+ with pytest.raises(dc.ResumeError, match = "EMA decay"):
+ dc.preflight_resume(path, identity = off, target_steps = 500)
+ assert dc.preflight_resume(path, identity = slow.identity, target_steps = 500)[1] == 4
diff --git a/studio/backend/tests/test_diffusion_train_perf.py b/studio/backend/tests/test_diffusion_train_perf.py
index 3dba5897ea7..f6aa8e58766 100644
--- a/studio/backend/tests/test_diffusion_train_perf.py
+++ b/studio/backend/tests/test_diffusion_train_perf.py
@@ -16,6 +16,8 @@ from __future__ import annotations
import itertools
+from pathlib import Path
+
import pytest
import torch
from fastapi import FastAPI
@@ -248,9 +250,15 @@ def test_service_stop_save_flag():
assert svc.stop(save = False) is True
assert q.items[-1] == {"save": False}
- # The default (save) path keeps the bare-True wire format.
- assert svc.stop() is True
- assert q.items[-1] is True
+ # The default (save) path keeps the bare-True wire format. A SECOND stop on the same job no
+ # longer reaches the child (see test_a_second_stop_does_not_change_what_the_child_was_told),
+ # so this is a fresh one.
+ other = DiffusionTrainingService()
+ other._proc = _AliveProc()
+ other_q = _StopQueue()
+ other._stop_queue = other_q
+ assert other.stop() is True
+ assert other_q.items[-1] is True
# ── preparing / warning events + stopped completion messages ──────────────────
@@ -456,3 +464,387 @@ def test_sdxl_cache_force_bypasses_gate(monkeypatch):
cache = _build_fake_sdxl_cache(monkeypatch, num_images = 3, latent_shape = (1, 4, 8, 8))
assert cache is not LATENT_CACHE_OVER_BUDGET and cache is not None
assert len(cache) == 3
+
+
+def test_a_no_save_stop_survives_a_child_that_dies_before_reporting_it():
+ """The trainer reports the discard on its completion event, but a child that OOMs or is
+ killed after the request never emits one. The unexpected-exit path then recorded a plain
+ error run with the last periodic checkpoint intact, so the history offered Resume from the
+ very bundle the user asked to throw away. The intent is remembered in the parent."""
+
+ class _DeadProc:
+ def is_alive(self) -> bool:
+ return False
+
+ svc = DiffusionTrainingService()
+ svc._proc = _AliveProc()
+ svc._stop_queue = _StopQueue()
+ svc._apply_event(
+ {"type": "checkpoint_saved", "checkpoint_path": "/o/checkpoint-40", "step": 40}
+ )
+ assert svc.status()["resume_blocked_reason"] is None
+
+ assert svc.stop(save = False) is True
+ # ...and the child dies without a completion event.
+ dead = _DeadProc()
+ svc._proc = dead
+
+ class _EmptyQueue:
+ def get(self, timeout = None):
+ raise RuntimeError("empty")
+
+ def get_nowait(self):
+ raise RuntimeError("empty")
+
+ svc._pump_loop(_EmptyQueue(), dead)
+
+ state = svc.status()
+ assert state["status"] == "error"
+ assert "stopped without saving" in (state["resume_blocked_reason"] or "")
+
+
+def test_a_fresh_job_forgets_the_previous_no_save_stop():
+ """The flag is per job. Carrying it across would block a resume the next run legitimately
+ offers."""
+ import inspect
+
+ svc = DiffusionTrainingService()
+ assert svc._discard_requested is False
+ svc._proc = _AliveProc()
+ svc._stop_queue = _StopQueue()
+ assert svc.stop(save = False) is True
+ assert svc._discard_requested is True
+ # start() clears it for the next job, so a discarded run cannot block the next one's resume.
+ assert "_discard_requested = False" in inspect.getsource(DiffusionTrainingService.start)
+
+
+def test_a_discard_is_applied_to_a_terminal_error_too(tmp_path, monkeypatch):
+ """An exception on the current step is a terminal `error`, and the pump returns on that path
+ rather than through the dead-process branch -- so a stop-without-saving followed by a crash
+ left the periodic checkpoint resumable in history."""
+ import core.training.diffusion_checkpoint as dc
+
+ bundle = tmp_path / "checkpoint-40"
+ bundle.mkdir()
+ (bundle / "keep.bin").write_bytes(b"x")
+
+ class _Proc:
+ def is_alive(self) -> bool:
+ return True
+
+ class _OneEvent:
+ def __init__(self, ev):
+ self._events = [ev]
+
+ def get(self, timeout = None):
+ if self._events:
+ return self._events.pop(0)
+ raise RuntimeError("empty")
+
+ svc = DiffusionTrainingService()
+ proc = _Proc()
+ svc._proc = proc
+ svc._stop_queue = _StopQueue()
+ svc._apply_event({"type": "checkpoint_saved", "checkpoint_path": str(bundle), "step": 40})
+ assert svc.stop(save = False) is True
+ monkeypatch.setattr(svc, "_persist_run_record", lambda **_kw: None)
+
+ svc._pump_loop(_OneEvent({"type": "error", "message": "CUDA out of memory"}), proc)
+
+ state = svc.status()
+ assert state["status"] == "error"
+ assert "stopped without saving" in (state["resume_blocked_reason"] or "")
+ # And the bundles the run wrote are gone: they hold optimizer state and the UI offers no
+ # delete path once the run is marked discarded.
+ assert not bundle.exists()
+ assert dc is not None
+
+
+def test_a_killed_discard_removes_only_this_runs_bundles(tmp_path):
+ """The parent knows exactly which bundles it saw checkpoint_saved for, so an earlier run's
+ leftovers in the same directory are untouched."""
+
+ class _Dead:
+ def is_alive(self) -> bool:
+ return False
+
+ class _Empty:
+ def get(self, timeout = None):
+ raise RuntimeError("empty")
+
+ def get_nowait(self):
+ raise RuntimeError("empty")
+
+ earlier = tmp_path / "checkpoint-99"
+ earlier.mkdir()
+ mine = tmp_path / "checkpoint-40"
+ mine.mkdir()
+
+ svc = DiffusionTrainingService()
+ svc._proc = _AliveProc()
+ svc._stop_queue = _StopQueue()
+ svc._apply_event({"type": "checkpoint_saved", "checkpoint_path": str(mine), "step": 40})
+ assert svc.stop(save = False) is True
+ dead = _Dead()
+ svc._proc = dead
+ svc._pump_loop(_Empty(), dead)
+
+ assert not mine.exists(), "this run's bundle must go"
+ assert earlier.is_dir(), "an earlier run's bundle is not this run's to delete"
+
+
+def test_an_epoch_mode_target_does_not_fall_back_to_the_unused_step_count():
+ """num_epochs overrides train_steps, which then still carries the request model's default of
+ 500. Using it for a run that died before its `resumed` event reported a 600-step checkpoint
+ as 600/500 and refused the resume."""
+ from core.training.diffusion_training_service import _resolved_total_steps
+
+ assert (
+ _resolved_total_steps({"total_steps": 1000}, {"num_epochs": 4, "train_steps": 500}) == 1000
+ )
+ assert _resolved_total_steps({}, {"num_epochs": 4, "train_steps": 500}) == 0
+ # Step mode is unchanged: the configured count is the target.
+ assert _resolved_total_steps({}, {"num_epochs": 0, "train_steps": 500}) == 500
+
+
+def test_the_read_time_refresh_uses_the_same_epoch_rule():
+ """The persisted record may carry the right target, but every read recomputes it -- and the
+ read side was still falling back to the request model's unused train_steps in epoch mode,
+ so a 600-step checkpoint of a run resolved to 1000 read as 600/500 and Resume was
+ disabled again the moment the run was listed."""
+ import inspect
+
+ from core.training.diffusion_training_service import _refresh_resume_state
+
+ source = inspect.getsource(_refresh_resume_state)
+ assert "_resolved_total_steps(" in source, "the read side must use the shared rule"
+ assert 'config.get("train_steps")' not in source, "and not the raw fallback it replaced"
+
+
+def test_the_source_identity_is_seeded_before_the_child_starts():
+ """The route has already validated and pinned a source bundle, so a resume that dies during
+ the model load -- before the trainer can emit `resumed` -- still needs the timestamp its
+ fallback is checked against, or the pathname alone offers back whatever later occupies the
+ slot."""
+ import inspect
+
+ from core.training.diffusion_training_service import DiffusionTrainingService
+
+ start = inspect.getsource(DiffusionTrainingService.start)
+ assert "_seed_source_identity(config)" in start
+ seeded = start.index("_seed_source_identity(config)")
+ # AFTER the state reset, which replaces the whole dict and would drop the seed...
+ assert seeded > start.index("self._state = _idle_state()")
+ # ...and before the pump thread starts, which is the only other writer of that state.
+ assert seeded < start.index("self._pump.start()")
+
+
+def test_seeding_reads_the_bundles_own_timestamp(tmp_path, monkeypatch):
+ import json as _json
+
+ from core.training.diffusion_training_service import DiffusionTrainingService
+
+ bundle = tmp_path / "checkpoint-10"
+ bundle.mkdir()
+ svc = DiffusionTrainingService()
+ monkeypatch.setattr(
+ "core.training.diffusion_checkpoint.read_checkpoint",
+ lambda path: {"created_at": 1234.5} if Path(path) == bundle else None,
+ )
+ svc._seed_source_identity({"resume_from_checkpoint": str(bundle)})
+ assert svc._state["resumed_source_created_at"] == 1234.5
+ # An unreadable or absent bundle simply records nothing rather than raising.
+ svc._seed_source_identity({"resume_from_checkpoint": str(tmp_path / "checkpoint-99")})
+ assert _json.dumps(svc._state["resumed_source_created_at"]) in ("1234.5", "null")
+
+
+def test_a_child_that_cleaned_up_is_not_cleaned_up_again(tmp_path, monkeypatch):
+ """The trainer's own discard hands a displaced slot back to the bundle it replaced, so the
+ path this run wrote to now holds ANOTHER run's checkpoint. The parent cleanup knows only
+ pathnames, and repeating it deleted that restored original -- cancelling one branch
+ destroyed a different run's resume point."""
+ from core.training.diffusion_training_service import DiffusionTrainingService
+
+ class _Proc:
+ def is_alive(self) -> bool:
+ return True
+
+ class _OneEvent:
+ def __init__(self, ev):
+ self._events = [ev]
+
+ def get(self, timeout = None):
+ if self._events:
+ return self._events.pop(0)
+ raise RuntimeError("empty")
+
+ # What the child restored into the slot this run had written over.
+ restored = tmp_path / "checkpoint-10"
+ restored.mkdir()
+ (restored / "adapter.safetensors").write_bytes(b"other run")
+
+ svc = DiffusionTrainingService()
+ proc = _Proc()
+ svc._proc = proc
+ svc._stop_queue = _StopQueue()
+ svc._apply_event({"type": "checkpoint_saved", "checkpoint_path": str(restored), "step": 10})
+ assert svc.stop(save = False) is True
+ monkeypatch.setattr(svc, "_persist_run_record", lambda **_kw: None)
+
+ svc._pump_loop(
+ _OneEvent(
+ {"type": "complete", "output_dir": str(tmp_path), "stopped": True, "discarded": True}
+ ),
+ proc,
+ )
+
+ assert restored.exists(), "the bundle the child handed back is not this run's to delete"
+ # The state half of the discard still applies.
+ state = svc.status()
+ assert "stopped without saving" in (state["resume_blocked_reason"] or "")
+ assert state["checkpoint_path"] is None
+
+
+def test_a_checkpoint_makes_the_run_recoverable_before_it_ends(tmp_path, monkeypatch):
+ """Previous runs is built from the run JSONs and nothing else, and only a terminal event
+ wrote one. Studio being killed after a periodic save therefore left a resumable bundle on
+ disk with no entry and no Resume action for it."""
+ import inspect
+ import json as _json
+
+ from core.training import diffusion_training_service as svc_mod
+
+ runs = tmp_path / "runs"
+ runs.mkdir()
+ monkeypatch.setattr(svc_mod, "_runs_dir", lambda: runs)
+
+ svc = svc_mod.DiffusionTrainingService()
+ svc._state.update(job_id = "a" * 32, output_dir = str(tmp_path / "out"), status = "running")
+
+ # A landed checkpoint asks for the record...
+ svc._apply_event(
+ {"type": "checkpoint_saved", "checkpoint_path": str(tmp_path / "checkpoint-40"), "step": 40}
+ )
+ assert svc._persist_interim is True
+ # ...and the pump writes it, rather than waiting for a terminal event that may never come.
+ assert "_persist_run_record(interim = True)" in inspect.getsource(
+ svc_mod.DiffusionTrainingService._pump_loop
+ )
+
+ svc._persist_run_record(interim = True)
+ written = runs / f"{'a' * 32}.json"
+ assert written.exists(), "the checkpoint landed but nothing recorded the run"
+ record = _json.loads(written.read_text(encoding = "utf-8"))
+ assert record["job_id"] == "a" * 32
+ # Interrupted is what it IS until the run ends; the terminal write replaces this file.
+ assert record["status"] == "error"
+
+ # ...and while the process is still on that job, the reader says so rather than offering a
+ # Resume for a directory the live run is writing into.
+ svc_mod._service = svc
+ try:
+ assert svc_mod._restate_live_job(dict(record))["status"] == "running"
+ finally:
+ svc_mod._service = None
+
+
+def test_a_failed_checkpoint_write_is_recorded_too(tmp_path, monkeypatch):
+ """The failure is sticky in memory, but only a successful write asked for a record. Studio
+ exiting after one left the last persisted record advertising the OLDER checkpoint as
+ resumable -- the one the service has just decided is stale -- and resuming it rolls the run
+ back past everything after it."""
+ import json as _json
+
+ from core.training import diffusion_training_service as svc_mod
+
+ runs = tmp_path / "runs"
+ runs.mkdir()
+ monkeypatch.setattr(svc_mod, "_runs_dir", lambda: runs)
+
+ svc = svc_mod.DiffusionTrainingService()
+ svc._state.update(job_id = "b" * 32, output_dir = str(tmp_path / "out"), status = "running")
+ svc._apply_event(
+ {"type": "checkpoint_saved", "checkpoint_path": str(tmp_path / "checkpoint-40"), "step": 40}
+ )
+ svc._persist_interim = False
+
+ svc._apply_event({"type": "checkpoint_failed", "message": "disk full"})
+ assert svc._persist_interim is True
+
+ svc._persist_run_record(interim = True)
+ record = _json.loads((runs / f"{'b' * 32}.json").read_text(encoding = "utf-8"))
+ assert record["checkpoint_write_error"] == "disk full"
+ assert record["can_resume"] is False
+
+
+def test_the_live_job_is_not_offered_as_resumable(tmp_path, monkeypatch):
+ """The interim record is written with an error status, so the resume fields are derived as
+ though the run were over. _UNRESUMABLE_STATUS rejects a running job for a reason: its output
+ directory is being written right now, and a Resume offered there can only race it."""
+ from core.training import diffusion_training_service as svc_mod
+
+ svc = svc_mod.DiffusionTrainingService()
+ svc._state.update(job_id = "c" * 32, status = "running", message = "Training...")
+
+ record = {
+ "job_id": "c" * 32,
+ "status": "error",
+ "can_resume": True,
+ "checkpoint_path": str(tmp_path / "checkpoint-40"),
+ }
+ svc_mod._service = svc
+ try:
+ restated = svc_mod._restate_live_job(dict(record))
+ finally:
+ svc_mod._service = None
+
+ assert restated["status"] == "running"
+ assert restated["can_resume"] is False
+ assert restated["checkpoint_path"] is None
+
+
+def test_one_bad_record_does_not_take_the_history_with_it(tmp_path, monkeypatch):
+ """Every other kind of corruption here is skipped per record. A valid-JSON record with the
+ required job_id and status but a nonnumeric counter reached the refresh and raised out of
+ the listing, so one hand-edited or older file blanked the whole Previous runs panel."""
+ import json as _json
+
+ from core.training import diffusion_training_service as svc_mod
+
+ runs = tmp_path / "runs"
+ runs.mkdir()
+ monkeypatch.setattr(svc_mod, "_runs_dir", lambda: runs)
+
+ (runs / f"{'d' * 32}.json").write_text(
+ _json.dumps({"job_id": "d" * 32, "status": "completed", "total_steps": "many"}),
+ encoding = "utf-8",
+ )
+ (runs / f"{'e' * 32}.json").write_text(
+ _json.dumps({"job_id": "e" * 32, "status": "completed", "total_steps": 500}),
+ encoding = "utf-8",
+ )
+
+ listed = svc_mod.list_diffusion_runs()
+ assert [r["job_id"] for r in listed] == ["e" * 32]
+ # ...and the detail endpoint answers with the stored record rather than a 500.
+ assert svc_mod.get_diffusion_run("d" * 32)["job_id"] == "d" * 32
+
+
+def test_a_second_stop_does_not_change_what_the_child_was_told(tmp_path):
+ """The child consumes the FIRST signal and acts on it. A later stop-without-saving cannot
+ un-export an adapter it has already written, so honouring it set a parent discard the child
+ never carried out: the run was marked discarded and its checkpoints deleted while the
+ adapter and catalog entry it published stayed on disk."""
+ from core.training.diffusion_training_service import DiffusionTrainingService
+
+ svc = DiffusionTrainingService()
+ svc._proc = _AliveProc()
+ queue = _StopQueue()
+ svc._stop_queue = queue
+
+ assert svc.stop(save = True) is True
+ assert svc._discard_requested is False
+ # Still "a stop is in flight", but the disposition is whichever one the child actually got.
+ assert svc.stop(save = False) is True
+ assert svc._discard_requested is False
+ assert len(queue.items) == 1
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index e1510a06fc2..d63a955eb52 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -426,6 +426,15 @@ export interface DiffusionTrainingStartRequest {
cache_variants?: number;
// Allow TF32 matmuls on Ampere+ for a throughput win at negligible quality cost.
enable_tf32?: boolean;
+ // Write a resumable checkpoint every N optimizer steps. 0 (the default) writes none; a
+ // stop-and-save always writes one, so Resume stays available either way.
+ save_steps?: number;
+ save_total_limit?: number;
+ // Continue a previous run: its output_dir, or one explicit checkpoint-<N> directory inside it.
+ // train_steps then means the TARGET TOTAL, so a checkpoint at 11 with train_steps 500 runs 12..500.
+ resume_from_checkpoint?: string | null;
+ // The run being continued. Recorded in the history for lineage only.
+ resumed_from_job_id?: string | null;
// Forwarded to the pipeline's from_pretrained for a gated/private base repo (e.g. FLUX).
hf_token?: string | null;
}
@@ -466,6 +475,12 @@ export interface DiffusionTrainingStatus {
// Live throughput + peak VRAM (from the trainer's progress events).
samples_per_second?: number | null;
peak_memory_gb?: number | null;
+ // The newest resume checkpoint this job wrote, the step it holds, why one could not be written,
+ // and the step a resumed job picked up from. Absent on an older backend.
+ checkpoint_path?: string | null;
+ checkpoint_step?: number | null;
+ resume_blocked_reason?: string | null;
+ resumed_from_step?: number | null;
// Bounded step/loss/lr history for the live charts.
metric_history?: DiffusionMetricHistory | null;
}
@@ -509,6 +524,18 @@ export interface DiffusionTrainingRunSummary {
instance_prompt?: string | null;
started_at?: number | null;
ended_at?: number | null;
+ // The run's adapter directory, which is what a Resume replays as resume_from_checkpoint.
+ output_dir?: string | null;
+ // Whether the run can be continued, re-derived from the checkpoints on disk on every read, with
+ // the step the newest bundle holds. When false, resume_blocked_reason says why (tooltip text).
+ can_resume?: boolean;
+ checkpoint_step?: number | null;
+ // The exact bundle a resume would continue; sent back as resume_from_checkpoint.
+ checkpoint_path?: string | null;
+ resume_blocked_reason?: string | null;
+ // Lineage: the run this one continued, and the step it picked up from.
+ resumed_from_job_id?: string | null;
+ resumed_from_step?: number | null;
}
export interface DiffusionTrainingRunDetail extends DiffusionTrainingRunSummary {
diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
index fa55056c53d..cae82c8fc12 100644
--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
@@ -95,6 +95,10 @@ import {
runExampleImport,
shortExampleLabel,
} from "./example-dataset-cards";
+import {
+ buildDiffusionResumePayload,
+ resumeActionLabel,
+} from "./resume-diffusion-run";
// The families the Train tab can train, in popularity order; a fallback for an older backend whose /info reports none.
type FamilyPreset = {
@@ -430,6 +434,9 @@ export function DiffusionTrainPanel({
const [batchSize, setBatchSize] = useState(1);
const [gradAccum, setGradAccum] = useState(1);
const [seed, setSeed] = useState(42);
+ // Periodic resume points. 0 (off) keeps the default behaviour: only a stop-and-save writes one,
+ // so nothing is spent on disk unless the user asks to survive a crash.
+ const [saveSteps, setSaveSteps] = useState(0);
// LR schedule. Warmup only applies to the non-constant schedules; plain "constant" ignores it.
const [lrScheduler, setLrScheduler] = useState<
"constant" | "constant_with_warmup" | "cosine" | "linear"
@@ -470,6 +477,8 @@ export function DiffusionTrainPanel({
const [stopDialogOpen, setStopDialogOpen] = useState(false);
// Set when the user confirms a stop. Clamped to the running state at read time so a fresh run never inherits it.
const [stopRequestedLocal, setStopRequestedLocal] = useState(false);
+ // The run whose Resume request is in flight, so its button alone shows the pending label.
+ const [resumingJobId, setResumingJobId] = useState<string | null>(null);
const refreshInfo = useCallback(async (): Promise<DiffusionTrainingInfo | null> => {
try {
@@ -642,6 +651,14 @@ export function DiffusionTrainPanel({
// The pending-stop flag only matters while a run is active; clamping at read time means a fresh run never inherits a stale "Stopping...".
const stopRequested = running && stopRequestedLocal;
+ // The just-finished run's persisted record, which is where can_resume lives (the live status has
+ // no way to know whether the checkpoint survived on disk). It appears a beat after the terminal
+ // status, via the delayed refetch below, so the Resume action enables itself once it lands.
+ const liveRunSummary = useMemo(
+ () => prevRuns.find((r) => r.job_id === status?.job_id) ?? null,
+ [prevRuns, status?.job_id],
+ );
+
// Whether there is a run to show live: running, or ANY terminal run the user has not dismissed. Dismissing must cover every
// terminal status, or "Train another" after a stop would trap the run view with no way back to the settings.
const terminalStatuses = ["completed", "stopped", "error"];
@@ -1019,6 +1036,7 @@ export function DiffusionTrainPanel({
lr_scheduler: lrScheduler,
lr_warmup_steps: lrScheduler === "constant" ? 0 : lrWarmupSteps,
lora_rank: rank,
+ save_steps: Math.max(0, Math.floor(saveSteps)),
mixed_precision: precision,
// DiT families quantise the base weights; sdxl uses mixed_precision above and ignores this. Only send compile where supported.
base_precision: isDiT ? basePrecision : undefined,
@@ -1048,6 +1066,7 @@ export function DiffusionTrainPanel({
batchSize,
gradAccum,
seed,
+ saveSteps,
gradCheckpoint,
lrScheduler,
lrWarmupSteps,
@@ -1060,6 +1079,41 @@ export function DiffusionTrainPanel({
poll,
]);
+ // Continue a stopped run from its newest checkpoint. The stored config is replayed verbatim
+ // (same hyperparameters, same output folder, same TARGET step count), with the run's output
+ // directory as resume_from_checkpoint -- the same approach as the LLM tab's resumeTrainingRun.
+ // The detail is re-fetched on click so `can_resume` reflects the checkpoints on disk right now,
+ // not whatever the list was showing when it was last polled.
+ const onResume = useCallback(
+ async (jobId: string) => {
+ setResumingJobId(jobId);
+ try {
+ const detail = await getDiffusionTrainingRun(jobId);
+ const payload = buildDiffusionResumePayload(detail, {
+ hfToken: hfApiToken(getHfToken()) || undefined,
+ });
+ await startDiffusionTraining(payload);
+ // Only after the start is ACCEPTED: a refusal (identity mismatch, a job already running)
+ // must leave the history detail the user was reading exactly as it was.
+ setStopRequestedLocal(false);
+ notifiedComplete.current = false;
+ setViewRun(null);
+ setDismissedJobId(null);
+ toast.success(
+ detail.checkpoint_step != null
+ ? `Resuming from step ${detail.checkpoint_step}`
+ : "Resuming training",
+ );
+ void poll();
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to resume training");
+ } finally {
+ setResumingJobId(null);
+ }
+ },
+ [poll],
+ );
+
// Confirm-then-stop, mirroring the LLM Train tab. `save` writes the current adapter before halting; false discards it.
const onStop = useCallback(
async (save: boolean) => {
@@ -1224,6 +1278,10 @@ export function DiffusionTrainPanel({
min: 0,
hint: "Fixes the run's randomness, so the same settings and images reproduce the same LoRA.",
})}
+ {numberField("Checkpoint every", saveSteps, setSaveSteps, 0, {
+ min: 0,
+ hint: "Saves a resume point every this many steps, so a crash or a shutdown can be picked up where it left off. 0 turns it off; stopping and saving always leaves one either way.",
+ })}
</div>
<div className="grid grid-cols-1 items-start gap-x-6 gap-y-5 @min-[324px]:grid-cols-2 @min-[498px]:grid-cols-3">
@@ -1768,8 +1826,12 @@ export function DiffusionTrainPanel({
? ` - ${new Date(viewRun.ended_at * 1000).toLocaleString()}`
: ""}
</p>
- {viewRun.saved && viewRun.catalog_path && (
- <div>
+ {/* Deploy and Resume sit together: a stopped run's two next steps are "use what I
+ have" and "carry on training it". Resume stays visible but disabled when the
+ backend says it cannot, with the reason as the tooltip, so the absence of a
+ checkpoint is explained rather than silently hiding the action. */}
+ <div className="flex flex-wrap items-center gap-2">
+ {viewRun.saved && viewRun.catalog_path && (
<Button
type="button"
size="sm"
@@ -1784,8 +1846,27 @@ export function DiffusionTrainPanel({
>
Deploy to Create
</Button>
- </div>
- )}
+ )}
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => void onResume(viewRun.job_id)}
+ disabled={
+ !viewRun.can_resume || running || resumingJobId === viewRun.job_id
+ }
+ title={
+ viewRun.can_resume
+ ? undefined
+ : viewRun.resume_blocked_reason ||
+ "This run has no checkpoint to continue from."
+ }
+ >
+ {resumingJobId === viewRun.job_id
+ ? "Resuming..."
+ : resumeActionLabel(viewRun)}
+ </Button>
+ </div>
</div>
<DiffusionCharts
lossHistory={viewLossHistory}
@@ -1918,20 +1999,36 @@ export function DiffusionTrainPanel({
{stopRequested ? "Stopping..." : "Stop training"}
</Button>
)}
- {/* Terminal runs WITHOUT an adapter card (error, or a discarded stop) still need a way back to the settings. */}
+ {/* Terminal runs WITHOUT an adapter card (error, or a discarded stop) still need a way back to the settings.
+ They can also be the most worth resuming: a crash mid-run leaves no adapter but may well have left a
+ periodic checkpoint, so offer Resume here too when the backend says there is one. */}
{!running &&
status &&
terminalStatuses.includes(status.status) &&
!completed &&
!stoppedWithAdapter && (
- <Button
- type="button"
- variant="outline"
- className="w-full"
- onClick={() => setDismissedJobId(status.job_id)}
- >
- Back to settings
- </Button>
+ <div className="flex flex-wrap gap-2">
+ {liveRunSummary?.can_resume && status.job_id && (
+ <Button
+ type="button"
+ className="flex-1"
+ onClick={() => void onResume(status.job_id as string)}
+ disabled={resumingJobId === status.job_id}
+ >
+ {resumingJobId === status.job_id
+ ? "Resuming..."
+ : resumeActionLabel(liveRunSummary)}
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="outline"
+ className="flex-1"
+ onClick={() => setDismissedJobId(status.job_id)}
+ >
+ Back to settings
+ </Button>
+ </div>
)}
</div>
@@ -1952,10 +2049,39 @@ export function DiffusionTrainPanel({
<span className="mt-1 block break-all">EMA adapter: {status.ema_path}</span>
)}
</p>
- <div className="mt-1 flex gap-2">
+ <div className="mt-1 flex flex-wrap gap-2">
<Button type="button" size="sm" onClick={onDeployClick}>
Deploy to Create
</Button>
+ {/* Only a run stopped short can be continued; a completed one is already at its
+ target. Disabled until the run record lands (and enabled only if its
+ checkpoint really is on disk), with the backend's reason as the tooltip. */}
+ {!completed && status?.job_id && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => void onResume(status.job_id as string)}
+ disabled={
+ !liveRunSummary?.can_resume ||
+ running ||
+ resumingJobId === status.job_id
+ }
+ title={
+ liveRunSummary?.can_resume
+ ? undefined
+ : liveRunSummary?.resume_blocked_reason ||
+ status.resume_blocked_reason ||
+ "Saving this run's checkpoint..."
+ }
+ >
+ {resumingJobId === status.job_id
+ ? "Resuming..."
+ : resumeActionLabel(
+ liveRunSummary ?? { checkpoint_step: status.checkpoint_step },
+ )}
+ </Button>
+ )}
<Button
type="button"
size="sm"
diff --git a/studio/frontend/src/features/images/train/resume-diffusion-run.ts b/studio/frontend/src/features/images/train/resume-diffusion-run.ts
new file mode 100644
index 00000000000..9fc8e9d79ac
--- /dev/null
+++ b/studio/frontend/src/features/images/train/resume-diffusion-run.ts
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type {
+ DiffusionTrainingRunDetail,
+ DiffusionTrainingRunSummary,
+ DiffusionTrainingStartRequest,
+} from "../api";
+
+export const RESUME_UNAVAILABLE_MESSAGE =
+ "This run has no checkpoint to continue from. Start a new run instead.";
+
+
+/**
+ * Replay a finished diffusion run's stored start config as a resume request.
+ *
+ * The same shape as the LLM tab's `resumeTrainingRun`: the run's own config is the source of
+ * truth (so the resumed job trains with exactly the hyperparameters it was stopped with), with
+ * `resume_from_checkpoint` pointed at the run's output directory. The backend picks the newest
+ * complete `checkpoint-<N>` bundle inside it and continues at N+1, up to the SAME `train_steps`
+ * target the original run had -- resuming a stop at 11 of 500 trains steps 12..500, it does not
+ * queue another 500.
+ *
+ * Pure and throwing: the caller owns the toast. The thrown message is the backend's
+ * `resume_blocked_reason` whenever it has one, since the server explains a refusal precisely and
+ * a generic message here would contradict it.
+ */
+export function buildDiffusionResumePayload(
+ detail: DiffusionTrainingRunDetail,
+ options: { hfToken?: string | null } = {},
+): DiffusionTrainingStartRequest {
+ const outputDir = detail.output_dir ?? null;
+ if (!(detail.can_resume && outputDir)) {
+ throw new Error(detail.resume_blocked_reason || RESUME_UNAVAILABLE_MESSAGE);
+ }
+ const config = (detail.config ?? {}) as Partial<DiffusionTrainingStartRequest>;
+ if (!config.base_model || !config.data_dir || !config.output_dir) {
+ // A record from a much older backend (or a hand-edited one) cannot be replayed safely: a
+ // missing path would resolve somewhere else entirely and train the wrong thing.
+ throw new Error(
+ "This run's saved settings are incomplete, so it cannot be resumed automatically.",
+ );
+ }
+
+ // Destructured out rather than deleted off a widened copy: these three are replaced below, not
+ // inherited. Replaying them verbatim would point the new run at whatever the OLD run resumed,
+ // and the token is never persisted anyway.
+ const {
+ hf_token: _replacedToken,
+ resume_from_checkpoint: _replacedCheckpoint,
+ resumed_from_job_id: _replacedJobId,
+ ...inherited
+ } = config;
+ return {
+ ...inherited,
+ // Re-stated because the narrowing above proved them present, which `Partial` cannot carry.
+ base_model: config.base_model,
+ data_dir: config.data_dir,
+ output_dir: config.output_dir,
+ // The EXACT bundle the backend advertised, when it named one. Sending only the run folder
+ // would let the server re-pick "newest", which in a folder two runs share is not necessarily
+ // the one whose step this UI is showing.
+ resume_from_checkpoint: detail.checkpoint_path || outputDir,
+ resumed_from_job_id: detail.job_id,
+ hf_token: options.hfToken || undefined,
+ };
+}
+
+/** The label the Resume action shows, including the step it would continue from. */
+export function resumeActionLabel(
+ run: Pick<DiffusionTrainingRunSummary, "checkpoint_step">,
+): string {
+ return run.checkpoint_step != null
+ ? `Resume from step ${run.checkpoint_step}`
+ : "Resume training";
+}
diff --git a/studio/frontend/tests/resume-diffusion-run.test.ts b/studio/frontend/tests/resume-diffusion-run.test.ts
new file mode 100644
index 00000000000..1f62c6bf353
--- /dev/null
+++ b/studio/frontend/tests/resume-diffusion-run.test.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { DiffusionTrainingRunDetail } from "../src/features/images/api.ts";
+
+const { buildDiffusionResumePayload, resumeActionLabel } = await import(
+ "../src/features/images/train/resume-diffusion-run.ts"
+);
+
+// A finished run's persisted record, as GET /api/train/diffusion/runs/{id} returns it. `config`
+// is the scrubbed start request the run was launched with, which a resume replays verbatim.
+function stoppedRun(
+ overrides: Partial<DiffusionTrainingRunDetail> = {},
+): DiffusionTrainingRunDetail {
+ return {
+ job_id: "a".repeat(32),
+ status: "stopped",
+ step: 11,
+ total_steps: 500,
+ saved: true,
+ can_resume: true,
+ checkpoint_step: 11,
+ checkpoint_path: "/studio/outputs/my-lora/checkpoint-11",
+ output_dir: "/studio/outputs/my-lora",
+ config: {
+ base_model: "stabilityai/sdxl-turbo",
+ data_dir: "/studio/datasets/my-images",
+ output_dir: "/studio/outputs/my-lora",
+ train_steps: 500,
+ lora_rank: 16,
+ seed: 42,
+ // Left over from the run that produced this record; both must be replaced, not inherited.
+ resume_from_checkpoint: "/studio/outputs/my-lora/checkpoint-3",
+ resumed_from_job_id: "b".repeat(32),
+ },
+ ...overrides,
+ };
+}
+
+test("replays the run's own config and points it at the run's output directory", () => {
+ const payload = buildDiffusionResumePayload(stoppedRun(), { hfToken: "hf_x" });
+ // train_steps is the TARGET TOTAL: the backend continues at 12 and stops at 500.
+ assert.equal(payload.train_steps, 500);
+ assert.equal(payload.lora_rank, 16);
+ assert.equal(payload.seed, 42);
+ assert.equal(payload.base_model, "stabilityai/sdxl-turbo");
+ // The EXACT bundle the backend named, not just the folder: two runs can share an output
+ // directory, so "newest in that folder" is not necessarily the step the UI is showing.
+ assert.equal(
+ payload.resume_from_checkpoint,
+ "/studio/outputs/my-lora/checkpoint-11",
+ );
+ assert.equal(payload.resumed_from_job_id, "a".repeat(32));
+ assert.equal(payload.hf_token, "hf_x");
+});
+
+test("falls back to the run folder when the backend names no bundle", () => {
+ const payload = buildDiffusionResumePayload(
+ stoppedRun({ checkpoint_path: null }),
+ );
+ assert.equal(payload.resume_from_checkpoint, "/studio/outputs/my-lora");
+});
+
+test("refuses a run the backend says cannot resume, quoting its reason", () => {
+ assert.throws(
+ () =>
+ buildDiffusionResumePayload(
+ stoppedRun({
+ can_resume: false,
+ resume_blocked_reason: "The training images have changed since this checkpoint.",
+ }),
+ ),
+ /training images have changed/,
+ );
+});
+
+test("refuses a record with no output directory rather than guessing one", () => {
+ assert.throws(
+ () => buildDiffusionResumePayload(stoppedRun({ output_dir: null })),
+ /no checkpoint to continue from/,
+ );
+});
+
+test("refuses a record whose stored settings are incomplete", () => {
+ const run = stoppedRun();
+ delete (run.config as Record<string, unknown>).base_model;
+ assert.throws(() => buildDiffusionResumePayload(run), /settings are incomplete/);
+});
+
+test("the action label names the step it would continue from", () => {
+ assert.equal(resumeActionLabel({ checkpoint_step: 11 }), "Resume from step 11");
+ assert.equal(resumeActionLabel({ checkpoint_step: null }), "Resume training");
+});