Repository navigation
FLUX.1-dev, Qwen-Image, and Z-Image LoRA training - #6820
Conversation
…8 accumulate, with user override Consumer/workstation GPUs (GDDR) halve fp8 FP32-accumulate throughput, so they want fast (FP16) accumulate; data-center HBM parts (B200/H100/A100/L40) are not nerfed and prefer the higher-precision FP32 accumulate. Add _is_consumer_gpu() (token-exact match on the device name per NVIDIA's GPU list, so workstation A4000 != data-center A40; GeForce/TITAN and unknown default to consumer) and gate the fp8 use_fast_accum on it. Measured: fast accumulate is ~2x on consumer Blackwell and ~8% on B200 (0.608 vs 0.665s), no overflow, quality below the quant noise floor. So the default leans to accuracy on data-center; a new request field transformer_quant_fast_accum (null=auto, true/false=force) lets the operator override per load (scripts/diffusion_bench.py --fp8-fast-accum auto|on|off). 187 diffusion tests pass (+ consumer detection, _resolve_fast_accum, and the override threading).
… a win on torch 2.9 scripts/nvfp4_probe.py measures NVFP4 via torchao on the real Z-Image transformer. Finding (B200, 1024px/8 steps): NVFP4 is a torchao feature and DOES run with use_triton_kernel=False (the default triton path needs the missing MSLK library), but only at bf16-compile rate (0.667s vs fp8 0.592s) -- it dequantises FP4->bf16 rather than using the FP4 tensor cores. The real FP4 speedup needs MSLK or torch>=2.11 + torchao's CUTLASS FP4 GEMM. The smoke probe (default triton=True) already keeps NVFP4 out of auto on this env, so auto correctly stays on fp8; NVFP4 activates automatically once fast.
…adder Validated NVFP4 on torch 2.11 + torchao CUTLASS FP4 in an isolated env. The FP4 tensor-core GEMM is genuinely active there (a 16384^3 GEMM hits ~3826 TFLOPS, 2.52x bf16 and 1.37x fp8), but it only beats fp8 on very large GEMMs. At the diffusion transformer's shapes (hidden ~3072, MLP ~12288, M~4096) NVFP4 is both slower (0.81x fp8 end to end on Z-Image 1024px) and less accurate (LPIPS 0.166 vs fp8's 0.044). Reorder the Blackwell auto ladder to fp8 before nvfp4 so auto is correct even on a future MSLK-equipped box; nvfp4 stays an explicit opt-in. Add scripts/nvfp4_t211_probe.py (extension diagnostics + GEMM micro + end-to-end).
The Phase 8 fast transformer_quant path materialises the dense bf16 transformer on the GPU and torchao-quantises it in place, so its load peak is ~2x GGUF's (~21 vs 13.4 GB) plus a ~12 GB download. Add a pre-quantized branch: quantise once offline (scripts/build_prequant_checkpoint.py) and at runtime build the transformer skeleton on the meta device (accelerate.init_empty_weights) and load_state_dict(assign=True) the quantized weights, so the dense bf16 never touches the GPU. Measured (B200, Z-Image fp8): full-pipeline GPU load peak 21.2 -> 14.6 GB (matching GGUF's 13.4), on-disk 12 -> 6.28 GB, output bit-identical (LPIPS 0.0). It is the same torchao config + min_features filter the runtime path uses, applied ahead of time. New core/inference/diffusion_prequant.py (resolve_prequant_source + load_prequantized_transformer, best-effort, lazy imports). diffusion.py _load_dense_quant_pipeline tries the pre-quant source first and falls back to the dense materialise+quantise path, then to GGUF, so the default is unchanged. DiffusionLoadRequest gains transformer_prequant_path; DiffusionFamily gains an empty prequant_repos map for hosted checkpoints (hosting deferred). Hermetic CPU tests for the resolver, the meta-init+assign loader, and the backend branch selection + fallbacks; GPU verification via scripts/verify_prequant_backend.py.
Add a selectable attention kernel via the diffusers set_attention_backend dispatcher. Attention is memory-bandwidth bound, so a better kernel is an end-to-end win orthogonal to the linear-weight quantisation (it speeds the QK/PV matmuls torchao never touches) and composes with torch.compile. auto picks the best exact backend for the device: cuDNN fused attention (_native_cudnn) on NVIDIA when a speed profile is active, measured ~1.18x end-to-end on a B200 (Z-Image 1024px/8 steps) with LPIPS ~0.004 vs the default (below the compile/quant noise floor); native SDPA elsewhere and when speed=off (so off stays bit-identical). Explicit native/cudnn/flash/flash3/flash4/sage/ xformers/aiter are honored, and an unavailable kernel falls back to the default rather than failing the load. New core/inference/diffusion_attention.py (normalize + per-device select + apply, best-effort, lazy imports). Set on pipe.transformer BEFORE compile in load_pipeline; attention_backend threads through begin_load / load_pipeline / status like the other load knobs. New request field attention_backend + status field. Hermetic CPU tests for normalize / select policy / apply fallback, plus route threading + 422. Measured via scripts/perf_levers_probe.py.
… ladder Consumer / workstation GPUs halve fp8 (and fp16/bf16) FP32-accumulate tensor-core throughput, while int8 runs at full rate (int32 accumulate is not nerfed). Public benchmarks (SDNQ across RTX 3090/4090/5090, AMD, Intel) confirm int8 via torch._int_mm is as fast or faster than fp8 on every consumer part, and the only path on pre-Ada consumer cards without fp8 tensor cores. So when transformer_quant=auto, reorder the arch tier to put int8 first on a consumer/workstation GPU (detected by the existing _is_consumer_gpu name heuristic), while data-center HBM parts keep fp8 first. Pure ladder reorder via _prefer_consumer_scheme; no new flags. Verified non-regression on a B200 (still picks fp8). Hermetic tests for consumer Blackwell/Ada/workstation (-> int8) and data-center Ada/Hopper/Blackwell (-> fp8).
…step DiT Add opt-in step caching (First-Block-Cache) for the diffusion transformer. Across denoise steps a DiT's output settles, so once the first block's residual barely changes the remaining blocks are skipped and their cached output reused. diffusers ships it natively (FirstBlockCacheConfig + transformer.enable_cache, with the standalone apply_first_block_cache hook as a fallback). Measured on Flux.1-dev (28 steps, 1024px): ~1.4x on top of torch.compile (2.83 -> 2.03s) at LPIPS ~0.08 vs the no-cache output, well inside the quality bar. OFF by default and a per-load opt-in: the win scales with step count, so it is for many-step models (Flux / Qwen-Image) and pointless for few-step distilled models (e.g. Z-Image-Turbo at ~8 steps), where a single skipped step is a large fraction of the trajectory. It composes with regional compile only with fullgraph=False (the cache's per-step decision is a torch.compiler.disable graph break), which the speed layer now switches to automatically when a cache is engaged. Best-effort: a model whose block signature the hook does not recognise is caught and the load proceeds uncached. - new core/inference/diffusion_cache.py: normalize_transformer_cache + apply_step_cache (enable_cache / apply_first_block_cache fallback; threshold auto-raised for a quantised transformer per ParaAttention's fp8 guidance; lazy diffusers import). - diffusion_speed.py: apply_speed_optims takes cache_active; compile drops fullgraph when a cache is engaged. - diffusion.py: apply_step_cache before compile; thread transformer_cache / transformer_cache_threshold through begin_load -> load_pipeline and report the engaged mode in status(). - models/inference.py + routes/inference.py: transformer_cache (off | fbcache) and transformer_cache_threshold request fields, engaged mode in the status response. - hermetic tests for normalisation, the enable_cache / hook-fallback paths, threshold selection, and best-effort failure handling, plus route threading + validation. - scripts/fbcache_flux_probe.py: the Flux validation probe (latency / speedup / VRAM / LPIPS vs the compiled no-cache baseline).
…p M=1 modulation linears) The opt-in dense int8 transformer path crashed on Flux.1 and Qwen-Image with 'torch._int_mm: self.size(0) needs to be greater than 16, but got 1'. int8 dynamic quant goes through torch._int_mm, which requires the activation row count M > 16. A DiT's AdaLN modulation projections (Flux norm1.linear 3072->18432, Qwen img_mod.1 / txt_mod.1, Flux.2 *_modulation.linear) and its timestep / guidance / pooled-text conditioning embedders are computed once from the [batch, dim] conditioning vector (M = batch = 1), not per token, so they hit _int_mm at M=1 and crash. Their feature dims are large, so the existing min_features filter did not exclude them. Fix: the int8 filter now also skips any Linear whose fully-qualified name matches a modulation / conditioning-embedder token (norm, _mod, modulation, timestep_embed, guidance_embed, time_text_embed, pooled). These layers run at M=1 once per block and are a negligible share of the FLOPs, so int8 keeps the full speedup on the attention / FFN layers (M = sequence length). fp8 / nvfp4 / mxfp8 use scaled_mm, which has no M>16 limit and quantises these layers fine, so the exclusion is int8-only. Sequence embedders (context_embedder / x_embedder / txt_in, M = seq) are deliberately not excluded -- note 'context_embedder' contains the substring 'text_embed', which is why the token is the specific 'time_text_embed', not 'text_embed'. Measured on a B200 (1024px, transformer_quant=int8 + speed=default), int8 now runs on every supported model and is the fastest dense path on Flux/Qwen (int8 runs full-rate vs fp8's FP32-accumulate): FLUX.1-dev 9.62s eager -> 1.98s (4.86x, vs fp8 2.15s), Qwen-Image -> 1.87s (5.57x, vs fp8 2.09s), FLUX.1-schnell -> 0.41s (3.59x). Z-Image and Flux.2-klein (already working) are unchanged. - diffusion_transformer_quant.py: add _INT8_EXCLUDE_NAME_TOKENS; make_filter_fn takes exclude_name_tokens; quantize_transformer passes it for int8 only. - hermetic test that the int8 filter excludes the modulation / embedder linears (and keeps attention / FFN / sequence-embedder linears), while fp8 keeps them. - scripts/int8_linear_probe.py: the meta-device probe used to enumerate each transformer's Linear layers and derive the exclusion list.
…ip M=1 modulation linears) The prequant-checkpoint builder applied the dense quant filter without the int8-only M=1 modulation / conditioning-embedder exclusion the runtime path uses, so a built int8 checkpoint baked those projections as int8 and crashed (torch._int_mm needs M>16) at the first denoise step on Flux / Qwen. Factor the scheme->exclusion decision into a shared exclude_tokens_for_scheme() used by both the runtime quantise path and the offline builder so they can never drift, and apply it in build_prequant_checkpoint.py. int8 prequant now produces a working checkpoint on every supported model, giving int8 (the consumer-preferred scheme) the same ~2x load-VRAM and download reduction fp8 already had.
…engine When no CUDA/ROCm/XPU GPU is available, route diffusion load/generate to the native stable-diffusion.cpp engine instead of diffusers, with diffusers as the guaranteed fallback. On CPU sd.cpp is 1.4-2.8x faster and uses 1.5-2.2x less RAM. - diffusion_engine_router: centralised engine selection (built on the existing select_diffusion_engine), env opt-outs, MPS gating, recorded fallback reason. - sd_cpp_backend (SdCppDiffusionBackend): the diffusers backend method surface backed by sd-cli, with lazy binary install, registry-driven asset fetch, step-progress parsing, and cancellation. - diffusion_families: per-family single-file VAE + text-encoder asset mapping. - sd_cpp_engine: cancellation support (process-group kill + SdCppCancelled). - routes/inference + gpu_arbiter: drive the active engine via the router; the API now reports the active engine and any fallback reason. - tests for the backend, router, route selection, and cancellation.
…r-image seeds, Qwen sampler Address review feedback on #6724: - engine router: unload the engine being deactivated on a switch, so the old model is not left resident-but-unreachable (the evictor only targets the active engine). - generate route: sd.cpp execution errors (nonzero exit / timeout / missing output) now map to 500, not 409 (which only means not-loaded / cancelled). - native batch: return per-image seeds and persist the actual seed for each image so every batch image is reproducible. - Qwen-Image native path: apply --sampling-method euler --flow-shift 3 per the stable-diffusion.cpp docs; other families keep sd-cli defaults. - honor speed_mode (native --diffusion-fa) and, off-CPU, memory_mode/cpu_offload offload flags on the native load instead of hardcoding them off. - fail the load when the sd-cli binary is present but not runnable (version() now returns None on exec error / nonzero exit). - size estimate: only treat the transformer asset as a possible local path.
…s behind operator opt-in load_prequantized_transformer ends in torch.load(weights_only=False), which executes arbitrary code from the pickle. The transformer_prequant_path load-request field reached that unpickle for any local file an authenticated caller named, so a request could trigger remote code execution. Refuse the source.kind=='path' branch unless the operator sets UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH=1; the first-party hosted-repo checkpoint stays trusted and unaffected. Document the requirement on the API field and add gate tests.
…tive, gate arch-specific kernels, accept sdpa
- apply_attention_backend now restores the native default when no backend is requested or a
kernel fails. diffusers keeps a process-wide active attention backend that
set_attention_backend updates, and a fresh transformer's processors follow it, so a load
that wanted native could silently inherit a backend (e.g. cuDNN) an earlier speed-profile
load pinned, breaking the bit-identical/off guarantee.
- select_attention_backend drops flash3/flash4 up front when the CUDA capability is below
Hopper/Blackwell. diffusers only checks the kernels package at set time, so an explicit
request on the wrong card set fine then crashed mid-generation; it now falls back to native.
- Add the sdpa alias to the attention_backend Literal so an API request with sdpa (already a
valid alias of native) is accepted instead of 422-rejected by Pydantic.
- Drop the dead replace('-','_') normalization (no alias uses dashes/underscores).
- perf_levers_probe.py output dir is now relative to the script, not a hardcoded path.
…nsformers; quantized threshold for GGUF - apply_step_cache now engages only via the transformer's native enable_cache (the diffusers CacheMixin path), which exists exactly when the pipeline wraps the transformer call in a cache_context. The standalone apply_first_block_cache fallback installed on non-CacheMixin transformers too (e.g. Z-Image), whose pipeline opens no cache_context, so the load reported transformer_cache=fbcache and then the first generation crashed inside the hook. Such a model now runs uncached per the best-effort contract. - GGUF transformers are quantized (the default Studio load path), so they now use the higher quantized FBCache threshold when the caller leaves it unset, instead of the dense default that could keep the cache from triggering. - fbcache_flux_probe.py: compile cached runs with fullgraph=False (FBCache is a graph break, so fullgraph=True failed warmup and silently measured an eager cached run); output dir is now relative to the script, not a hardcoded path.
…adder _is_consumer_gpu treated professional parts (RTX PRO 6000 Blackwell, RTX 6000 Ada) as consumer because their names carry no datacenter token, so the auto ladder moved int8 ahead of fp8 and the fp8 path chose fast accumulate for them. The rest of the backend already classifies these as datacenter/professional (llama_cpp.py _DATACENTER_GPU_RE), so detect the same RTX PRO 6000 / RTX 6000 Ada markers here and keep fp8 first with precise accumulate. Also fix the consumer-Blackwell test to use compute capability (10, 0) instead of (12, 0).
…he mxfp8 config Accessing torch.float8_e4m3fn raises AttributeError on a torch build without it (not just TypeError on older torchao), which would break the mxfp8 config helper instead of falling back to the default. Catch both so the fallback is robust. quant_probe.py: same AttributeError fallback; run LPIPS on CPU so the scorer never holds CUDA memory during the per-row VRAM probe; output dir relative to the script.
…restore on failed speeded load - snapshot_backend_flags reads each flag defensively (getattr + hasattr), so a build/platform missing one (no cuda.matmul on CPU/MPS) still captures the rest instead of skipping the whole snapshot. restore_backend_flags restores each flag independently so one failure can't leave the others leaked process-wide. - load_pipeline restores the flags (and clears the GPU cache) when the build fails after apply_speed_optims mutated the process-wide flags but before _state captured them for unload to restore -- otherwise a failed default/max load left cudnn.benchmark/TF32 on and contaminated later off generations.
…ffusion-lora-training-api
…o diffusion-lora-training-ui
The trainer only supports the SDXL U-Net, but a FLUX / Qwen-Image / Z-Image repo or a GGUF filename passed as base_model was accepted and then failed minutes later inside StableDiffusionXLPipeline.from_pretrained with an unrelated-looking error. Add a name-based guard in normalized() so known DiT-family names and .gguf checkpoints are rejected up front, which the API start route surfaces as an immediate 400 with a message that says exactly which bases are trainable. Unrecognisable names still pass through so custom local SDXL checkpoints keep working.
…ffusion-lora-training-api
Training an image LoRA required knowing the Studio home layout and copying files onto the server by hand, which is the most confusing step of the whole flow. Two small endpoints fix that: - GET /api/train/diffusion/info reports the datasets and outputs roots plus every dataset folder that contains images (with image/caption counts), so the UI can offer a picker instead of a blind free-text path. - POST /api/train/diffusion/dataset uploads images and optional caption .txt / metadata.jsonl files into a named folder under the datasets root, creating it on first use and accumulating on repeat uploads so large sets can arrive in batches. Names are validated to a single path component and files stream to disk under the same per-upload size cap as LLM dataset uploads. The returned name is a valid data_dir for /diffusion/start.
…o diffusion-lora-training-ui
The dialog assumed users knew the Studio home layout and that only SDXL is trainable, and hid both facts behind free-text fields. Restructure it around the three real decisions: - Base model is a dropdown of the trainable SDXL picks (Base 1.0, Turbo, the loaded SDXL pipeline when there is one) with a custom repo/path escape hatch, instead of a bare text field defaulting to a repo id. - Training images come from an in-browser upload (new dataset endpoints) or a picker over existing dataset folders with image/caption counts. No shell access or knowledge of the datasets root is needed any more, and the captioning rules are explained inline. - The output field is now Adapter name and the instance prompt is labelled as the trigger prompt, with a no-captions warning wired to the selected dataset's actual caption count. Hyperparameters collapse behind a training settings toggle since the defaults suit a first run. A completed run says where the adapter went and offers Done / Train another, and the top-bar button gets an icon and a plainer description. The dialog title states the SDXL-only scope and that other families load LoRAs but cannot train them yet.
The start route freed resident GPU workloads (export, Images pipeline, chat) before the service validated the config, so a start that was then refused, now including a non-SDXL base model, tore down the user's loaded model for nothing. Run the same cheap normalise pass first; the LLM path already follows this rule via its before_spawn hook.
…o diffusion-lora-training-ui
Split the SDXL trainer into a shared, architecture-agnostic layer so more model families can be trained without duplicating the plumbing: - New core/training/diffusion_train_common.py holds the config + validation, dataset discovery, event emission, stop protocol, adapter publishing, and a lazy trainer registry (get_trainer). diffusion_lora_trainer.py keeps the SDXL-specific loop and re-exports the moved names so existing imports are unchanged. - The SDXL-only base-model blocklist becomes a positive check: the family is resolved from the base model (or an explicit model_family) via the diffusion family registry, and a known-but-not-yet-trainable family is refused with a clear message. Unknown custom names still default to the SDXL trainer. - DiffusionFamily gains a trainable flag and train_base_repos; SDXL is marked trainable. DiT families flip on when their trainers land. - Trained adapters now write a <name>.json metadata sidecar (family, base model, rank, trigger prompt, ...) that the LoRA scanner reads to family-gate the adapter in the picker instead of showing it as unknown for every model. - The training base-model trust allowlist adds the official FLUX.1-dev, Z-Image-Turbo, and Qwen-Image repos (safetensors-only, no remote code).
The training service kept only the latest loss, so a live loss chart could show a single point. Fold each progress event into bounded (step, loss, lr) history arrays (capped at 4000 points, decimated when full) plus the latest throughput and peak VRAM, and record the family / base model / catalog path on completion. The status endpoint returns these as a nested metric_history object the UI can chart directly, and the start request accepts an optional model_family override.
Cover the trainer registry (get_trainer resolves SDXL, unknown family raises), family resolution (explicit model_family validation, resolved_family on the config), the metadata sidecar write + scan read with family gating, and the service loss-history folding (append, bad-point skipping, decimation at cap, family/perf fields) plus the status route nesting metric_history.
Extends diffusion LoRA training beyond SDXL to the three popular DiT families via a single shared flow-matching loop parameterised by small per-family specs (loading, prompt/latent encoding, transformer forward, save). Verified against diffusers 0.38.0: - FLUX.1-dev: 2x2 latent packing + image ids, guidance-embed forward, on-the-fly nf4 QLoRA of the 12B transformer (the dev repo is gated, so training needs the user's HF token). - Qwen-Image: 5D VAE latents normalised by the per-channel latents_mean/std, img_shapes forward, prequant nf4 base by default (on-the-fly nf4 for the bf16 base). - Z-Image: list I/O with the reversed timestep convention and a negated prediction, bf16 only. The registry (get_trainer) and DiffusionFamily.trainable / train_base_repos now route these families to the DiT trainer; the SDXL blocklist guard is replaced by a positive family resolution that also rejects GGUF repos (inference-only) and still-unsupported families. Per-family defaults + labels + VRAM notes are exposed via family_train_infos for the Train UI. Memory: caption embeddings are precomputed once and the text encoders freed before the loop; gradient checkpointing (non-reentrant, required for bnb 4-bit) and 8-bit AdamW are on by default.
…damW) SDXL re-encoded every caption with both CLIP text encoders on every step (pure waste, since captions are constant) and kept the encoders resident. Precompute each unique caption's embeddings once, then free the text encoders before the loop: numerically identical (embeddings are deterministic and this consumes no torch RNG, so the noise/timestep stream is unchanged) but faster and ~1.5 GB lighter. Default the optimizer to 8-bit AdamW (bitsandbytes) with an fp32 fallback, halving optimizer state with no meaningful LoRA quality cost. Env toggles (UNSLOTH_DIFFUSION_NO_PRECOMPUTE / _FP32_OPTIM) let the accuracy guard A/B the paths.
The training info endpoint now returns the trainable model families (name, label, default + allowed base repos, recommended defaults, and a VRAM/access note) so the Train UI can offer a base picker with realistic guidance. The start route preflights a gated base repo (HEAD model_index.json with the user's token) BEFORE freeing resident GPU workloads, so a missing FLUX.1-dev license/token fails fast with an actionable 400 instead of evicting the loaded model and then hitting a confusing mid-load 401.
…ight Cover the DiT spec table, the QLoRA prequant heuristic, the Z-Image bf16-only guard, the gated-repo name check, family resolution now that FLUX/Qwen/Z-Image are trainable (and GGUF repos are rejected as inference-only), the families list in /diffusion/info, and the gated-base 400 preflight that leaves the GPU untouched.
The fp32 LoRA parameters and the bnb 4-bit base matmuls need a single compute dtype during the forward, exactly like the diffusers dreambooth scripts run under accelerator.autocast. Without it the 4-bit backward on FLUX.1-dev fails with an illegal-address CUBLAS error partway into the first step. Z-Image and Qwen-Image smokes are unaffected and the SDXL path (its own trainer) is untouched.
There was a problem hiding this comment.
Code Review
This pull request introduces flow-matching LoRA training for DiT image families (FLUX.1-dev, Qwen-Image, and Z-Image), including a new trainer module, precomputation of text embeddings to optimize VRAM usage, and preflight access checks for gated Hugging Face repositories. The review feedback highlights several key improvement opportunities: explicitly validating and restricting the batch size to 1 in the DiT trainer, defensively verifying local directory paths to avoid false positives in GGUF checks and unnecessary preflight network requests, sanitizing Hugging Face tokens, moving text encoders to the CPU before freeing them to prevent VRAM leaks, and using context managers when opening images to avoid resource leaks.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| cfg = config.normalized() | ||
| spec = _SPECS.get(cfg.resolved_family) | ||
| if spec is None: | ||
| raise ValueError(f"No DiT trainer for family {cfg.resolved_family!r}") | ||
|
|
There was a problem hiding this comment.
The DiT training loop is currently hardcoded to process one sample at a time, meaning it only supports a train_batch_size of 1. If a user configures a larger batch size, the trainer will silently train with batch size 1 while reporting incorrect throughput metrics. We should explicitly validate and reject train_batch_size > 1 up front.
| cfg = config.normalized() | |
| spec = _SPECS.get(cfg.resolved_family) | |
| if spec is None: | |
| raise ValueError(f"No DiT trainer for family {cfg.resolved_family!r}") | |
| if cfg.train_batch_size > 1: | |
| raise ValueError( | |
| f"DiT LoRA training currently only supports a train_batch_size of 1. " | |
| f"Use gradient_accumulation_steps to simulate larger batch sizes." | |
| ) | |
| # DiT families train in bf16 (Z-Image/Qwen require it; FLUX prefers it). A caller that | |
| # explicitly asks for fp16 on a bf16-only family is refused rather than silently | |
| # upgraded, so the choice is never misrepresented. | |
| if cfg.mixed_precision == "fp16" and spec.force_bf16: |
| # GGUF weights (a ``.gguf`` file or a ``*-GGUF`` repo) are inference-only: training needs | ||
| # the full diffusers pipeline (transformer + VAE + text encoders), which a GGUF repo does | ||
| # not provide. Reject by name even when the family itself is trainable. | ||
| if name.endswith(".gguf") or "gguf" in name: |
There was a problem hiding this comment.
Using a simple substring check "gguf" in name on the base model path can cause false positives if the user is training from a local directory that happens to contain the substring "gguf" in its path (e.g., /home/user/gguf_models/flux-dev). We should defensively verify that the path is not an existing local directory before checking for the "gguf" substring.
| if name.endswith(".gguf") or "gguf" in name: | |
| if name.endswith(".gguf") or (not os.path.isdir(base_model) and "gguf" in name): |
| repo = (base_model or "").strip() | ||
| # Only remote 'org/name' repos are gated; skip local paths and single-file names. | ||
| if ( | ||
| not repo | ||
| or repo.count("/") != 1 | ||
| or repo.startswith((".", "/", "~")) | ||
| or repo.endswith(".gguf") |
There was a problem hiding this comment.
If hf_token contains whitespace or is empty, the preflight check might send a malformed Authorization header, causing Hugging Face to return a 401 Unauthorized error even for public repositories. We should sanitize the token first. Additionally, we can check if the path is an existing local directory to avoid unnecessary network requests for local paths.
repo = (base_model or "").strip()
# Only remote 'org/name' repos are gated; skip local paths and single-file names.
if not repo or repo.count("/") != 1 or repo.startswith((".", "/", "~")) or repo.endswith(".gguf") or Path(repo).is_dir():
return
url = f"https://huggingface.co/{repo}/resolve/main/model_index.json"
token = hf_token.strip() if isinstance(hf_token, str) else hf_token
headers = {"Authorization": f"Bearer {token}"} if token else {}
req = urllib.request.Request(url, method = "HEAD", headers = headers)| ) | ||
| if _check_stop(): | ||
| stopped = True | ||
| break | ||
|
|
||
| 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) |
There was a problem hiding this comment.
To guarantee that the massive text encoders (like T5-XXL) are completely evicted from VRAM, we should explicitly move them to the CPU before setting them to None. This prevents VRAM leaks in case there are reference cycles keeping the encoders alive in Python's garbage collector.
| ) | |
| if _check_stop(): | |
| stopped = True | |
| break | |
| 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) | |
| def _free_text_encoders(pipe) -> None: | |
| """Drop every text-encoder / tokenizer the pipeline holds, so the (large) encoders do | |
| not sit in VRAM during training. The embeddings are already precomputed.""" | |
| for attr in ("text_encoder", "text_encoder_2", "text_encoder_3", "tokenizer", | |
| "tokenizer_2", "tokenizer_3"): | |
| val = getattr(pipe, attr, None) | |
| if val is not None: | |
| try: | |
| if hasattr(val, "to"): | |
| val.to("cpu") | |
| setattr(pipe, attr, None) | |
| except Exception: # noqa: BLE001 | |
| pass |
| ), | ||
| } | ||
|
|
||
|
|
There was a problem hiding this comment.
Opening the image file without a context manager can leave the file descriptor open, potentially leading to resource leaks during long training runs with many images. We should use a with statement to guarantee the file is closed properly. Additionally, unconditionally convert the image to 'RGB' mode to prevent errors from unsupported modes when saving.
| with Image.open(path) as raw_img: | |
| img = ImageOps.exif_transpose(raw_img).convert("RGB") |
References
- When processing images from arbitrary sources with PIL, unconditionally convert them to 'RGB' mode to prevent errors from unsupported modes like CMYK, P, L, I, or F when saving to formats like PNG.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 83a5d52e7b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| i = rng.randrange(len(image_paths)) | ||
| px = _load_pixel_tensor( | ||
| image_paths[i], cfg.resolution, cfg.center_crop, cfg.random_flip, rng | ||
| ).unsqueeze(0).to(device) | ||
| latents = spec.encode_latents(vae, px).to(weight_dtype) |
There was a problem hiding this comment.
Honor train_batch_size in DiT batches
When a DiT run is started with train_batch_size > 1, this loop still samples exactly one image and adds a batch dimension with unsqueeze(0) for every accumulation microstep. That silently trains with batch size 1 while progress reports multiply throughput by cfg.train_batch_size, so larger-batch experiments are under-sampled and misreported instead of using the requested effective batch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: the DiT loop still samples one image per microstep, so train_batch_size above 1 only skews the throughput math. We will either honor the batch size or reject values above 1 up front.
| # The flow-matching + 4-bit path is bf16 throughout (fp32 on a CPU-only box, which is | ||
| # unsupported for real runs but keeps import/unit tests architecture-agnostic). | ||
| weight_dtype = torch.bfloat16 if device == "cuda" else torch.float32 | ||
| use_lora_targets = tuple(cfg.lora_target_modules) or spec.lora_targets |
There was a problem hiding this comment.
Use family defaults for DiT LoRA targets
For default DiT requests, config.normalized() always fills cfg.lora_target_modules with the generic DEFAULT_LORA_TARGETS, so this expression is always truthy and spec.lora_targets is never used. As a result FLUX.1 and Qwen-Image default training skips the added-kv projections (add_q_proj, add_k_proj, etc.) that the new family specs define, reducing the intended adapter coverage unless the caller manually passes those targets.
Useful? React with 👍 / 👎.
|
|
||
| pe, pooled, text_ids = embeds_batch | ||
| bsz, c, h, w = noisy.shape | ||
| packed = FluxPipeline._pack_latents(noisy, bsz, c, h, w) |
There was a problem hiding this comment.
Require 16-pixel multiples before packing DiT latents
For FLUX.1 (and the analogous Qwen packing path), any accepted resolution that is a multiple of 8 but not 16, such as 520, produces odd VAE latent dimensions (65x65) and then reaches this 2x2 pack, which cannot reshape the tensor. The shared config validator still allows those values, so these DiT jobs fail in the first training step instead of being rejected up front or rounded consistently with the inference pipeline.
Useful? React with 👍 / 👎.
|
|
||
| if cfg.max_grad_norm and cfg.max_grad_norm > 0: | ||
| torch.nn.utils.clip_grad_norm_(lora_params, cfg.max_grad_norm) | ||
| optimizer.step() |
There was a problem hiding this comment.
Advance the configured LR scheduler in DiT training
For DiT runs that set lr_scheduler or lr_warmup_steps, this loop only calls optimizer.step() and never constructs or steps a learning-rate scheduler, while progress reports the unchanged cfg.learning_rate. The same public diffusion config is honored by the SDXL trainer, so Qwen/FLUX/Z-Image experiments requesting warmup, cosine, or linear decay silently run at a constant LR.
Useful? React with 👍 / 👎.
| trainable = True, | ||
| train_base_repos = ("black-forest-labs/FLUX.1-dev",), |
There was a problem hiding this comment.
Restrict FLUX training to trusted dev base
Setting the whole flux.1 family trainable means DiffusionLoraConfig(...base_model='black-forest-labs/FLUX.1-schnell') now passes normalization, but the training subprocess later calls _assert_trusted_base_model, whose allowlist only includes black-forest-labs/flux.1-dev. In that scenario /diffusion/start has already freed resident GPU models before the child fails, so reject non-train_base_repos FLUX bases during the cheap preflight or allowlist the intended base.
Useful? React with 👍 / 👎.
| datasets_root = str(root), | ||
| outputs_root = str(outputs_root()), | ||
| datasets = found, | ||
| families = families, |
There was a problem hiding this comment.
Wire returned families into the train dialog
/diffusion/info now returns the trainable family metadata, but the inspected frontend still types DiffusionTrainingInfo with only datasets (studio/frontend/src/features/images/api.ts:332-336) and the base select maps only SDXL_BASES (studio/frontend/src/features/images/diffusion-train-dialog.tsx:276-280). In the production dialog the new FLUX/Qwen/Z choices, defaults, and VRAM notes are therefore invisible unless a user manually enters a custom base, so the advertised UI support for these trainers is not actually reachable.
Useful? React with 👍 / 👎.
# Conflicts: # studio/backend/core/inference/diffusion_families.py # studio/backend/core/inference/sd_cpp_backend.py # studio/backend/core/inference/sd_cpp_engine.py # studio/backend/core/training/diffusion_lora_trainer.py # studio/backend/core/training/diffusion_train_common.py # studio/backend/models/inference.py # studio/backend/models/training.py # studio/backend/routes/training.py # studio/backend/tests/test_diffusion_lora_trainer.py # studio/backend/tests/test_diffusion_training.py # studio/backend/tests/test_sd_cpp_install.py # studio/install_sd_cpp_prebuilt.py
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Flow-matching LoRA trainers for the three most requested DiT families, in one shared loop with per-family adapters. Stacked on the training platform PR.
What changed
diffusion_dit_trainer.py: one flow-matching training loop (logit-normal timestep sampling,noisy = (1-sigma)*latents + sigma*noise,target = noise - latents) parameterized per family. Family specifics live in adapter objects, not conditionals: FLUX packs latents 2x2 with img/txt ids and feeds the guidance-distilled embedding; Qwen-Image normalizes with the VAE latents mean/std and passesimg_shapes; Z-Image uses list I/O, the reversed(1000-t)/1000timestep convention, a negated prediction, and is locked to bf16.trainable,train_base_repos) andGET /api/train/diffusion/infonow returns per-family defaults and VRAM notes for the UI. Starting with a gated base (FLUX.1-dev) preflights token access and returns a clean 400 before any resident model is unloaded. GGUF repos are rejected as training bases.Verification
93 unit tests pass across the trainer suites. Live 30-step QLoRA smokes on a B200, each followed by loading the adapter into the matching base pipeline and generating: