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.

Studio: train image LoRAs with aspect-ratio buckets (#13218)

Daniel Han1e30dc7d9d95
diff --git a/studio/backend/core/training/diffusion_checkpoint.py b/studio/backend/core/training/diffusion_checkpoint.py
index 1ad643f2e92..56aad4e4a21 100644
--- a/studio/backend/core/training/diffusion_checkpoint.py
+++ b/studio/backend/core/training/diffusion_checkpoint.py
@@ -99,6 +99,8 @@ _IDENTITY_LABELS: tuple[tuple[str, str], ...] = (
("cache_variants", "cached crop variants"),
("center_crop", "centre cropping"),
("random_flip", "random flipping"),
+ # Buckets change canvases and batch order; a pre-field manifest trained square (_LEGACY_IDENTITY_DEFAULTS).
+ ("bucketing", "aspect ratio buckets"),
# TF32 versus strict fp32 continues the trajectory at a different numeric precision, and off is the documented
# strict-reproducibility mode.
("enable_tf32", "TF32 matmuls"),
@@ -139,6 +141,7 @@ _OPTIONAL_IDENTITY_FIELDS = frozenset(
"cache_variants",
"center_crop",
"random_flip",
+ "bucketing",
"enable_tf32",
"train_batch_size",
"gradient_accumulation_steps",
@@ -148,6 +151,8 @@ _OPTIONAL_IDENTITY_FIELDS = frozenset(
"base_precision_effective",
}
)
+# Bundle side only: an incoming None is the route's unresolved pre-trainer identity ("cannot tell").
+_LEGACY_IDENTITY_DEFAULTS: dict[str, str] = {"bucketing": "off"}
# What source_revision() returns when it cannot resolve a revision offline.
_UNRESOLVED_REVISION = "unresolved"
@@ -215,6 +220,7 @@ class CheckpointIdentity:
cache_variants: Optional[int] = None
center_crop: Optional[str] = None
random_flip: Optional[str] = None
+ bucketing: Optional[str] = None
enable_tf32: Optional[str] = None
train_batch_size: Optional[int] = None
gradient_accumulation_steps: Optional[int] = None
@@ -256,6 +262,7 @@ class CheckpointIdentity:
"cache_variants": self.cache_variants,
"center_crop": self.center_crop,
"random_flip": self.random_flip,
+ "bucketing": self.bucketing,
"enable_tf32": self.enable_tf32,
"train_batch_size": self.train_batch_size,
"gradient_accumulation_steps": self.gradient_accumulation_steps,
@@ -298,6 +305,7 @@ class CheckpointIdentity:
cache_variants = _optional_int(data.get("cache_variants")),
center_crop = _optional_str(data.get("center_crop")),
random_flip = _optional_str(data.get("random_flip")),
+ bucketing = _optional_str(data.get("bucketing")),
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")),
@@ -326,6 +334,8 @@ class CheckpointIdentity:
mine, theirs = self.as_dict(), other.as_dict()
for field, label in _IDENTITY_LABELS:
a, b = mine.get(field), theirs.get(field)
+ if a in (None, "") and field in _LEGACY_IDENTITY_DEFAULTS:
+ a = _LEGACY_IDENTITY_DEFAULTS[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 0.0-against-0.15 comparison that matters.
if field in _OPTIONAL_IDENTITY_FIELDS and (a in (None, "") or b in (None, "")):
@@ -582,6 +592,7 @@ def identity_for_config(
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)),
+ bucketing = _flag_key(getattr(cfg, "bucketing", 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),
@@ -1876,6 +1887,21 @@ def _assert_loadable(path: Path, manifest: dict[str, Any]) -> None:
) from error
+def recorded_bucketing(path_value: str) -> bool:
+ """Whether the resumed bundle trained bucketed (pre-field or unreadable: False; preflight_resume refuses)."""
+ try:
+ root = resolve_resume_dir(path_value)
+ except ResumeError:
+ return False
+ explicit = read_checkpoint(root) if checkpoint_step(root) >= 0 else None
+ candidates = [(root, explicit)] if explicit is not None else iter_valid_checkpoints(root)
+ for _path, manifest in candidates:
+ identity = manifest.get("identity")
+ if isinstance(identity, dict):
+ return _optional_str(identity.get("bucketing")) == "on"
+ return False
+
+
def preflight_resume(
path_value: str, *, identity: CheckpointIdentity, target_steps: int
) -> tuple[str, int]:
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index 11e92d3e7f3..1b100ce1d50 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -55,12 +55,15 @@ from core.training.diffusion_train_common import (
_plan_cache_variants,
_publish_to_lora_catalog,
_restore_perf_flags,
+ bucket_groups,
discover_image_caption_pairs,
has_functional_torchao,
flow_bf16_trainable,
native_bf16_supported_xpu,
PermutationBatchSampler,
+ plan_image_canvases,
repo_is_prequantized,
+ resolve_bucketing,
resolve_train_device,
resolve_train_steps,
restore_resume_state,
@@ -79,7 +82,9 @@ from core.training.diffusion_checkpoint import (
preflight_resume,
)
from core.training.diffusion_train_extras import (
+ BucketBatchSampler,
LoRAEMA,
+ cover_resize_dims,
PersistentConditioningCache,
save_ema_adapter,
)
@@ -1516,17 +1521,22 @@ def _assert_gated_access(base_model: str, hf_token: Optional[str]) -> None:
)
+def _canvas(resolution):
+ """(w, h) of the training canvas: a bucket tuple, or the legacy square ``resolution``."""
+ if isinstance(resolution, (tuple, list)):
+ return int(resolution[0]), int(resolution[1])
+ return int(resolution), int(resolution)
+
+
def _open_resized(path, resolution):
- """Open + EXIF-orient + short-side resize to ``resolution`` (same geometry as the SDXL loader).
- Returns the resized PIL image and its (rw, rh)."""
+ """Open + EXIF-orient + cover-resize to the canvas (same geometry as the SDXL loader; a square
+ canvas is the legacy short-side resize). Returns the resized PIL image and its (rw, rh)."""
from PIL import Image, ImageOps
from core.inference.mcp_images import flattened_rgb
img = flattened_rgb(ImageOps.exif_transpose(Image.open(path)), background = (255, 255, 255))
- w0, h0 = img.size
- scale = resolution / min(w0, h0)
- rw, rh = max(resolution, round(w0 * scale)), max(resolution, round(h0 * scale))
+ rw, rh = cover_resize_dims(*img.size, *_canvas(resolution))
return img.resize((rw, rh), Image.LANCZOS), rw, rh
@@ -1543,13 +1553,14 @@ def _load_pixel_tensor(path, resolution, center_crop, random_flip, rng):
without the SDXL time-ids (DiT families don't use them)."""
from PIL import Image
+ cw, ch = _canvas(resolution)
img, rw, rh = _open_resized(path, resolution)
if center_crop:
- left, top = (rw - resolution) // 2, (rh - resolution) // 2
+ left, top = (rw - cw) // 2, (rh - ch) // 2
else:
- left = rng.randint(0, max(0, rw - resolution))
- top = rng.randint(0, max(0, rh - resolution))
- img = img.crop((left, top, left + resolution, top + resolution))
+ left = rng.randint(0, max(0, rw - cw))
+ top = rng.randint(0, max(0, rh - ch))
+ img = img.crop((left, top, left + cw, top + ch))
if random_flip and rng.random() < 0.5:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
return _to_unit_tensor(img)
@@ -1562,13 +1573,14 @@ def _load_pixel_tensor_planned(path, resolution, center_crop, u_left, u_top, fli
center-crop run matches the uncached one bit-for-bit."""
from PIL import Image
+ cw, ch = _canvas(resolution)
img, rw, rh = _open_resized(path, resolution)
if center_crop:
- left, top = (rw - resolution) // 2, (rh - resolution) // 2
+ left, top = (rw - cw) // 2, (rh - ch) // 2
else:
- left = min(int(u_left * (rw - resolution + 1)), max(0, rw - resolution))
- top = min(int(u_top * (rh - resolution + 1)), max(0, rh - resolution))
- img = img.crop((left, top, left + resolution, top + resolution))
+ left = min(int(u_left * (rw - cw + 1)), max(0, rw - cw))
+ top = min(int(u_top * (rh - ch + 1)), max(0, rh - ch))
+ img = img.crop((left, top, left + cw, top + ch))
if flip:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
return _to_unit_tensor(img)
@@ -1585,6 +1597,7 @@ def _build_latent_cache(
check_stop,
pcache = None,
plan = None,
+ canvases = None,
):
"""Precompute the per-image latent posterior cache: for each planned crop/flip variant, encode
once and store the affine (A, B) pair on CPU (pinned when possible) in fp32. The stats stay
@@ -1621,15 +1634,18 @@ def _build_latent_cache(
for i, path in enumerate(image_paths):
variants = []
for u_left, u_top, flip in plan[i]:
- key = pcache.latent_key(path, (u_left, u_top, flip)) if pcache is not None else None
+ canvas = cfg.resolution if canvases is None else canvases[i]
+ key = (
+ pcache.latent_key(path, (u_left, u_top, flip), None if canvases is None else canvas)
+ if pcache is not None
+ else None
+ )
entry = pcache.get(key) if key is not None else None
if entry is not None:
a, b = entry
else:
px = (
- _load_pixel_tensor_planned(
- path, cfg.resolution, cfg.center_crop, u_left, u_top, flip
- )
+ _load_pixel_tensor_planned(path, canvas, cfg.center_crop, u_left, u_top, flip)
.unsqueeze(0)
.to(device)
)
@@ -1693,7 +1709,14 @@ def _encode_prompts_cached(spec, pipe, to_encode, device, pcache):
return [hits[cap] for cap in to_encode]
-def _load_warm_conditioning(pcache, image_paths, plan, to_encode, device):
+def _load_warm_conditioning(
+ pcache,
+ image_paths,
+ plan,
+ to_encode,
+ device,
+ canvases = None,
+):
"""Load the FULL conditioning set (caption embeds + latent posterior stats) from the persistent
cache. Returns (caption_embeds, latent_cache) on a complete hit, else (None, None) so the
caller takes the cold path -- any missing/corrupt entry, and also an in-memory holding that
@@ -1726,7 +1749,9 @@ def _load_warm_conditioning(pcache, image_paths, plan, to_encode, device):
for i, path in enumerate(image_paths):
variants = []
for variant in plan[i]:
- entry = pcache.get(pcache.latent_key(path, variant))
+ entry = pcache.get(
+ pcache.latent_key(path, variant, None if canvases is None else canvases[i])
+ )
if entry is None:
return None, None
a, b = entry
@@ -1844,7 +1869,7 @@ def run_dit_lora_training(
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()
+ cfg = resolve_bucketing(config.normalized())
spec = _SPECS.get(cfg.resolved_family)
if spec is None:
raise ValueError(f"No DiT trainer for family {cfg.resolved_family!r}")
@@ -1900,7 +1925,11 @@ 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)
+ cfg = replace(
+ cfg,
+ train_steps = resolve_train_steps(cfg, len(pairs), [p for p, _ in pairs]),
+ num_epochs = 0,
+ )
# Validate a resume against this run's identity BEFORE the multi-GB phased load, using the RESOLVED LoRA targets
# rather than the generic default the config carries.
identity = identity_for_config(
@@ -1999,8 +2028,14 @@ def _train_dit(
_emit(on_event, "warning", message = f"conditioning cache disabled: {exc}")
# The crop/flip variant plan is seed-deterministic, so persistent keys are stable across runs and the warm check
# can run before anything loads.
+ canvases, crop_room = plan_image_canvases(cfg, image_paths)
plan = _plan_cache_variants(
- len(image_paths), cfg.cache_variants, cfg.center_crop, cfg.random_flip, cfg.seed
+ len(image_paths),
+ cfg.cache_variants,
+ cfg.center_crop,
+ cfg.random_flip,
+ cfg.seed,
+ crop_room = crop_room,
)
pipe = None
@@ -2011,7 +2046,7 @@ def _train_dit(
latent_cache = None
if pcache is not None and use_cache:
caption_embeds, latent_cache = _load_warm_conditioning(
- pcache, image_paths, plan, to_encode, device
+ pcache, image_paths, plan, to_encode, device, canvases
)
if caption_embeds is not None:
_emit(
@@ -2046,6 +2081,7 @@ def _train_dit(
_check_stop,
pcache = pcache,
plan = plan,
+ canvases = canvases,
)
if latent_cache is LATENT_CACHE_OVER_BUDGET:
# The estimated cache exceeded the host-memory budget; keep the VAE resident and fall through to the
@@ -2168,8 +2204,12 @@ def _train_dit(
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.
- index_sampler = PermutationBatchSampler(n_images, rng)
+ # run covers the whole dataset. Bucketed runs draw each batch from one bucket so its latents stack into one shape.
+ index_sampler = (
+ PermutationBatchSampler(n_images, rng)
+ if canvases is None
+ else BucketBatchSampler(bucket_groups(canvases), 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.
@@ -2250,6 +2290,8 @@ def _train_dit(
step_loss = 0.0
for _ in range(cfg.gradient_accumulation_steps):
idxs = index_sampler.next_batch(batch_size)
+ if canvases is not None:
+ idxs = idxs[1]
if latent_cache is not None:
latents = _sample_cached_latents(
latent_cache, idxs, variant_rng, device, weight_dtype
@@ -2258,7 +2300,11 @@ def _train_dit(
px = torch.stack(
[
_load_pixel_tensor(
- image_paths[i], cfg.resolution, cfg.center_crop, cfg.random_flip, rng
+ image_paths[i],
+ cfg.resolution if canvases is None else canvases[i],
+ cfg.center_crop,
+ cfg.random_flip,
+ rng,
)
for i in idxs
]
diff --git a/studio/backend/core/training/diffusion_lora_trainer.py b/studio/backend/core/training/diffusion_lora_trainer.py
index 5f4f3a37d16..edb27e4980b 100644
--- a/studio/backend/core/training/diffusion_lora_trainer.py
+++ b/studio/backend/core/training/diffusion_lora_trainer.py
@@ -60,13 +60,17 @@ from core.training.diffusion_train_common import ( # noqa: F401
_plan_cache_variants,
_publish_to_lora_catalog,
_restore_perf_flags,
+ bucket_groups,
discover_image_caption_pairs,
get_trainer,
PermutationBatchSampler,
+ plan_image_canvases,
+ resolve_bucketing,
resolve_train_steps,
restore_resume_state,
write_resume_checkpoint,
)
+from core.training.diffusion_train_extras import BucketBatchSampler, cover_resize_dims
from core.training.diffusion_checkpoint import (
clear_own_checkpoints,
discard_preexisting_checkpoints,
@@ -88,70 +92,74 @@ def compute_sdxl_add_time_ids(resolution: int) -> tuple[int, int, int, int, int,
return (resolution, resolution, 0, 0, resolution, resolution)
-def _load_image_tensor(
- path: str, resolution: int, center_crop: bool, random_flip: bool, rng: random.Random
+def _canvas(resolution: Any) -> tuple[int, int]:
+ """(w, h) of the training canvas: a bucket tuple, or the legacy square ``resolution``."""
+ if isinstance(resolution, (tuple, list)):
+ return int(resolution[0]), int(resolution[1])
+ return int(resolution), int(resolution)
+
+
+def _crop_to_canvas(
+ path: str, resolution: Any, center_crop: bool, pick: Any, flip: Any
) -> tuple[Any, tuple[int, int, int, int, int, int]]:
- """CxHxW pixels in [-1, 1] with SDXL time ids for the EXIF-oriented crop."""
+ """Cover-resize to the canvas, crop at ``pick(range_x, range_y)``, optionally mirror. Returns
+ CxHxW pixels in [-1, 1] and SDXL time ids (original_h, original_w, crop_top, crop_left,
+ target_h, target_w); a square canvas reproduces the legacy short-side geometry exactly."""
import numpy as np
import torch
from PIL import Image, ImageOps
from core.inference.mcp_images import flattened_rgb
+ cw, ch = _canvas(resolution)
# apply EXIF orientation before geometry so rotated photos train upright.
img = flattened_rgb(ImageOps.exif_transpose(Image.open(path)), background = (255, 255, 255))
original_w, original_h = img.size
- scale = resolution / min(original_w, original_h)
- resized_w = max(resolution, round(original_w * scale))
- resized_h = max(resolution, round(original_h * scale))
+ resized_w, resized_h = cover_resize_dims(original_w, original_h, cw, ch)
img = img.resize((resized_w, resized_h), Image.LANCZOS)
if center_crop:
- left, top = (resized_w - resolution) // 2, (resized_h - resolution) // 2
+ left, top = (resized_w - cw) // 2, (resized_h - ch) // 2
else:
- left = rng.randint(0, max(0, resized_w - resolution))
- top = rng.randint(0, max(0, resized_h - resolution))
- img = img.crop((left, top, left + resolution, top + resolution))
+ left, top = pick(resized_w - cw, resized_h - ch)
+ img = img.crop((left, top, left + cw, top + ch))
crop_left = left
- if random_flip and rng.random() < 0.5:
+ if flip():
img = img.transpose(Image.FLIP_LEFT_RIGHT)
# mirror the crop origin after a flip to match diffusers.
- crop_left = max(0, resized_w - resolution - left)
+ crop_left = max(0, resized_w - cw - left)
arr = np.asarray(img, dtype = np.float32) / 255.0
tensor = torch.from_numpy(arr).permute(2, 0, 1) * 2.0 - 1.0
- time_ids = (original_h, original_w, top, crop_left, resolution, resolution)
+ time_ids = (original_h, original_w, top, crop_left, ch, cw)
return tensor, time_ids
-def _load_image_tensor_planned(
- path: str, resolution: int, center_crop: bool, u_left: float, u_top: float, flip: bool
+def _load_image_tensor(
+ path: str, resolution: Any, center_crop: bool, random_flip: bool, rng: random.Random
) -> tuple[Any, tuple[int, int, int, int, int, int]]:
- """cache loader preserving ``_load_image_tensor`` crop, flip, and legacy center semantics."""
- import numpy as np
- import torch
- from PIL import Image, ImageOps
+ """CxHxW pixels in [-1, 1] with SDXL time ids for the EXIF-oriented crop."""
+ return _crop_to_canvas(
+ path,
+ resolution,
+ center_crop,
+ lambda rx, ry: (rng.randint(0, max(0, rx)), rng.randint(0, max(0, ry))),
+ lambda: random_flip and rng.random() < 0.5,
+ )
- from core.inference.mcp_images import flattened_rgb
- img = flattened_rgb(ImageOps.exif_transpose(Image.open(path)), background = (255, 255, 255))
- original_w, original_h = img.size
- scale = resolution / min(original_w, original_h)
- resized_w = max(resolution, round(original_w * scale))
- resized_h = max(resolution, round(original_h * scale))
- img = img.resize((resized_w, resized_h), Image.LANCZOS)
- if center_crop:
- left, top = (resized_w - resolution) // 2, (resized_h - resolution) // 2
- else:
- left = min(int(u_left * (resized_w - resolution + 1)), max(0, resized_w - resolution))
- top = min(int(u_top * (resized_h - resolution + 1)), max(0, resized_h - resolution))
- img = img.crop((left, top, left + resolution, top + resolution))
- crop_left = left
- if flip:
- img = img.transpose(Image.FLIP_LEFT_RIGHT)
- crop_left = max(0, resized_w - resolution - left)
- arr = np.asarray(img, dtype = np.float32) / 255.0
- tensor = torch.from_numpy(arr).permute(2, 0, 1) * 2.0 - 1.0
- time_ids = (original_h, original_w, top, crop_left, resolution, resolution)
- return tensor, time_ids
+def _load_image_tensor_planned(
+ path: str, resolution: Any, center_crop: bool, u_left: float, u_top: float, flip: bool
+) -> tuple[Any, tuple[int, int, int, int, int, int]]:
+ """cache loader preserving ``_load_image_tensor`` crop, flip, and legacy center semantics."""
+ return _crop_to_canvas(
+ path,
+ resolution,
+ center_crop,
+ lambda rx, ry: (
+ min(int(u_left * (rx + 1)), max(0, rx)),
+ min(int(u_top * (ry + 1)), max(0, ry)),
+ ),
+ lambda: flip,
+ )
def _encode_sdxl_prompts(
@@ -182,7 +190,16 @@ def _encode_sdxl_prompts(
def _build_sdxl_latent_cache(
- vae, vae_scale, image_paths, cfg, device, weight_dtype, on_event, check_stop
+ vae,
+ vae_scale,
+ image_paths,
+ cfg,
+ device,
+ weight_dtype,
+ on_event,
+ check_stop,
+ canvases = None,
+ plan = None,
):
"""Precompute the per-image latent posterior cache: for each planned crop/flip variant,
encode once and store ``(A, B, time_ids)`` on CPU in fp32. ``A`` and ``B`` are the affine
@@ -192,12 +209,14 @@ def _build_sdxl_latent_cache(
per-step sample happens in fp32 and only the RESULT is cast to weight_dtype, matching the
in-loop path (encode fp32 -> sample fp32 -> scale -> .to(weight_dtype)); fp32 doubles the
cache RAM over bf16 but the cache is tiny (a handful of latents per image). Returns None if
- the build was interrupted by a stop request. ``vae_scale`` is read before the VAE is freed."""
+ the build was interrupted by a stop request. ``vae_scale`` is read before the VAE is freed.
+ ``canvases`` holds each image's bucket for a bucketed run (None: the square resolution)."""
import torch
- plan = _plan_cache_variants(
- len(image_paths), cfg.cache_variants, cfg.center_crop, cfg.random_flip, cfg.seed
- )
+ if plan is None:
+ plan = _plan_cache_variants(
+ len(image_paths), cfg.cache_variants, cfg.center_crop, cfg.random_flip, cfg.seed
+ )
def _hold(t):
t = t.to(torch.float32).cpu()
@@ -217,7 +236,12 @@ def _build_sdxl_latent_cache(
variants = []
for u_left, u_top, flip in plan[i]:
tensor, time_ids = _load_image_tensor_planned(
- path, cfg.resolution, cfg.center_crop, u_left, u_top, flip
+ path,
+ cfg.resolution if canvases is None else canvases[i],
+ cfg.center_crop,
+ u_left,
+ u_top,
+ flip,
)
pixel_values = tensor.unsqueeze(0).to(device, dtype = torch.float32)
with torch.no_grad():
@@ -318,7 +342,7 @@ def run_diffusion_lora_training(
except Exception: # noqa: BLE001 - never let log tidying stop a training run
pass
- cfg = config.normalized()
+ cfg = resolve_bucketing(config.normalized())
rng = random.Random(cfg.seed)
torch.manual_seed(cfg.seed)
@@ -355,7 +379,11 @@ 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)
+ cfg = replace(
+ cfg,
+ train_steps = resolve_train_steps(cfg, len(pairs), [p for p, _ in pairs]),
+ num_epochs = 0,
+ )
# Validate a resume request against this run's identity BEFORE the multi-GB base model load, so a
# mismatch fails in seconds instead of after the download.
identity = identity_for_config(cfg, dataset_pairs = pairs)
@@ -467,6 +495,7 @@ def run_diffusion_lora_training(
) not in ("1", "true")
# Over the host-memory budget; keep the VAE resident and encode in-loop.
latent_cache = None
+ canvases, crop_room = plan_image_canvases(cfg, [p for p, _ in pairs])
if use_cache:
latent_cache = _build_sdxl_latent_cache(
vae,
@@ -477,6 +506,15 @@ def run_diffusion_lora_training(
weight_dtype,
on_event,
_check_stop,
+ canvases = canvases,
+ plan = _plan_cache_variants(
+ len(pairs),
+ cfg.cache_variants,
+ cfg.center_crop,
+ cfg.random_flip,
+ cfg.seed,
+ crop_room = crop_room,
+ ),
)
if latent_cache is LATENT_CACHE_OVER_BUDGET:
latent_cache = None
@@ -517,12 +555,19 @@ def run_diffusion_lora_training(
# 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)
+ # Bucketed runs draw each batch from one bucket so its latents stack into one shape.
+ index_sampler = (
+ PermutationBatchSampler(len(pairs), rng)
+ if canvases is None
+ else BucketBatchSampler(bucket_groups(canvases), rng)
+ )
def _next_batch() -> tuple[list[int], list[str], list[str]]:
# Draw the full configured batch, not min(batch, n): the sampler refills across cycles so a small
# dataset still yields that many indices.
idx = index_sampler.next_batch(cfg.train_batch_size)
+ if canvases is not None:
+ idx = idx[1]
chosen = [pairs[i] for i in idx]
return idx, [c[0] for c in chosen], [c[1] for c in chosen]
@@ -598,8 +643,14 @@ def run_diffusion_lora_training(
)
else:
loaded = [
- _load_image_tensor(p, cfg.resolution, cfg.center_crop, cfg.random_flip, rng)
- for p in img_paths
+ _load_image_tensor(
+ p,
+ cfg.resolution if canvases is None else canvases[i],
+ cfg.center_crop,
+ cfg.random_flip,
+ rng,
+ )
+ for i, p in zip(idx, img_paths)
]
pixel_values = torch.stack([t for t, _ in loaded]).to(
device, dtype = torch.float32
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index 98fe14cce23..f116cb76825 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -962,6 +962,7 @@ def family_train_infos() -> list[dict[str, Any]]:
# save_steps is REFUSED for a checkpointless family, not ignored, so a panel that keeps offering
# "Checkpoint every" turns a nonzero value into a rejected Start with no way to see why.
"supports_checkpoints": name not in CHECKPOINTLESS_FAMILIES,
+ "supports_bucketing": name not in UNBUCKETED_FAMILIES,
# A batch > 1 is REFUSED for a family whose forward covers one packed sequence, so leaving the control
# unrestricted turns a reasonable 2 into a rejected Start with nothing to say why.
"max_train_batch_size": 1 if name in SINGLE_SEQUENCE_FAMILIES else None,
@@ -1010,6 +1011,7 @@ class DiffusionLoraConfig:
center_crop: bool = False
# Off by default: flipping mirrors text, logos and one-sided features in half the samples.
random_flip: bool = False
+ bucketing: Optional[bool] = None
caption_column: str = "text"
adapter_name: str = "default"
hf_token: Optional[str] = None
@@ -1278,6 +1280,11 @@ class DiffusionLoraConfig:
# trainer resolve different captions from a metadata.jsonl and their fingerprints disagree, so an accepted
# resume is refused in the child.
caption_column = str(self.caption_column or "").strip() or "text"
+ bucketing = None if self.bucketing is None else _coerce_bool(self.bucketing)
+ if resolved_family in UNBUCKETED_FAMILIES:
+ bucketing = False
+ elif bucketing is None and not resume_from_checkpoint:
+ bucketing = True
return replace(
self,
learning_rate = learning_rate,
@@ -1290,6 +1297,7 @@ class DiffusionLoraConfig:
caption_column = caption_column,
num_epochs = int(self.num_epochs),
cache_variants = int(self.cache_variants),
+ bucketing = bucketing,
save_steps = save_steps,
save_total_limit = save_total_limit,
resume_from_checkpoint = resume_from_checkpoint,
@@ -1304,14 +1312,22 @@ class DiffusionLoraConfig:
)
-def resolve_train_steps(cfg: "DiffusionLoraConfig", n_images: int) -> int:
+def resolve_train_steps(
+ cfg: "DiffusionLoraConfig",
+ n_images: int,
+ image_paths: Optional[list[str]] = None,
+) -> int:
"""The effective optimizer-step count for a run. When ``cfg.num_epochs`` is set (> 0), one epoch
- is one full pass over the dataset in optimizer steps -- ceil(N / (batch x grad_accum)) -- so
- the run is ``num_epochs`` such passes, capped at 100000. With ``num_epochs == 0`` the
- explicit ``cfg.train_steps`` is used unchanged."""
+ is one full pass over the dataset in optimizer steps -- ceil(ceil(N / batch) / grad_accum) --
+ so the run is ``num_epochs`` such passes, capped at 100000. Bucketed runs (``image_paths``)
+ count batches per bucket: a bucket pads its last batch within itself. With ``num_epochs == 0`` the explicit ``cfg.train_steps`` is used unchanged."""
if cfg.num_epochs > 0:
- per_step = max(1, cfg.train_batch_size * cfg.gradient_accumulation_steps)
- steps_per_epoch = max(1, math.ceil(n_images / per_step))
+ batch = max(1, cfg.train_batch_size)
+ batches = math.ceil(n_images / batch)
+ canvases = plan_image_canvases(cfg, image_paths)[0] if image_paths is not None else None
+ if canvases is not None:
+ batches = sum(math.ceil(len(g) / batch) for g in bucket_groups(canvases).values())
+ steps_per_epoch = max(1, math.ceil(batches / max(1, cfg.gradient_accumulation_steps)))
return min(100000, cfg.num_epochs * steps_per_epoch)
return cfg.train_steps
@@ -1503,6 +1519,7 @@ def discover_image_caption_pairs(
# The shared DiffusionLoraConfig carries save_steps / resume_from_checkpoint for every family, so a loop that
# implements neither has to say so rather than ignore them.
CHECKPOINTLESS_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
+UNBUCKETED_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
# The batch axis is a pure replication axis for these: the layout, the rotary grid and the row timesteps are set by
# one clip's geometry and its caption's length.
@@ -1583,6 +1600,7 @@ _H3_FIXED_RECIPE: dict[str, Any] = {
"snr_gamma": None,
"cache_latents": True,
"cache_variants": 1,
+ "bucketing": False,
}
@@ -1640,20 +1658,29 @@ def _emit(on_event: Optional[EventCb], type_: str, **kw: Any) -> None:
def _plan_cache_variants(
- num_images: int, cache_variants: int, center_crop: bool, random_flip: bool, seed: int
+ num_images: int,
+ cache_variants: int,
+ center_crop: bool,
+ random_flip: bool,
+ seed: int,
+ crop_room: Optional[list[tuple[int, int]]] = None,
) -> list[list[tuple[float, float, bool]]]:
"""Seed-deterministic crop/flip plan for the latent cache: per image, up to ``cache_variants``
draws of (u_left, u_top, flip) with the crop as unit fractions the loader maps onto its
integer crop range. Uses its own rng stream so the training loop's draws are untouched.
Center-crop / no-flip collapse duplicate variants, so callers encode each distinct variant
- exactly once. Pure (no torch) for CPU unit tests."""
+ exactly once. ``crop_room``: per-image (x, y) crop slack; an axis with none pins its fraction.
+ Pure (no torch) for CPU unit tests."""
crop_rng = random.Random(seed)
plan: list[list[tuple[float, float, bool]]] = []
- for _ in range(max(0, num_images)):
+ for i in range(max(0, num_images)):
variants: list[tuple[float, float, bool]] = []
for _ in range(max(1, cache_variants)):
u_left, u_top = crop_rng.random(), crop_rng.random()
flip = bool(random_flip and crop_rng.random() < 0.5)
+ if crop_room is not None:
+ u_left = u_left if crop_room[i][0] > 0 else 0.5
+ u_top = u_top if crop_room[i][1] > 0 else 0.5
if center_crop:
u_left = u_top = 0.5 # loader ignores the fractions for a center crop
key = (u_left, u_top, flip)
@@ -1663,6 +1690,51 @@ def _plan_cache_variants(
return plan
+def resolve_bucketing(cfg: "DiffusionLoraConfig") -> "DiffusionLoraConfig":
+ """Settle an unset ``bucketing``: the bundle's recorded value on a resume (pre-field runs stay square)."""
+ if cfg.bucketing is not None:
+ return cfg
+ if not cfg.resume_from_checkpoint:
+ return replace(cfg, bucketing = cfg.resolved_family not in UNBUCKETED_FAMILIES)
+ from core.training.diffusion_checkpoint import recorded_bucketing
+
+ return replace(cfg, bucketing = recorded_bucketing(cfg.resume_from_checkpoint))
+
+
+def plan_image_canvases(
+ cfg: "DiffusionLoraConfig", image_paths: list[str]
+) -> tuple[Optional[list[tuple[int, int]]], Optional[list[tuple[int, int]]]]:
+ """Per-image (w, h) canvas and (x, y) crop slack, or (None, None) when unbucketed. Headers only."""
+ if not cfg.bucketing:
+ return None, None
+ from core.training.diffusion_train_extras import (
+ bucket_resolutions,
+ cover_resize_dims,
+ nearest_bucket,
+ oriented_image_size,
+ )
+
+ choices = bucket_resolutions(cfg.resolution)
+ canvases, room = [], []
+ for path in image_paths:
+ w0, h0 = oriented_image_size(path)
+ bw, bh = nearest_bucket(w0, h0, choices)
+ rw, rh = cover_resize_dims(w0, h0, bw, bh)
+ canvases.append((bw, bh))
+ room.append((rw - bw, rh - bh))
+ # All-square datasets keep the unbucketed sampler and cache keys, so existing caches stay warm.
+ if all(c == (cfg.resolution, cfg.resolution) for c in canvases):
+ return None, None
+ return canvases, room
+
+
+def bucket_groups(canvases: list[tuple[int, int]]) -> dict[tuple[int, int], list[int]]:
+ groups: dict[tuple[int, int], list[int]] = {}
+ for i, shape in enumerate(canvases):
+ groups.setdefault(shape, []).append(i)
+ return groups
+
+
# Two fp32 posterior tensors per crop/flip variant per image, so a few thousand images can exhaust pinned RAM; over
# budget it falls back to per-step VAE encoding.
_LATENT_CACHE_BUDGET_BYTES = 4 * 1024**3 # 4 GiB
@@ -2243,6 +2315,8 @@ def _config_from_dict(config: dict) -> DiffusionLoraConfig:
kwargs["gradient_checkpointing"] = _coerce_gradient_checkpointing(
kwargs["gradient_checkpointing"]
)
+ if kwargs.get("bucketing") is not None:
+ kwargs["bucketing"] = _coerce_bool(kwargs["bucketing"])
for flag in ("cache_latents", "enable_tf32"):
if flag in kwargs:
kwargs[flag] = _coerce_bool(kwargs[flag])
diff --git a/studio/backend/core/training/diffusion_train_extras.py b/studio/backend/core/training/diffusion_train_extras.py
index 727cf570c28..cfaf73bbaf0 100644
--- a/studio/backend/core/training/diffusion_train_extras.py
+++ b/studio/backend/core/training/diffusion_train_extras.py
@@ -391,8 +391,7 @@ class PersistentConditioningCache:
return None
-# Buckets snap to 64 pixels: the DiT families divide by 8 in the VAE and 2 again in latent patching, and regional
-# torch.compile prefers few distinct shapes.
+# 64: a multiple of every family's latent grid (16 DiTs, 32 LTX-2, SDXL U-Net) and few compiled shapes.
BUCKET_DIVISOR = 64
@@ -401,6 +400,33 @@ BUCKET_DIVISOR = 64
MAX_BUCKET_RATIO = 2.0
+def bucket_resolutions(
+ resolution: int,
+ divisor: int = BUCKET_DIVISOR,
+ max_ratio: float = MAX_BUCKET_RATIO,
+) -> list[tuple[int, int]]:
+ """The exact legacy square plus kohya BucketManager buckets (tallest grid height within resolution**2)."""
+ base = int(resolution)
+ area = base * base
+ out = {(base, base)}
+ w = divisor
+ while w * w <= area * max_ratio:
+ h = (area // w) // divisor * divisor
+ if h >= divisor and 1.0 / max_ratio <= w / h <= max_ratio:
+ out.add((w, h))
+ out.add((h, w))
+ w += divisor
+ return sorted(out)
+
+
+def nearest_bucket(width: int, height: int, buckets: list[tuple[int, int]]) -> tuple[int, int]:
+ """Closest aspect in log space; ties: larger area, then sorted order (deterministic)."""
+ if width <= 0 or height <= 0:
+ raise ValueError("image dimensions must be positive")
+ r = math.log(width / height)
+ return min(buckets, key = lambda b: (abs(math.log(b[0] / b[1]) - r), -b[0] * b[1], b))
+
+
def compute_bucket(
width: int,
height: int,
@@ -408,18 +434,8 @@ def compute_bucket(
divisor: int = BUCKET_DIVISOR,
max_ratio: float = MAX_BUCKET_RATIO,
) -> tuple[int, int]:
- """The (bucket_w, bucket_h) for an image: preserve aspect (clamped to
- ``max_ratio``), keep area ~= base_resolution**2, snap both dims to
- ``divisor``. A square input maps exactly to (base, base)."""
- if width <= 0 or height <= 0:
- raise ValueError("image dimensions must be positive")
- ratio = width / height
- ratio = max(1.0 / max_ratio, min(max_ratio, ratio))
- area = float(base_resolution) * float(base_resolution)
- bw = math.sqrt(area * ratio)
- bh = bw / ratio
- snap = lambda v: max(divisor, int(round(v / divisor)) * divisor) # noqa: E731
- return snap(bw), snap(bh)
+ """The (bucket_w, bucket_h) for an image of ``width`` x ``height``."""
+ return nearest_bucket(width, height, bucket_resolutions(base_resolution, divisor, max_ratio))
def assign_buckets(
@@ -428,42 +444,93 @@ def assign_buckets(
divisor: int = BUCKET_DIVISOR,
max_ratio: float = MAX_BUCKET_RATIO,
) -> dict[tuple[int, int], list[int]]:
+ choices = bucket_resolutions(base_resolution, divisor, max_ratio)
buckets: dict[tuple[int, int], list[int]] = {}
for i, (w, h) in enumerate(sizes):
- buckets.setdefault(compute_bucket(w, h, base_resolution, divisor, max_ratio), []).append(i)
+ buckets.setdefault(nearest_bucket(w, h, choices), []).append(i)
return buckets
+def cover_resize_dims(width: int, height: int, canvas_w: int, canvas_h: int) -> tuple[int, int]:
+ """Smallest uniform scale covering the canvas (square canvas = legacy short-side resize)."""
+ scale = max(canvas_w / width, canvas_h / height)
+ return max(canvas_w, round(width * scale)), max(canvas_h, round(height * scale))
+
+
+def oriented_image_size(path: str) -> tuple[int, int]:
+ """(width, height) after EXIF orientation, from the header only (no pixel decode)."""
+ from PIL import Image
+
+ with Image.open(path) as im:
+ w, h = im.size
+ try:
+ orientation = im.getexif().get(0x0112, 1)
+ except Exception: # noqa: BLE001 -- unreadable EXIF is treated as upright, like exif_transpose
+ orientation = 1
+ return (h, w) if orientation in (5, 6, 7, 8) else (w, h)
+
+
class BucketBatchSampler:
"""Batch indices so every batch comes from ONE bucket (one latent shape).
- Within each bucket the draw is a reshuffled permutation (each cycle visits
- every image once, like the trainers' PermutationBatchSampler); the bucket
- for each batch is drawn weighted by bucket size so coverage stays uniform
- across the dataset. Seed-deterministic via the caller's ``rng``. A batch
- never mixes buckets; a bucket smaller than the batch size wraps within
- itself so the batch shape stays fixed."""
+ Epoch-style like PermutationBatchSampler: every image once per cycle; a bucket's last partial
+ batch wraps within itself so shapes stay fixed."""
def __init__(self, buckets: dict[tuple[int, int], list[int]], rng: random.Random):
if not buckets or not any(buckets.values()):
raise ValueError("BucketBatchSampler needs at least one bucketed item")
self._rng = rng
- self._shapes = sorted(buckets.keys())
+ self._shapes = sorted(s for s in buckets if buckets[s])
self._items = {s: list(buckets[s]) for s in self._shapes}
- self._weights = [len(self._items[s]) for s in self._shapes]
- self._order: dict[tuple[int, int], list[int]] = {s: [] for s in self._shapes}
- self._pos = {s: 0 for s in self._shapes}
+ self._batches: list[tuple[tuple[int, int], list[int]]] = []
+ self._pos = 0
+
+ def _refill(self, k: int) -> None:
+ batches: list[tuple[tuple[int, int], list[int]]] = []
+ for shape in self._shapes:
+ order = list(self._items[shape])
+ self._rng.shuffle(order)
+ count = -(-len(order) // k)
+ stream = (order * (-(-count * k // len(order))))[: count * k]
+ batches.extend((shape, stream[b * k : (b + 1) * k]) for b in range(count))
+ self._rng.shuffle(batches)
+ self._batches, self._pos = batches, 0
def next_batch(self, k: int) -> tuple[tuple[int, int], list[int]]:
- shape = self._rng.choices(self._shapes, weights = self._weights, k = 1)[0]
- out: list[int] = []
- while len(out) < k:
- order, pos = self._order[shape], self._pos[shape]
- if pos >= len(order):
- order = list(self._items[shape])
- self._rng.shuffle(order)
- self._order[shape], pos = order, 0
- take = min(k - len(out), len(order) - pos)
- out.extend(order[pos : pos + take])
- self._pos[shape] = pos + take
- return shape, out
+ if self._pos >= len(self._batches) or len(self._batches[self._pos][1]) != k:
+ self._refill(k)
+ shape, idxs = self._batches[self._pos]
+ self._pos += 1
+ return shape, list(idxs)
+
+ def _bucket_key(self) -> list[list[Any]]:
+ return [[s[0], s[1], list(self._items[s])] for s in self._shapes]
+
+ def state_dict(self) -> dict[str, Any]:
+ return {
+ "kind": "bucket",
+ "buckets": self._bucket_key(),
+ "batches": [[s[0], s[1], list(i)] for s, i in self._batches],
+ "pos": int(self._pos),
+ }
+
+ def load_state_dict(self, state: Optional[dict[str, Any]]) -> bool:
+ """False (never a silent fresh cycle) unless the state matches this exact bucket assignment."""
+ if not isinstance(state, dict) or state.get("kind") != "bucket":
+ return False
+ try:
+ if [[int(w), int(h), [int(i) for i in idx]] for w, h, idx in state["buckets"]] != (
+ self._bucket_key()
+ ):
+ return False
+ batches = [((int(w), int(h)), [int(i) for i in idx]) for w, h, idx in state["batches"]]
+ pos = int(state.get("pos") or 0)
+ except (KeyError, TypeError, ValueError):
+ return False
+ for shape, idxs in batches:
+ if shape not in self._items or not set(idxs) <= set(self._items[shape]):
+ return False
+ if not 0 <= pos <= len(batches):
+ return False
+ self._batches, self._pos = batches, pos
+ return True
diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.py
index d0c5cdf8a26..e3631c1169d 100644
--- a/studio/backend/core/training/diffusion_training_service.py
+++ b/studio/backend/core/training/diffusion_training_service.py
@@ -710,6 +710,9 @@ class DiffusionTrainingService:
self._config = {
k: v for k, v in dict(config).items() if k not in {"hf_token", "_job_account"}
}
+ # A resume's unset bucketing stays unset; the trainer adopts the bundle's.
+ if normalized_cfg.bucketing is not None:
+ self._config["bucketing"] = normalized_cfg.bucketing
self._config.update(train_recipe_overrides(normalized_cfg))
self._pump = account_thread(
target = self._pump_loop, args = (event_queue, self._proc), daemon = True
diff --git a/studio/backend/models/training.py b/studio/backend/models/training.py
index 87d36344a05..45efe21b77b 100644
--- a/studio/backend/models/training.py
+++ b/studio/backend/models/training.py
@@ -978,6 +978,15 @@ class DiffusionTrainingStartRequest(BaseModel):
random_flip: bool = Field(
False, description = "Randomly mirror training images left-right (augmentation)"
)
+ bucketing: Optional[bool] = Field(
+ None,
+ description = (
+ "Aspect-ratio buckets: train each image on the same-area canvas nearest its aspect "
+ "ratio instead of a square crop. null means on for a new run and, on a resume, what "
+ "the checkpoint recorded (square for a run from before buckets existed). MiniMax-H3 "
+ "always trains unbucketed."
+ ),
+ )
caption_column: str = Field("text")
hf_token: Optional[str] = Field(None)
cache_latents: bool = Field(
@@ -1228,6 +1237,7 @@ class DiffusionTrainableFamily(BaseModel):
# control: save_steps is refused, not ignored, for a checkpointless family, so offering the control means
# offering a value that rejects Start; defaults True so an older backend's payload keeps it.
supports_checkpoints: bool = True
+ supports_bucketing: bool = True
# 1 for a family whose forward covers one packed sequence: a value above the cap is refused rather
# than clamped, and declaring it here is what stops Pydantic dropping it from the response.
max_train_batch_size: Optional[int] = None
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 48de8e32b1f..b24f9e05b1f 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -3405,6 +3405,14 @@ def _resolve_diffusion_data_dir(raw: str) -> Path:
return resolved
+def _diffusion_resume_target_steps(normalized_cfg: Any, pairs: list) -> int:
+ """The trainer's step target (bucketing and per-bucket batches settled alike); a smaller one refuses late checkpoints."""
+ from core.training import diffusion_train_common as _dtc
+
+ cfg = _dtc.resolve_bucketing(normalized_cfg)
+ return _dtc.resolve_train_steps(cfg, len(pairs), [p for p, _ in pairs])
+
+
def _preflight_diffusion_resume(
config: dict,
identity: Any,
@@ -3675,11 +3683,14 @@ async def start_diffusion_training(
raise HTTPException(status_code = 400, detail = str(e))
if resuming:
try:
+ target_steps = await asyncio.to_thread(
+ _diffusion_resume_target_steps, normalized_cfg, pairs
+ )
await asyncio.to_thread(
_preflight_diffusion_resume,
config,
resume_identity.with_dataset(dataset_fingerprint(pairs)),
- _dtc.resolve_train_steps(normalized_cfg, len(pairs)),
+ target_steps,
)
except ResumeError as e:
raise HTTPException(status_code = 400, detail = str(e))
diff --git a/studio/backend/tests/test_diffusion_bucketing.py b/studio/backend/tests/test_diffusion_bucketing.py
new file mode 100644
index 00000000000..b77d3f0c3a9
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_bucketing.py
@@ -0,0 +1,480 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Aspect-ratio bucketing for the image LoRA trainers: the bucket set, assignment, the
+one-bucket-per-batch sampler and its resume state, the per-bucket crop geometry and SDXL time
+ids, every DiT family's packing on a non-square latent, the config default, and resume identity.
+
+CPU-only."""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+import math
+import random
+from types import SimpleNamespace
+
+import pytest
+import torch
+from PIL import Image
+
+import core.training.diffusion_checkpoint as dc
+from core.training import diffusion_dit_trainer as dit
+from core.training.diffusion_lora_trainer import _load_image_tensor, _load_image_tensor_planned
+from core.training.diffusion_train_common import (
+ DiffusionLoraConfig,
+ _config_from_dict,
+ _plan_cache_variants,
+ bucket_groups,
+ plan_image_canvases,
+ resolve_bucketing,
+ resolve_train_steps,
+ train_recipe_overrides,
+)
+from core.training.diffusion_train_extras import (
+ BUCKET_DIVISOR,
+ BucketBatchSampler,
+ bucket_resolutions,
+ cover_resize_dims,
+ nearest_bucket,
+ oriented_image_size,
+)
+
+
+def _img(
+ path,
+ w,
+ h,
+ color = (200, 30, 30),
+ exif_orientation = None,
+):
+ im = Image.new("RGB", (w, h), color)
+ if exif_orientation is not None:
+ exif = Image.Exif()
+ exif[0x0112] = exif_orientation
+ im.save(path, exif = exif)
+ else:
+ im.save(path)
+ return str(path)
+
+
[email protected]("res", [512, 768, 1024])
+def test_bucket_set_is_bounded_same_area_and_on_grid(res):
+ buckets = bucket_resolutions(res)
+ assert (res, res) in buckets
+ for w, h in buckets:
+ if (w, h) != (res, res):
+ assert w % BUCKET_DIVISOR == 0 and h % BUCKET_DIVISOR == 0
+ assert w * h <= res * res
+ assert w * h >= 0.8 * res * res
+ assert 0.5 <= w / h <= 2.0
+ assert (h, w) in buckets
+ assert len(buckets) <= 13
+
+
+def test_bucket_set_at_512_and_1024():
+ assert bucket_resolutions(512) == [(384, 640), (448, 576), (512, 512), (576, 448), (640, 384)]
+ assert {(1216, 832), (832, 1216), (1152, 896), (1344, 768)} <= set(bucket_resolutions(1024))
+
+
+def test_off_grid_resolution_keeps_its_exact_square():
+ assert (520, 520) in bucket_resolutions(520)
+
+
+def test_assignment_follows_aspect():
+ choices = bucket_resolutions(1024)
+ assert nearest_bucket(3000, 3000, choices) == (1024, 1024)
+ assert nearest_bucket(1000, 1010, choices) == (1024, 1024)
+ w, h = nearest_bucket(1080, 1920, choices)
+ assert h > w and abs(math.log((w / h) / (1080 / 1920))) < 0.1
+ w, h = nearest_bucket(1920, 1080, choices)
+ assert w > h
+ assert nearest_bucket(8000, 1000, choices) == max(choices, key = lambda b: b[0] / b[1])
+
+
+def test_cover_resize_is_the_legacy_short_side_resize_for_a_square_canvas():
+ for w0, h0 in ((1920, 1080), (1080, 1920), (777, 333), (64, 64)):
+ scale = 512 / min(w0, h0)
+ legacy = (max(512, round(w0 * scale)), max(512, round(h0 * scale)))
+ assert cover_resize_dims(w0, h0, 512, 512) == legacy
+ rw, rh = cover_resize_dims(1080, 1920, 448, 576)
+ assert rw >= 448 and rh >= 576 and (rw == 448 or rh == 576)
+
+
+def test_oriented_size_reads_exif_rotation(tmp_path):
+ assert oriented_image_size(_img(tmp_path / "a.jpg", 300, 200)) == (300, 200)
+ assert oriented_image_size(_img(tmp_path / "b.jpg", 300, 200, exif_orientation = 6)) == (200, 300)
+
+
+def _groups():
+ return {(512, 512): [0, 1, 2], (640, 384): [3, 4], (384, 640): [5, 6, 7, 8]}
+
+
[email protected]("k", [1, 2, 3])
+def test_sampler_one_bucket_per_batch_and_every_image_per_cycle(k):
+ groups = _groups()
+ sampler = BucketBatchSampler(groups, random.Random(0))
+ cycle = sum(-(-len(v) // k) for v in groups.values())
+ seen = []
+ for _ in range(cycle):
+ shape, idxs = sampler.next_batch(k)
+ assert len(idxs) == k and set(idxs) <= set(groups[shape])
+ seen.extend(idxs)
+ assert set(seen) == set(range(9))
+
+
+def test_sampler_interleaves_buckets_and_is_seed_deterministic():
+ a = BucketBatchSampler(_groups(), random.Random(7))
+ b = BucketBatchSampler(_groups(), random.Random(7))
+ da = [a.next_batch(1) for _ in range(30)]
+ assert da == [b.next_batch(1) for _ in range(30)]
+ assert len({s for s, _ in da[:9]}) == 3
+
+
+def test_sampler_state_round_trips_mid_cycle():
+ rng = random.Random(3)
+ a = BucketBatchSampler(_groups(), rng)
+ for _ in range(4):
+ a.next_batch(2)
+ state = json.loads(json.dumps(a.state_dict()))
+ rng_state = rng.getstate()
+ expected = [a.next_batch(2) for _ in range(12)]
+ rng2 = random.Random()
+ rng2.setstate(rng_state)
+ b = BucketBatchSampler(_groups(), rng2)
+ assert b.load_state_dict(state)
+ assert [b.next_batch(2) for _ in range(12)] == expected
+
+
+def test_sampler_refuses_a_foreign_state():
+ a = BucketBatchSampler(_groups(), random.Random(0))
+ a.next_batch(1)
+ state = a.state_dict()
+ other = BucketBatchSampler({(512, 512): [0, 1, 2, 3, 4, 5, 6, 7, 8]}, random.Random(0))
+ assert not other.load_state_dict(state)
+ assert not a.load_state_dict({"n": 9, "order": list(range(9)), "pos": 0})
+ assert not a.load_state_dict(None)
+ assert not a.load_state_dict({**state, "pos": 999})
+
+
+def _cfg(tmp_path, **kw):
+ kw.setdefault("instance_prompt", "a photo")
+ return DiffusionLoraConfig(
+ base_model = "stabilityai/stable-diffusion-xl-base-1.0",
+ data_dir = str(tmp_path),
+ output_dir = str(tmp_path / "out"),
+ resolution = 512,
+ **kw,
+ )
+
+
+def test_canvases_follow_each_image(tmp_path):
+ paths = [
+ _img(tmp_path / "p.png", 600, 900),
+ _img(tmp_path / "l.png", 900, 600),
+ _img(tmp_path / "s.png", 700, 700),
+ _img(tmp_path / "exact.png", 448, 576),
+ ]
+ cfg = _cfg(tmp_path).normalized()
+ assert cfg.bucketing is True
+ canvases, room = plan_image_canvases(cfg, paths)
+ assert canvases[0][1] > canvases[0][0] and canvases[1][0] > canvases[1][1]
+ assert canvases[2] == (512, 512) and canvases[3] == (448, 576)
+ assert room[3] == (0, 0)
+ assert set(bucket_groups(canvases)) == set(canvases)
+ off = dataclasses.replace(cfg, bucketing = False)
+ assert plan_image_canvases(off, paths) == (None, None)
+
+
+def test_an_all_square_dataset_keeps_the_unbucketed_run(tmp_path):
+ paths = [_img(tmp_path / f"s{i}.png", 700 + i, 700) for i in range(3)]
+ cfg = _cfg(tmp_path).normalized()
+ assert cfg.bucketing is True
+ assert plan_image_canvases(cfg, paths) == (None, None)
+ mixed = paths + [_img(tmp_path / "l.png", 900, 600)]
+ assert plan_image_canvases(cfg, mixed)[0] is not None
+
+
+def test_an_epoch_covers_every_bucket_batch(tmp_path):
+ # 3 buckets x 3 images, batch 2: 6 batches per pass, not ceil(9 / 2) = 5.
+ paths = [
+ _img(tmp_path / f"{kind}{i}.png", w, h)
+ for kind, (w, h) in {"p": (600, 900), "l": (900, 600), "s": (700, 700)}.items()
+ for i in range(3)
+ ]
+ cfg = _cfg(tmp_path, num_epochs = 1, train_batch_size = 2).normalized()
+ assert len(bucket_groups(plan_image_canvases(cfg, paths)[0])) == 3
+ assert resolve_train_steps(cfg, len(paths), paths) == 6
+ assert (
+ resolve_train_steps(dataclasses.replace(cfg, gradient_accumulation_steps = 4), 9, paths) == 2
+ )
+ assert resolve_train_steps(dataclasses.replace(cfg, bucketing = False), 9, paths) == 5
+ assert resolve_train_steps(cfg, 9) == 5
+
+
+def test_the_resume_preflight_target_matches_the_trainer(tmp_path):
+ # The route refuses a checkpoint at or past its target, so it must match the trainer's count.
+ from routes.training import _diffusion_resume_target_steps
+
+ paths = [
+ _img(tmp_path / f"{kind}{i}.png", w, h)
+ for kind, (w, h) in {"p": (600, 900), "l": (900, 600), "s": (700, 700)}.items()
+ for i in range(3)
+ ]
+ pairs = [(p, "a photo") for p in paths]
+ cfg = _cfg(tmp_path, num_epochs = 1, train_batch_size = 2).normalized()
+ assert _diffusion_resume_target_steps(cfg, pairs) == 6
+ inherited = dataclasses.replace(
+ cfg, bucketing = None, resume_from_checkpoint = str(tmp_path / "missing")
+ )
+ assert _diffusion_resume_target_steps(inherited, pairs) == 5
+
+
+def test_plan_collapses_variants_without_crop_room():
+ legacy = _plan_cache_variants(2, 4, False, True, 11)
+ assert _plan_cache_variants(2, 4, False, True, 11, crop_room = None) == legacy
+ bucketed = _plan_cache_variants(2, 4, False, True, 11, crop_room = [(0, 0), (40, 0)])
+ # No slack: only the flip remains, so at most two variants; slack on one axis keeps its draws.
+ assert len(bucketed[0]) <= 2 and all(v[:2] == (0.5, 0.5) for v in bucketed[0])
+ assert all(v[1] == 0.5 for v in bucketed[1])
+ assert [v[0] for v in bucketed[1]] == [v[0] for v in legacy[1]]
+
+
+def test_sdxl_bucket_crop_and_time_ids(tmp_path):
+ path = _img(tmp_path / "p.png", 600, 900)
+ t, ids = _load_image_tensor(path, (448, 576), False, False, random.Random(0))
+ assert t.shape == (3, 576, 448)
+ rw, rh = cover_resize_dims(600, 900, 448, 576)
+ orig_h, orig_w, top, left, target_h, target_w = ids
+ assert (orig_h, orig_w, target_h, target_w) == (900, 600, 576, 448)
+ assert 0 <= top <= rh - 576 and 0 <= left <= rw - 448
+ t2, ids2 = _load_image_tensor_planned(path, (448, 576), True, 0.0, 0.0, True)
+ assert t2.shape == (3, 576, 448)
+ assert ids2[2] == (rh - 576) // 2 and ids2[4:] == (576, 448)
+
+
+def test_square_canvas_tuple_is_byte_identical_to_the_legacy_int(tmp_path):
+ path = _img(tmp_path / "l.png", 900, 600)
+ for loader in (
+ lambda r: _load_image_tensor(path, r, False, True, random.Random(5)),
+ lambda r: _load_image_tensor_planned(path, r, False, 0.3, 0.7, True),
+ ):
+ a, ida = loader(512)
+ b, idb = loader((512, 512))
+ assert torch.equal(a, b) and ida == idb
+ a = dit._load_pixel_tensor(path, 512, False, True, random.Random(5))
+ b = dit._load_pixel_tensor(path, (512, 512), False, True, random.Random(5))
+ assert torch.equal(a, b)
+ assert dit._load_pixel_tensor_planned(path, (640, 384), False, 0.5, 0.5, False).shape == (
+ 3,
+ 384,
+ 640,
+ )
+
+
+class _EchoTransformer(torch.nn.Module):
+ """Returns its packed input as the prediction, so forward(noisy) round-trips to noisy exactly
+ when the family's pack / position ids / unpack agree on a non-square grid."""
+
+ def __init__(self, config = None):
+ super().__init__()
+ self.config = config or SimpleNamespace(guidance_embeds = False)
+ self.calls = []
+
+ def forward(self, *args, **kw):
+ self.calls.append(kw)
+ if args: # Z-Image: list I/O
+ return ([x.clone() for x in args[0]],)
+ return (kw["hidden_states"].clone(),)
+
+
+def _sig(bsz, nd):
+ return torch.full((bsz,), 0.5).view(bsz, *([1] * (nd - 1)))
+
+
[email protected]("h,w", [(48, 80), (80, 48)])
+def test_flux_round_trips_non_square(h, w):
+ pytest.importorskip("diffusers")
+ dit._FLUX_STATIC.clear()
+ noisy = torch.randn(2, 16, h, w)
+ embeds = (torch.randn(2, 7, 32), torch.randn(2, 8), torch.zeros(7, 3))
+ tr = _EchoTransformer()
+ out = dit._flux_forward(
+ tr, noisy, torch.full((2,), 500.0), _sig(2, 4), embeds, None, "cpu", torch.float32
+ )
+ assert torch.equal(out, noisy)
+ assert tr.calls[0]["img_ids"].shape == ((h // 2) * (w // 2), 3)
+
+
[email protected]("h,w", [(48, 80), (80, 48)])
+def test_qwen_round_trips_non_square(h, w):
+ pytest.importorskip("diffusers")
+ noisy = torch.randn(2, 16, 1, h, w)
+ tr = _EchoTransformer()
+ out = dit._qwen_forward(
+ tr,
+ noisy,
+ torch.full((2,), 500.0),
+ _sig(2, 5),
+ (torch.randn(2, 5, 8), None),
+ None,
+ "cpu",
+ torch.float32,
+ )
+ assert torch.equal(out, noisy)
+ assert tr.calls[0]["img_shapes"] == [[(1, h // 2, w // 2)]] * 2
+
+
[email protected]("h,w", [(48, 80), (80, 48)])
+def test_zimage_round_trips_non_square(h, w):
+ noisy = torch.randn(2, 16, h, w)
+ out = dit._zimage_forward(
+ _EchoTransformer(),
+ noisy,
+ torch.full((2,), 500.0),
+ _sig(2, 4),
+ ([torch.randn(5, 8)] * 2,),
+ None,
+ "cpu",
+ torch.float32,
+ )
+ assert torch.equal(out, -noisy)
+
+
[email protected]("h,w", [(48, 80), (80, 48)])
+def test_krea2_round_trips_non_square(h, w):
+ pytest.importorskip("diffusers.pipelines.krea2")
+ noisy = torch.randn(2, 16, 1, h, w)
+ tr = _EchoTransformer()
+ embeds = (torch.randn(2, 6, 4, 8), torch.ones(2, 6, dtype = torch.int64))
+ out = dit._krea2_forward(
+ tr, noisy, torch.full((2,), 500.0), _sig(2, 5), embeds, None, "cpu", torch.float32
+ )
+ assert torch.equal(out, noisy)
+ assert tr.calls[0]["position_ids"].shape[0] == 6 + (h // 2) * (w // 2)
+
+
[email protected]("h,w", [(24, 40), (40, 24)])
+def test_flux2_round_trips_non_square(h, w):
+ pytest.importorskip("diffusers")
+ dit._FLUX2_STATIC.clear()
+ noisy = torch.randn(2, 128, h, w)
+ embeds = (torch.randn(2, 7, 32), torch.zeros(2, 7, 4))
+ out = dit._flux2_forward(
+ _EchoTransformer(),
+ noisy,
+ torch.full((2,), 500.0),
+ _sig(2, 4),
+ embeds,
+ None,
+ "cpu",
+ torch.float32,
+ )
+ assert torch.equal(out, noisy)
+
+
[email protected]("h,w", [(12, 20), (20, 12)])
+def test_ltx2_round_trips_non_square(h, w):
+ pytest.importorskip("diffusers")
+ try:
+ dit._ltx2_pipeline_cls()
+ except Exception as exc: # noqa: BLE001
+ pytest.skip(f"LTX2Pipeline unavailable: {exc}")
+ conf = SimpleNamespace(
+ patch_size = 1,
+ patch_size_t = 1,
+ vae_scale_factors = (8, 32, 32),
+ audio_sampling_rate = 16000,
+ audio_hop_length = 160,
+ audio_scale_factor = 4,
+ audio_in_channels = 8,
+ )
+
+ class _Ltx(_EchoTransformer):
+ def forward(self, *args, **kw):
+ self.calls.append(kw)
+ return kw["hidden_states"].clone(), None
+
+ tr = _Ltx(conf)
+ noisy = torch.randn(2, 16, 1, h, w)
+ embeds = (torch.randn(2, 6, 32), torch.randn(2, 6, 32), torch.ones(2, 6, dtype = torch.int64))
+ out = dit._ltx2_forward(
+ tr, noisy, torch.full((2,), 500.0), _sig(2, 5), embeds, None, "cpu", torch.float32
+ )
+ assert torch.equal(out, noisy)
+ assert (tr.calls[0]["height"], tr.calls[0]["width"]) == (h, w)
+
+
+def test_bucketing_defaults_on_for_a_fresh_run_and_unset_for_a_resume(tmp_path):
+ assert _cfg(tmp_path).normalized().bucketing is True
+ assert _cfg(tmp_path, bucketing = False).normalized().bucketing is False
+ assert (
+ _config_from_dict(
+ {
+ "base_model": "stabilityai/stable-diffusion-xl-base-1.0",
+ "data_dir": "d",
+ "output_dir": "o",
+ "bucketing": "false",
+ }
+ ).bucketing
+ is False
+ )
+ resumed = _cfg(tmp_path, resume_from_checkpoint = str(tmp_path / "nowhere")).normalized()
+ assert resumed.bucketing is None
+ assert resolve_bucketing(resumed).bucketing is False
+
+
+def test_h3_recipe_pins_bucketing_off():
+ cfg = SimpleNamespace(resolved_family = "minimax-h3")
+ assert train_recipe_overrides(cfg)["bucketing"] is False
+
+
+def _identity(tmp_path, bucketing):
+ cfg = dataclasses.replace(_cfg(tmp_path).normalized(), bucketing = bucketing)
+ return dc.identity_for_config(cfg)
+
+
+def test_identity_records_bucketing_and_refuses_a_flip(tmp_path):
+ on, off = _identity(tmp_path, True), _identity(tmp_path, False)
+ assert on.bucketing == "on" and off.bucketing == "off"
+ assert "aspect ratio buckets" in (on.mismatch_reason(off) or "")
+ assert "aspect ratio buckets" in (off.mismatch_reason(on) or "")
+ assert on.mismatch_reason(_identity(tmp_path, True)) is None
+
+
+def test_a_manifest_without_the_field_trained_square(tmp_path):
+ legacy = dc.CheckpointIdentity.from_dict(
+ {**_identity(tmp_path, False).as_dict(), "bucketing": None}
+ )
+ assert legacy.bucketing is None
+ assert legacy.mismatch_reason(_identity(tmp_path, False)) is None
+ assert "aspect ratio buckets" in (legacy.mismatch_reason(_identity(tmp_path, True)) or "")
+ # The route's pre-trainer identity has not resolved the field yet: cannot tell, not a mismatch.
+ assert legacy.mismatch_reason(_identity(tmp_path, None)) is None
+
+
+def test_resume_adopts_the_recorded_bucketing(tmp_path, monkeypatch):
+ monkeypatch.setattr(dc, "resolve_resume_dir", lambda p: dc.Path(p))
+ for recorded, expected in (("on", True), ("off", False), (None, False)):
+ bundle = tmp_path / f"run_{recorded}" / "checkpoint-3"
+ bundle.mkdir(parents = True)
+ ident = {**_identity(tmp_path, False).as_dict(), "bucketing": recorded}
+ monkeypatch.setattr(dc, "read_checkpoint", lambda p, ident = ident: {"identity": ident})
+ assert dc.recorded_bucketing(str(bundle)) is expected
+ cfg = _cfg(tmp_path, resume_from_checkpoint = str(bundle)).normalized()
+ assert resolve_bucketing(cfg).bucketing is expected
+
+
+def test_persistent_cache_keys_a_bucketed_latent_by_its_canvas(tmp_path):
+ from core.training.diffusion_train_extras import PersistentConditioningCache
+
+ path = _img(tmp_path / "p.png", 600, 900)
+ cache = PersistentConditioningCache(str(tmp_path / "cc"), "fam", 512)
+ variant = (0.5, 0.5, False)
+ cache.put(cache.text_key("cap"), (torch.zeros(1, 3),))
+ cache.put(cache.latent_key(path, variant, (448, 576)), (torch.ones(1, 4, 72, 56), None))
+ plan = [[variant]]
+ embeds, latents = dit._load_warm_conditioning(cache, [path], plan, ["cap"], "cpu", [(448, 576)])
+ assert latents[0][0][0].shape == (1, 4, 72, 56)
+ assert dit._load_warm_conditioning(cache, [path], plan, ["cap"], "cpu") == (None, None)
diff --git a/studio/backend/tests/test_diffusion_h3_trainer.py b/studio/backend/tests/test_diffusion_h3_trainer.py
index e322ea6b2f9..f8e1c729641 100644
--- a/studio/backend/tests/test_diffusion_h3_trainer.py
+++ b/studio/backend/tests/test_diffusion_h3_trainer.py
@@ -1317,6 +1317,8 @@ def test_the_persisted_h3_recipe_is_the_one_the_loop_runs():
# cached-with-one anyway and the record said otherwise.
"cache_latents": True,
"cache_variants": 1,
+ # One packed clip canvas: no image buckets, whatever the request said.
+ "bucketing": False,
}
# Config-only: the other flow-matching loops disagree only on min-SNR, and SDXL on nothing.
other = DiffusionLoraConfig(
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index be24d45cdfa..6e3cae434fd 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -628,6 +628,8 @@ export interface DiffusionTrainingStartRequest {
cache_variants?: number;
// Allow TF32 matmuls on Ampere+ for a throughput win at negligible quality cost.
enable_tf32?: boolean;
+ // Omitted: on for a new run; a resume keeps its checkpoint's.
+ bucketing?: 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;
@@ -821,6 +823,8 @@ export interface DiffusionTrainableFamily {
// Whether the family's loop writes checkpoint bundles (gates the "Checkpoint every" field).
// Undefined on an older backend, which has no checkpointless family, so it reads as true.
supports_checkpoints?: boolean;
+ // Undefined on an older backend (control hidden).
+ supports_bucketing?: boolean;
/** 1 for a family whose forward covers one packed sequence; null/absent means unrestricted. */
max_train_batch_size?: number | null;
// When set, deploying a LoRA trained on this family previews it on this repo instead of the
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 2e503704d67..080571e6d4f 100644
--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
@@ -455,6 +455,8 @@ export function DiffusionTrainPanel({
// Same for checkpoints: MiniMax-H3's loop writes no resume bundle and its validation REFUSES a
// nonzero save_steps, so offering the field meant a rejected Start with nothing saying why.
const supportsCheckpoints = reportedFamily?.supports_checkpoints ?? true;
+ // Same for buckets: MiniMax-H3 always trains one packed canvas, and an older backend drops the field.
+ const supportsBucketing = reportedFamily?.supports_bucketing ?? false;
// Same for the batch axis: MiniMax-H3's forward covers ONE packed sequence and its validation REFUSES a batch
// above 1 rather than clamping, so a value carried over from another family rejected Start with nothing saying
// why. Hidden when the family caps it at 1.
@@ -510,6 +512,7 @@ export function DiffusionTrainPanel({
const [lrWarmupSteps, setLrWarmupSteps] = useState(0);
// Gradient checkpointing trades ~20-30% step time for a large activation-VRAM saving.
const [gradCheckpoint, setGradCheckpoint] = useState(true);
+ const [bucketing, setBucketing] = useState(true);
const [randomFlip, setRandomFlip] = useState(false);
// Only the DiT loops read it, and MiniMax-H3 refuses it: it has no unconditional branch to train.
const [cfgDropout, setCfgDropout] = useState(0);
@@ -1195,6 +1198,7 @@ export function DiffusionTrainPanel({
gradient_accumulation_steps: gradAccum,
seed,
gradient_checkpointing: gradCheckpoint,
+ bucketing: supportsBucketing ? bucketing : undefined,
random_flip: randomFlip,
lr_scheduler: lrScheduler,
lr_warmup_steps: lrScheduler === "constant" ? 0 : lrWarmupSteps,
@@ -1240,6 +1244,8 @@ export function DiffusionTrainPanel({
saveSteps,
saveTotalLimit,
gradCheckpoint,
+ supportsBucketing,
+ bucketing,
randomFlip,
cfgDropout,
supportsCfgDropout,
@@ -1544,6 +1550,25 @@ export function DiffusionTrainPanel({
</Select>
</div>
+ {supportsBucketing && (
+ <div className={fieldClass}>
+ <FieldLabel hint="Trains each image at the same pixel count but its own shape (portrait, landscape or square), so non-square photos are not cropped square.">
+ Aspect ratio buckets
+ </FieldLabel>
+ <Select
+ value={bucketing ? "on" : "off"}
+ onValueChange={(v) => setBucketing(v === "on")}
+ >
+ <SelectTrigger className={selectClass} aria-label="Aspect ratio buckets">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="on">On (keep aspect)</SelectItem>
+ <SelectItem value="off">Off (square crop)</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ )}
{!isH3 && (
<div className={fieldClass}>
<FieldLabel hint="Mirrors images left-right at random for extra variety. Leave off for text, logos or subjects with one-sided features (a side parting, a scar); try on for styles and symmetric subjects.">