Skip to content

Studio: add image generation, editing workflows and LoRA training with Unsloth GGUFs - #6763

Merged
danielhanchen merged 1285 commits into
mainfrom
image-generation
Aug 4, 2026
Merged

danielhanchen merged 1285 commits into
mainfrom
image-generation

Conversation

@oobabooga

@oobabooga oobabooga commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

Reposted version of #6658 where the branch lives in unslothai/unsloth instead of my fork, so all the phase-N follow-ups can target the PR branch directly. This branch is the integration point for the phased Images work; the phase PRs (#6768 through #6822) have been squash-merged here.

This PR adds a full Images page to Unsloth Studio: diffusion image generation, image editing workflows, multi-LoRA inference, and LoRA training, running Unsloth GGUFs alongside safetensors, bnb-4bit and FP8 checkpoints. All screenshots below are from a live Playwright run of this exact branch.

Create: text to image with Unsloth GGUFs

Create tab: Z-Image-Turbo GGUF loaded, 1024px generation with gallery

  • The model menu is the same picker used for chat: in the Images page it lists only image models (curated GGUF, bnb-4bit and FP8 variants per family), and the chat tab excludes them, so neither lists the other's models.
  • Only the transformer ships as a GGUF, so the matching VAE, text encoder(s) and scheduler are pulled from the model's base diffusers repo, resolved automatically from the GGUF repo's base_model tag.
  • The GPU is shared with the chat backend: loading an image model evicts the loaded chat model and vice versa, so only one sits in VRAM. Starting a training run unloads whichever image engine is resident.

Model picker with the curated image model catalog: GGUF, bnb-4bit, FP8 and SDXL entries

Model architectures

Detection is by architecture, so one entry covers every quant and variant:

Beyond GGUFs, the loader takes full diffusers pipelines (safetensors), unsloth bnb-4bit checkpoints, FP8 single-file checkpoints, and local models (a pipeline folder or a single .safetensors file); local diffusion checkpoints are tagged so the picker finds them.

Not integrated: ERNIE-Image (no single-file GGUF loader in diffusers yet) and FLUX.2-dev (its 48GB text encoder does not fit next to the transformer on one GPU). Both are still published GGUF repos, so the picker's Hub search surfaces them; loading ERNIE-Image is refused with the supported-family list rather than failing deep in the loader.

Two inference engines

  • Native stable-diffusion.cpp: a persistent sd-server keeps the model resident across generations (one load, many images), with prebuilt binaries for Linux, macOS and Windows so installation needs no compiler. GGUF LoRAs apply natively.
  • Diffusers: full pipelines, GGUF transformers inside diffusers pipelines, bnb-4bit and FP8 loads, ControlNet-guided generation, and every image-conditioned workflow.
  • An engine router picks the backend per model and format; both share the gallery, the LoRA picker and the settings panel.

Image workflows

Create, Transform (img2img with a strength slider), Inpaint (paint the mask in the browser), Extend (outpaint), Edit (instruction editing via Qwen-Image-Edit or FLUX.1-Kontext), Upscale (hires fix with scale and detail strength), and reference / multi-reference conditioning for FLUX.2-klein. Image-conditioned inputs are automatically resized to multiples the model accepts.

Transform workflow: source image, strength slider and img2img result

Inpaint with a painted mask, and Upscale Inpaint workflow: mask painted in the browser canvas Inpaint result: masked region replaced following the prompt Upscale workflow: hires fix with scale and detail strength

Video workflows

Text-to-video on its own /video page, sharing the loader, the GPU arbiter and the gallery with
Images. Image-conditioned video is NOT in this PR: VideoGenerateRequest carries no image field, so
the families that can do image-to-video run text-to-video here. (LTX-2 appears under Hugging Face's
image-to-video pipeline tag, which is why that tag is in the Video picker's task list; it is a
discovery tag, not a claim of i2v support.) Five families, all generated end to end on one B200 at
20 steps unless noted:

Family Clip Generation
Wan2.2-TI2V-5B bf16 1280x704, 41 frames 160.8 s
Wan2.2-TI2V-5B GGUF Q4_K_M 1280x704, 41 frames 95.1 s
Wan2.2-T2V-A14B (dual-expert MoE) 41 frames 240.5 s
HunyuanVideo-1.5 480p / 720p 49 frames 390.7 s / 681.0 s
LTX-2.3 distilled GGUF, with audio 768x512, 41 frames, 8 steps 15.0 s

LTX-2.3 generates synchronised audio: the sidecar reports has_audio: true and the WebM export
carries one vp9 video stream plus one opus audio stream at 48 kHz. Clips export as MP4, WebM or a
frame- and edge-capped GIF, and the gallery survives a restart with its recipe intact.

Performance and memory options

The Advanced panel exposes the load-time and run-time tuning, with safe defaults on Auto:

Advanced panel: speed mode, dtype, attention, memory mode, step cache, CPU offload

  • Dtype: run the GGUF as-is, or load the base model's transformer quantised to INT8 / FP8 / FP4 on low-precision tensor cores for a faster step at the cost of more VRAM. FP8 uses per-row scaling so consumer and datacenter GPUs both produce clean output.
  • Speed: regional torch.compile of the transformer blocks, TF32 matmul flags scoped to the generation (snapshot and restore, so nothing leaks into other Studio work), and an optional step cache.
  • Memory: auto, low-VRAM sequential offload, model offload, or max speed, with a defined precedence; the dense transformer is prefetched while the text encoder works.
  • Attention backend selection and CPU offload toggle.
  • Live download progress while the model and its base repo fetch, and a per-step progress bar with ETA while generating.

LoRAs at inference

  • A multi-LoRA picker with a per-adapter weight slider; adapters stack.
  • Works on both engines: native GGUF LoRA application through sd.cpp, PEFT adapters through diffusers.
  • Local adapters are auto-discovered from the Studio loras directory, and anything trained in the Train tab shows up immediately.

Train tab: LoRA training on your own images

The Images page has a Create | Train switch. Training covers the same families as inference: flux.1, qwen-image and z-image through a shared flow-matching DiT trainer, plus SDXL through a UNet trainer.

Train tab: model family, base model, dataset picker and example datasets

  • QLoRA by default: the base loads in 4-bit nf4 through bitsandbytes (measured z-image peaks: 4.69 GB at rank 16 / 768 px, 8.62 GB at rank 8 / 512 px with compile on, so budget by rank, resolution and compile rather than by family), with bf16 mixed precision, gradient checkpointing, 8-bit AdamW, and text embeddings precomputed once so the text encoders are freed before training starts.
  • Datasets: upload images from the browser, or one-click import a bundled example set (DreamBooth dog, Tuxemon, 1920 Tarot, Smithsonian butterflies, Nouns avatars). Captions come from metadata.jsonl, per-image .txt sidecars, or a DreamBooth instance prompt; a caption edited in the grid always wins.
  • Labeling grid: review and edit every caption inline before training.

Caption labeling grid on the DreamBooth dog dataset next to a completed run

  • Live charts: loss (raw and smoothed), learning rate and gradient norm (the pre-clip total norm, so spikes stay visible even when clipping flattens the update) stream in while the run progresses, next to step count, speed and peak VRAM. The run header switches to a clear completion state when the job finishes. Training runs in a spawned subprocess with an event queue, so a crash surfaces as an error instead of a hung UI, and non-finite metrics are nulled before they can break the JSON stream.

Live training: progress, loss, learning rate and gradient norm charts, speed and peak VRAM

  • Stop and resume UX: stop saves the partial adapter; run history persists across restarts with per-run configs and metric logs.
  • Deploy to Create: one click loads the training base with the fresh adapter and switches to the Create tab for immediate generation.

Completed run: final loss curve and the Adapter ready card with Deploy to Create

Create tab generating with the freshly trained LoRA applied

Other details

  • Disk-backed gallery with infinite scroll; every output embeds its generation settings (prompt, model, steps, seed) so any past image's recipe can be reloaded.
  • Reproducible seeds, resolution presets and aspect ratio controls, batch size and sequential runs.
  • The On Device tab lists cached diffusion models alongside chat models.
  • Trust-listed training bases and gated-repo detection with a clear error instead of a mid-run failure.

Testing

  • 800+ backend unit tests on this branch cover the engines, quant filters, trainers, training service and routes (trainer logic is unit-tested without a GPU via injected fakes).
  • The flows above were exercised end to end with Playwright against a live Studio running this branch, including a real 60-step z-image QLoRA run, deploy, and generation with the trained adapter.

Follow-up stack

Stacked on this PR and reviewed separately: #6838 (training performance: latent caching, batching, LR schedules, regional compile), #6839 (bf16 / int8 / fp8 training precisions), #6840 (Train tab layout restructure), #6843 (Krea 2), #6852 (mxfp8 and SDXL compile).

Training correctness: Qwen-Image flow shift

The DiT LoRA trainer now shifts Qwen-Image training sigmas to the inference distribution (flow_shift config: numeric linear shift or auto, which applies the scheduler's own exponential time_shift with mu = log 3 plus the shift_terminal 0.02 stretch). Previously training sampled unshifted sigmas: Qwen's scheduler config carries use_dynamic_shifting: true, so its static shift never applies at init and nothing supplied mu at train time. The official diffusers script has the same latent issue (its shift=3.0 init override is provably inert); kohya musubi-tuner (--discrete_flow_shift 2.2) and NVIDIA NeMo Automodel (2.23) both train shifted, and auto reproduces the exact inference distribution instead of an approximation. Verified with paired 80-step LoRA runs (identity vs auto, same seed/data): both stable, shifted run trains on 3x more high-noise draws (sigma > 0.7: 20 percent to 61 percent) with lower late-window loss. Other families are unchanged (their configs make identity correct; verified against kohya, ai-toolkit, and the official diffusers scripts per family). Optional per-sample CFG dropout and bell loss weighting are wired but default off.

Trainer efficiency: LoRA EMA, conditioning cache, quant config polish

Three further trainer upgrades, all behind config flags defaulting to current behavior:

  • ema_decay keeps an EMA shadow of the LoRA params only (warmup-ramped) and saves a second adapter under <out>/ema alongside the primary.
  • cond_cache_dir enables a persistent conditioning cache: text embeddings and VAE latent stats are pre-encoded once (safetensors, content-hash keyed, bit-identical on reload), so warm runs never load the VAE or text encoders. Measured on Qwen-Image nf4: the ~16 GB Qwen2.5-VL encoder stays off the GPU (verified with a loader tripwire), step-1 loss bit-identical, wall time for the smoke run halved.
  • Quant config tightening: nf4 now uses double quantization (~0.4 bits/param off the frozen-base scale metadata at no fidelity cost), fp8 training prefers the rowwise recipe (per-row scales confine DiT activation outliers), and the quantize filter enforces GEMM-tiling divisibility (16 for fp8/nvfp4, 32 for MX).

Aspect bucketing helpers and an FSDP2 multi-GPU design note (bf16/fp8 scope; int8 excluded due to DTensor-over-tensor-subclass sharding) ship alongside for follow-up work.

Prior work

The single-GPU handoff between chat and diffusion is adapted from #5754 by @danielhanchen. #5872 is a related WIP that also adds diffusion (including video).

Batched inference: throughput and accuracy validation

The inference path now does first-class batched generation, validated against serial engines on 32-image suites (16 out-of-distribution prompts x 2 seeds) per family on diffusers 0.39 / torch 2.10.

  • Batched multi-image generation. /images/generate accepts a prompts list (one image per prompt, plain txt2img) or a seeds list (one prompt, one image per seed); the legacy batch_size path now derives per-image seeds as base..base+n-1, matching the native sd.cpp engine and the gallery recipe replay. Every image gets its own torch.Generator, so any batch member regenerates alone from its recorded seed. The whole list runs as one forward by default, with OOM backoff that halves a failed chunk and retries (an explicit batch_size caps images per forward). Measured end to end on the same production GGUFs the sd.cpp gate scores: batched rendering is 10-22x faster than serial engines (FLUX.2-klein-4B 32-image suite 10.7 s vs 234 s; Qwen-Image-2512 20B 125 s vs 1230 s with cond+uncond CFG batching at batch 8 / 1024 px; batch 32 fits the 4-step 12B-class models), with LPIPS deltas within 0.002 of the serial renders, so the speedup is numerics-safe.

  • Conditioning cache on the inference path. UNSLOTH_DIFFUSION_COND_CACHE_DIR (the inference sibling of the trainers' cond_cache_dir, reusing the same PersistentConditioningCache store) wraps the loaded pipeline's encode_prompt: a repeated prompt returns the stored embeddings and never runs the text-encoder forward, so warm prompts keep the multi-GB encoders off the GPU under offload. Verified bit-identical on all three eval families (renders from cached embeddings match inline-encoded renders exactly); a fully warm Qwen-Image run loads the pipeline with no text encoder resident at all (8-18 s load, the ~7B-VL encoder's VRAM freed). Bypassed automatically while LoRA adapters are attached, since an adapter may target the text encoders.

  • Compile cache over GGUF and batched shapes. torch.compile mode="default" runs cleanly over diffusers' GGUF dequant path, but cold warmup at batched shapes is heavy: ~159 s first-pass wall on a 12B-class 4-step model at batch 32, up to ~655 s on the 20B CFG-batched model. The Mega-cache now fingerprints GGUF loads as their own key (quant="gguf"; previously a GGUF and a dense load of the same family shared a fingerprint) and registers every distinct (width, height, batch) chunk a batched call actually ran, OOM-backoff halves included, so a static-compile bundle grows to cover the batch sizes in use and those warmups are paid once ever.

  • GGUF container-prefix shim. sd.cpp-converted GGUFs prefix every tensor with model.diffusion_model.. diffusers' FLUX.1 converter strips it, but the FLUX.2 converter KeyErrors on the prefixed keys ('double_blocks.0.img_attn.norm.key_norm') and the Qwen-Image mapping is an identity, so the model silently stays on meta and .to("cuda") dies with "Cannot copy out of meta tensor". The GGUF load path now wraps the single-file converter to strip the prefix when present, a no-op for clean checkpoints, so both families load directly.

  • Sigma-table accuracy validation (no code change). The cross-engine eval also validates the flow-shift handling this PR ships: rendering Qwen-Image-2512 with the trainer's sigma table (pure linear shift 3, no terminal stretch) closes the LPIPS gap to sd.cpp to -0.0035, versus -0.0149 for a naively pinned FlowMatchEulerDiscreteScheduler(shift=3.0). The existing shift logic is the more faithful match to the reference engine.

Covered by new CPU unit tests (batch planning and validation, per-image seed reproducibility, OOM backoff, cond-cache reuse/bypass and list-slot round-trip, batch-dimension compile-cache keys) on top of the existing suite, plus a GPU smoke through the Studio backend on a Z-Image-Turbo Q4_K GGUF: batch 4 with seeds [1234, 777, 1234, 777] rendered in one forward (9.3 s first pass with the compiled dequant, 3.0 s warm), repeated seeds produced bit-identical images, different seeds produced clearly distinct images (mean abs pixel delta 40.8), and a warm repeat served the prompt from the conditioning cache with bit-identical outputs.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a local text-to-image diffusion backend, a single-GPU arbiter to manage VRAM allocation between chat and image generation, and a disk-backed image gallery that embeds generation recipes directly into PNG files. It also adds corresponding API routes, model filtering by task, and a frontend UI page for image generation. The review feedback highlights several improvement opportunities: deduplicating hardlinked files in the Hugging Face cache size calculation, sanitizing empty or whitespace-only Hugging Face tokens to prevent authentication failures, using time.monotonic() instead of time.time() for stable ETA measurements, and moving hardcoded English strings in the frontend to translation files to maintain internationalization standards.

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.

Comment on lines +322 to +335
def _cache_bytes(repo_id: str) -> int:
from huggingface_hub import constants

blobs = Path(constants.HF_HUB_CACHE) / f"models--{repo_id.replace('/', '--')}" / "blobs"
total = 0
try:
for entry in blobs.iterdir():
try:
total += entry.stat().st_size
except OSError:
continue # broken symlink / unreadable
except OSError:
return 0 # repo not in cache yet
return total

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When calculating the total size of files in a Hugging Face cache repository, we should deduplicate by blob_path (resolving symlinks to their real paths) to accurately account for hardlinked files shared across revisions and avoid double-counting. Additionally, on case-sensitive filesystems, we should perform a case-insensitive fallback search in the cache directory if the direct path does not exist, without performing redundant case-sensitive prefix checks.

    @staticmethod
    def _cache_bytes(repo_id: str) -> int:
        from huggingface_hub import constants

        cache_dir = Path(constants.HF_HUB_CACHE)
        folder_name = f"models--{repo_id.replace('/', '--')}"
        repo_path = cache_dir / folder_name

        if not repo_path.exists():
            # Fallback to case-insensitive match on case-sensitive filesystems
            target_lower = folder_name.lower()
            try:
                for entry in cache_dir.iterdir():
                    if entry.name.lower() == target_lower:
                        repo_path = entry
                        break
            except OSError:
                pass

        # Deduplicate by blob_path to accurately account for hardlinked files shared across revisions
        seen_blobs = set()
        total = 0
        try:
            snapshots_dir = repo_path / "snapshots"
            if snapshots_dir.exists():
                for snapshot in snapshots_dir.iterdir():
                    if snapshot.is_dir():
                        for file in snapshot.rglob("*"):
                            try:
                                # resolve() gives the canonical path to the blob
                                real_path = file.resolve()
                                if real_path.is_file() and real_path not in seen_blobs:
                                    seen_blobs.add(real_path)
                                    total += real_path.stat().st_size
                            except OSError:
                                continue
        except OSError:
            return 0
        return total
References
  1. When calculating the total size of files in a Hugging Face cache repository, deduplicate by blob_path to accurately account for hardlinked files shared across revisions.
  2. Avoid redundant case-sensitive prefix checks (like startswith(prefix)) after already performing a case-insensitive full-name match, as it can incorrectly reject mixed-case or capitalized directories (e.g., Models--Org--Repo).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blobs/ is already the deduplicated store; snapshots/ entries are symlinks into it, so summing blobs does not double count.

Comment on lines +187 to +200
def begin_load(
self,
repo_id: str,
*,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
hf_token: Optional[str] = None,
cpu_offload: bool = False,
) -> dict[str, Any]:
"""Validate, then run the (slow) load on a daemon thread. Returns at once."""
fam = self.validate_load(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If hf_token is passed as an empty or whitespace-only string from the client, passing it directly to Hugging Face Hub functions can cause authentication failures (401 Unauthorized) even for public repositories. We should sanitize hf_token to None if it is empty or whitespace-only.

Suggested change
def begin_load(
self,
repo_id: str,
*,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
hf_token: Optional[str] = None,
cpu_offload: bool = False,
) -> dict[str, Any]:
"""Validate, then run the (slow) load on a daemon thread. Returns at once."""
fam = self.validate_load(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)
def begin_load(
self,
repo_id: str,
*,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
hf_token: Optional[str] = None,
cpu_offload: bool = False,
) -> dict[str, Any]:
"""Validate, then run the (slow) load on a daemon thread. Returns at once."""
fam = self.validate_load(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)
if hf_token:
hf_token = hf_token.strip() or None

Comment on lines +339 to +354
def load_pipeline(
self,
repo_id: str,
*,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
hf_token: Optional[str] = None,
cpu_offload: bool = False,
_load_token: Optional[int] = None,
) -> dict[str, Any]:
import diffusers

fam = self.validate_load(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similarly to begin_load, we should sanitize hf_token to None if it is empty or whitespace-only to prevent authentication failures on public repositories.

Suggested change
def load_pipeline(
self,
repo_id: str,
*,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
hf_token: Optional[str] = None,
cpu_offload: bool = False,
_load_token: Optional[int] = None,
) -> dict[str, Any]:
import diffusers
fam = self.validate_load(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)
def load_pipeline(
self,
repo_id: str,
*,
gguf_filename: Optional[str] = None,
base_repo: Optional[str] = None,
family_override: Optional[str] = None,
hf_token: Optional[str] = None,
cpu_offload: bool = False,
_load_token: Optional[int] = None,
) -> dict[str, Any]:
import diffusers
if hf_token:
hf_token = hf_token.strip() or None
fam = self.validate_load(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)

Comment on lines +463 to +469
def _on_step(pipe, step_index, timestep, callback_kwargs):
now = time.time()
gen.step = step_index + 1
if gen.first_step_at == 0.0:
gen.first_step_at = now
gen.eta_seconds = _estimate_eta(gen.total_steps, gen.step, gen.first_step_at, now)
return callback_kwargs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For measuring step durations and calculating the ETA, time.monotonic() should be used instead of time.time(). time.time() is subject to system clock adjustments (e.g., NTP syncs), which can cause the clock to go backwards or jump, leading to incorrect or negative ETA values. time.monotonic() is guaranteed to be monotonic and is the standard Python best practice for measuring intervals.

Suggested change
def _on_step(pipe, step_index, timestep, callback_kwargs):
now = time.time()
gen.step = step_index + 1
if gen.first_step_at == 0.0:
gen.first_step_at = now
gen.eta_seconds = _estimate_eta(gen.total_steps, gen.step, gen.first_step_at, now)
return callback_kwargs
def _on_step(pipe, step_index, timestep, callback_kwargs):
now = time.monotonic()
gen.step = step_index + 1
if gen.first_step_at == 0.0:
gen.first_step_at = now
gen.eta_seconds = _estimate_eta(gen.total_steps, gen.step, gen.first_step_at, now)
return callback_kwargs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed on the branch.

Comment on lines +394 to +396
const [prompt, setPrompt] = useState(
"a tiny ginger sloth coding in a sunlit treehouse, photorealistic",
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The new ImagesPage component contains many hardcoded English strings for UI labels, placeholders, tooltips, and toast messages. To maintain the project's internationalization (i18n) standards (as seen in en.ts and zh-CN.ts), these strings should be moved to the translation files and retrieved using the useTranslation hook.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@oobabooga

Copy link
Copy Markdown
Member Author

This commit fixes the fp8 text-encoder quant from this PR. It loads and reports success, then crashes on the first generation for two of the four families (FLUX.1 / T5 and FLUX.2-klein / Qwen3). The crash is at generation, not load, and the tests stub torch, so it slipped through. I only caught it running each model live.

Both crashes are the same shape: a module that has to stay dense gets fp8'd by diffusers' layerwise casting, then leaks fp8 into an op that can't take it. T5 keeps wo in fp32 (transformers#20287) and reads its weight dtype before the upcast hook fires. Qwen3 ties lm_head to embed_tokens, so fp8'ing lm_head drags the shared embedding to fp8.

The fix keys off the model's own signals rather than hardcoding per model: skip encoder._keep_in_fp32_modules, and skip a tied output projection. Verified live on all four families, no regression, output stays faithful (same-seed PSNR about 27 dB FLUX.1, 23 dB klein). Regression tests added.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a local diffusion (text-to-image) backend for Studio, supporting both a PyTorch-based engine (with optional dynamic quantization, attention backend selection, and step caching) and a native stable-diffusion.cpp engine for CPU/MPS systems. It also adds memory planning, an on-disk image gallery, and a GPU arbiter to coordinate VRAM between chat and diffusion. The review feedback highlights several critical improvements: sanitizing hf_token to prevent Hugging Face API client errors, using get_active_diffusion_engine() in training and model deletion routes to correctly handle the active engine, avoiding raw substring checks in model family detection to prevent false positives, and defensively checking for the weight attribute on text embeddings to avoid potential AttributeError crashes.

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.

Comment on lines +307 to +309
) -> dict[str, Any]:
"""Validate, then run the (slow) load on a daemon thread. Returns at once."""
fam = self.validate_load_request(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The hf_token is not sanitized before being passed to Hugging Face API clients (like HfApi or hf_hub_download). If an empty or whitespace-only token is provided, these clients will throw an error instead of falling back to anonymous access. Please sanitize hf_token to ensure the application gracefully degrades to anonymous access.

        fam = self.validate_load_request(
            repo_id, gguf_filename = gguf_filename, family_override = family_override
        )
        hf_token = hf_token.strip() if hf_token and hf_token.strip() else None

Comment on lines +485 to +489
# Validate first (cheap, no torch/diffusers) so a direct call with a bad
# family fails with ValueError even in a no-diffusers runtime.
fam = self.validate_load_request(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Sanitize hf_token at the entry of load_pipeline as well, to prevent malformed or empty tokens from causing Hugging Face API client errors when load_pipeline is called directly.

Suggested change
# Validate first (cheap, no torch/diffusers) so a direct call with a bad
# family fails with ValueError even in a no-diffusers runtime.
fam = self.validate_load_request(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)
# Validate first (cheap, no torch/diffusers) so a direct call with a bad
# family fails with ValueError even in a no-diffusers runtime.
hf_token = hf_token.strip() if hf_token and hf_token.strip() else None
fam = self.validate_load_request(
repo_id, gguf_filename = gguf_filename, family_override = family_override
)

Comment thread studio/backend/routes/training.py Outdated
Comment on lines +375 to +382
from core.inference.diffusion import get_diffusion_backend

diffusion = get_diffusion_backend()
if diffusion.is_loaded:
logger.info(
"Unloading diffusion (Images) model to free GPU memory for training"
)
diffusion.unload()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In _free_vram_for_training, the code imports and unloads get_diffusion_backend() directly. However, if the active engine is sd_cpp (stable-diffusion.cpp) running on the GPU, this will fail to unload it, potentially leaving GPU memory occupied during training. Please use get_active_diffusion_engine() from core.inference.diffusion_engine_router to ensure the currently active engine is correctly unloaded.

Suggested change
from core.inference.diffusion import get_diffusion_backend
diffusion = get_diffusion_backend()
if diffusion.is_loaded:
logger.info(
"Unloading diffusion (Images) model to free GPU memory for training"
)
diffusion.unload()
from core.inference.diffusion_engine_router import get_active_diffusion_engine
diffusion = get_active_diffusion_engine()
if diffusion.is_loaded:
logger.info(
"Unloading diffusion (Images) model to free GPU memory for training"
)
diffusion.unload()

Comment thread studio/backend/routes/models.py Outdated
Comment on lines +3323 to +3324
from core.inference.diffusion import get_diffusion_backend
diffusion_status = get_diffusion_backend().status()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In delete_cached_model, the code imports and checks the status of get_diffusion_backend() directly. If the active engine is sd_cpp (stable-diffusion.cpp), get_diffusion_backend().status() will report that no model is loaded, allowing the user to delete the GGUF file while it is actively being used by the native engine. Please use get_active_diffusion_engine() from core.inference.diffusion_engine_router to ensure the delete guard correctly checks the active engine's status.

Suggested change
from core.inference.diffusion import get_diffusion_backend
diffusion_status = get_diffusion_backend().status()
from core.inference.diffusion_engine_router import get_active_diffusion_engine
diffusion_status = get_active_diffusion_engine().status()

Comment on lines +178 to +180
for fam in _FAMILIES:
if fam.name in needle or any(alias in needle for alias in fam.aliases):
return fam

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Statically detecting model families using simple raw substring checks (e.g., fam.name in needle) can lead to false positives (for example, matching 'reflux.1' or 'notz-image'). In accordance with the repository guidelines, please verify that the tag or family name appears as a whole segment using delimiters like dashes, underscores, dots, and slashes.

Suggested change
for fam in _FAMILIES:
if fam.name in needle or any(alias in needle for alias in fam.aliases):
return fam
for fam in _FAMILIES:
pattern = r"(?:^|[-_./\\])(?:" + "|".join(re.escape(x) for x in (fam.name,) + fam.aliases) + r")(?:$|[-_./\\])"
if re.search(pattern, needle):
return fam
References
  1. When statically detecting model types or tags (such as MLX) from repository IDs or names, avoid simple raw substring checks to prevent false positives (e.g., matching 'MLXmodel' or 'mlxify'). Instead, split the repository name into segments using delimiters like dashes, underscores, and dots, and verify if the tag appears as a whole segment, or check for specific organization prefixes.

)
out_emb = get_out() if callable(get_out) else None
in_emb = get_in() if callable(get_in) else None
if out_emb is not None and in_emb is not None and out_emb.weight is in_emb.weight:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent potential AttributeError crashes on custom or future text encoder architectures, defensively verify that both out_emb and in_emb have a weight attribute before accessing out_emb.weight.

    if (
        out_emb is not None
        and in_emb is not None
        and hasattr(out_emb, "weight")
        and hasattr(in_emb, "weight")
        and out_emb.weight is in_emb.weight
    ):

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca782d102e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

try:
# Snapshot taken: the local `state` ref keeps the pipe alive even if
# unload() nulls _state mid-denoise, so the call below needs no _lock.
generator = torch.Generator(device = state.device)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use a CPU generator for MPS diffusion

On Apple Silicon with the default engine policy, the router leaves MPS on the diffusers backend unless UNSLOTH_DIFFUSION_SD_CPP_MPS=1, so state.device can be "mps" here. Current PyTorch MPS builds do not support torch.Generator(device="mps"), so /images/generate fails before the pipeline is invoked for every MPS diffusers load; create a CPU generator for MPS (or otherwise seed the MPS RNG) instead of constructing it on state.device.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

torch 2.x supports MPS generators and Studio requires torch 2.x, so this constructor works on current builds.

pipe, plan, device = device, logger = logger
)

self._state = _LoadState(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recheck the load token before committing

If an unload or chat eviction arrives after the token check above but while the GGUF/base pipeline construction and placement are still running, it can bump _load_token and clear _state, yet this assignment still publishes the stale pipeline afterward. Fresh evidence is that the heavy build now runs outside _lock, but the state swap here is unconditional; re-check _load_token under _lock immediately before committing _state so a cancelled load cannot resurrect Images or overlap with a chat load.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pipeline build and the state commit both run under _lock (only the prefetch download is outside it), so an unload cannot interleave between the token check and this commit.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@oobabooga

oobabooga commented Jul 3, 2026 •

Copy link
Copy Markdown
Member Author

Changes made while consolidating the diffusion PRs (not in any single PR)

Fifteen diffusion PRs were squash-merged into image-generation bottom-up: #6768, #6769, #6772, #6771, #6773, #6787, #6788, #6789, #6791, #6792, #6794, #6819, #6820, #6821, #6822. Each merge re-based the PR on the current branch, and a few changes were made during that process that don't belong to any single PR. They're buried under the "merge image-generation into ..." commits, so documenting them here for transparency.

Native sd.cpp LoRA now works in server mode (new integration)

6771 added LoRA to the native engine while it still ran one image per sd-cli call (prompt <lora:...> tags resolved against a --lora-model-dir). 6768 later made a resident sd-server the default native path, and sd-server ignores prompt-embedded LoRA tags by design (stable-diffusion.cpp examples/server/api.md). So a straight merge would have silently dropped LoRA on the default native path.

_generate_server now stages the selected adapters into the server's --lora-model-dir scratch dir and passes them through the structured lora request field (path and multiplier). _generate_oneshot keeps 6771's original prompt-tag mechanism. Supporting changes: a SdCppServer.lora_dir property, a lora arg on build_img_gen_request, hf_token threaded into _SdState, and supports_lora in the native status. Verified live: a LoRA visibly changed the output on a native FLUX/Z-Image load, and with new backend dispatch tests.

Native engine reject guards restored

The image route passes controlnet (and img2img/inpaint/reference/upscale) to whichever engine is active. The native backend falls back to diffusers for those, so its generate() must reject them with a clear ValueError, not a TypeError into a 500. The ControlNet guard was restored during the 6773 merge, with supports_controlnet: false in the native status.

Dead code / merge artifacts removed

  • images-page.tsx: a stale <DiffusionTrainDialog> block and an unused AiMagicIcon import (leftovers from the dialog-to-tab move in 6822). They referenced removed symbols and broke tsc.
  • DiffusionStatusResponse: a duplicate supports_lora field.

Agent scratch stripped

Each branch carried about 170 working files under async_task_outputs/, logs/, plans/, temp/. These were removed so they don't land in image-generation.

Left as-is (flagged, not changed)

Two pre-existing UX issues in 6789 were left alone since they're the PR's own, not merge artifacts: a useCallback in handleGenerate that reads loraCapable without listing it (or status) as a dep, and a duplicate setLoras call in restoreSettings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a native stable-diffusion.cpp engine backend as a no-GPU tier alongside the existing diffusers backend, adding various performance optimizations such as eager fusions, GGUF compile-safe dequantization, attention backend selection, step caching, and pre-quantized transformer loading. It also adds support for flow-matching LoRA training for DiT image families and dataset management. The review feedback highlights several critical improvements: resolving Windows-specific path backslash issues in dataset discovery and image record generation by using .as_posix(), defensively checking for F.rms_norm to prevent crashes on older PyTorch versions, and ensuring the SdCppServer teardown path safely handles partially-constructed objects using getattr.

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.

for meta_name in ("metadata.jsonl", "captions.jsonl"):
meta_path = root / meta_name
if not meta_path.is_file():
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

On Windows, str(img.relative_to(root)) produces backslashes (e.g., images\\0.png), which will fail to match the forward-slashed keys (e.g., images/0.png) typically used in metadata.jsonl or captions.jsonl. Use .as_posix() to ensure a consistent, cross-platform forward-slash representation.

Suggested change
continue
caption = meta_caption.get(img.name) or meta_caption.get(img.relative_to(root).as_posix())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8ad8a58: the discover lookup now tries img.name first and falls back to img.relative_to(root).as_posix(), so the key uses forward slashes on Windows too.

if (
not repo
or repo.count("/") != 1
or repo.startswith((".", "/", "~"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

On Windows, str(image_path.relative_to(folder)) produces backslashes (e.g., images\\0.png), which will fail to match the forward-slashed keys (e.g., images/0.png) typically used in metadata.jsonl or captions.jsonl. Use .as_posix() to ensure a consistent, cross-platform forward-slash representation.

            caption = meta_caption.get(image_path.name) or meta_caption.get(image_path.relative_to(folder).as_posix())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8ad8a58: _image_record now falls back to image_path.relative_to(folder).as_posix() (guarded for images outside the folder), matching the forward-slashed metadata keys on every platform.

Comment on lines +137 to +138
if _NPU or self.bias is not None or _orig_rmsnorm_forward is None or len(tuple(self.dim)) != 1:
return _orig_rmsnorm_forward(self, hidden_states) # type: ignore[misc]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

To prevent potential AttributeError crashes on older PyTorch versions (prior to 2.4) where torch.nn.functional.rms_norm is not available, defensively check if F.rms_norm exists before attempting to use it, falling back to the original implementation if it is missing.

Suggested change
if _NPU or self.bias is not None or _orig_rmsnorm_forward is None or len(tuple(self.dim)) != 1:
return _orig_rmsnorm_forward(self, hidden_states) # type: ignore[misc]
if _NPU or self.bias is not None or _orig_rmsnorm_forward is None or len(tuple(self.dim)) != 1 or not hasattr(F, "rms_norm"):
return _orig_rmsnorm_forward(self, hidden_states) # type: ignore[misc]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8ad8a58, one level earlier than suggested: install_compile_safe_patches now skips the RMSNorm patch entirely at install time when torch.nn.functional has no rms_norm, so older torch keeps the stock eager implementation instead of gaining a patched module that would crash at forward time.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

install_patches already skips the RMSNorm patch when this torch has no F.rms_norm (the hasattr gate right above the capture), so the patched forward can never run on an older torch.

Comment on lines +315 to +321
self._client.close()
except Exception: # noqa: BLE001
pass
if self._scratch_dir:
shutil.rmtree(self._scratch_dir, ignore_errors = True)
self._scratch_dir = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To ensure that the teardown path tolerates partially-constructed objects (e.g., if __init__ raises an exception before all attributes are initialized, or when the object is instantiated via __new__ in tests), access instance attributes like _client and _scratch_dir using getattr(self, 'attribute_name', None) instead of direct access. This prevents potential AttributeError crashes during cleanup.

Suggested change
self._client.close()
except Exception: # noqa: BLE001
pass
if self._scratch_dir:
shutil.rmtree(self._scratch_dir, ignore_errors = True)
self._scratch_dir = None
try:
client = getattr(self, "_client", None)
if client is not None:
client.close()
except Exception: # noqa: BLE001
pass
scratch_dir = getattr(self, "_scratch_dir", None)
if scratch_dir:
shutil.rmtree(scratch_dir, ignore_errors = True)
self._scratch_dir = None
References
  1. Ensure that cleanup or teardown paths (such as process termination or object destruction) tolerate partially-constructed objects (e.g., when init raises an exception before all attributes are initialized, or when the object is instantiated via new in tests). Access instance attributes in these paths using getattr(self, 'attribute_name', None) instead of direct access to prevent AttributeError.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The teardown path cannot see a partially constructed object here: _client and _scratch_dir are assigned before the atexit.register(self.stop) call at the end of __init__, so if __init__ raises earlier the hook was never registered, and stop() already wraps the client close in try/except. We do not instantiate this class via __new__ in tests. Leaving as is.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_client and _scratch_dir are both assigned before atexit.register(self.stop) at the end of init, and _dispose already wraps the close in try/except, so a partially constructed instance can never reach this path.

@danielhanchen danielhanchen changed the title Studio: add image generation with Unsloth GGUFs Studio: add image generation, editing workflows and LoRA training with Unsloth GGUFs Jul 4, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

Images reads it off WORKFLOW_TABS, so it is the same icon the sidebar
submenu shows and it follows the active workflow. Video's heading is also
Create, so it takes the Create icon rather than the nav row's film slate.
@shimmyshimmer

Copy link
Copy Markdown
Member

Small one: the workflow icon now sits beside the heading on both pages.

Images reads it straight off WORKFLOW_TABS, so it is the same icon the sidebar submenu shows and it follows whichever workflow is active. Inpaint gets the paint roller, Transform the wand, Upscale the zoom, and so on. Nothing new to keep in sync.

Video's heading is also "Create", so it takes the Create icon rather than the film slate from its nav row. The sidebar already says Video; the heading names the workflow, and the same word should carry the same icon on both pages.

Both are sized to the existing h-9 heading row, so the two pages stay level with each other.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

danielhanchen and others added 2 commits August 4, 2026 14:47
DiffusionGenerateRequest already refuses a repeated adapter id, with a comment naming the
hazard: _resolve_lora_set suffixes colliding adapter names, so the same id resolves the SAME
adapter twice and set_adapters stacks both copies past the per-adapter weight bound.
DiffusionLoadRequest bounds only the list length, and it matters more there. Generation-time
stacking spoils one image; on the load path the adapters are baked into the quantized build
before compilation, so the unintended combination rides every image until a reload.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

1 similar comment
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

One conflict, in the zh-CN locale. Main retranslated sidebarMenu.description against the older
English wording; this branch replaced that wording and added a sidebarNav section above it. en.ts
merged cleanly to the branch's text for both keys, and the branch's zh-CN already matches it, so
the branch side is what keeps the two locales in sync.
The resident-GGUF fast path consults llama_backend.holds_no_vram before asserting CHAT ownership,
but two tests hand it a SimpleNamespace built before that attribute existed, so they raised
AttributeError and returned a 500. A real LlamaCppBackend exposes it as a property; the doubles
now carry it too. Product code is unchanged: these pass on main and were the branch breaking its
own test, not a defect in the guard.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: af73eb643e

ℹ️ 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".

The pinned tag was master-741-484baa4 from 1 July, while our mirror has published up to
master-809-eb7f35c on 2 August, so every auto-install was landing a build 68 releases behind.
Verified the target release before moving to it: not a draft or prerelease, the sha256 manifest
covers all five archives, the manifest names the upstream commit it was built from, and the
Linux archive carries both sd-cli and sd-server, each of which runs.

The mirror asset list in the test hardcoded the old tag as a string. It now derives from
DEFAULT_TAG, since a fixture that claims to describe what the CI publishes stops being true the
moment the pin moves.
@Hiddenath

Copy link
Copy Markdown

Is it possible to generate images and videos through API requests?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants