Repository navigation
Studio: add image generation, editing workflows and LoRA training with Unsloth GGUFs - #6763
Conversation
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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 totalReferences
- When calculating the total size of files in a Hugging Face cache repository, deduplicate by
blob_pathto accurately account for hardlinked files shared across revisions. - 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).
There was a problem hiding this comment.
blobs/ is already the deduplicated store; snapshots/ entries are symlinks into it, so summing blobs does not double count.
| 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 | ||
| ) |
There was a problem hiding this comment.
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.
| 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 |
| 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 | ||
| ) |
There was a problem hiding this comment.
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.
| 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 | |
| ) |
| 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 |
There was a problem hiding this comment.
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.
| 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 |
| const [prompt, setPrompt] = useState( | ||
| "a tiny ginger sloth coding in a sunlit treehouse, photorealistic", | ||
| ); |
There was a problem hiding this comment.
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.
|
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 The fix keys off the model's own signals rather than hardcoding per model: skip |
|
/gemini review |
There was a problem hiding this comment.
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.
| ) -> dict[str, Any]: | ||
| """Validate, then run the (slow) load on a daemon thread. Returns at once.""" | ||
| fam = self.validate_load_request( |
There was a problem hiding this comment.
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| # 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 | ||
| ) |
There was a problem hiding this comment.
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.
| # 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 | |
| ) |
| 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() |
There was a problem hiding this comment.
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.
| 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() |
| from core.inference.diffusion import get_diffusion_backend | ||
| diffusion_status = get_diffusion_backend().status() |
There was a problem hiding this comment.
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.
| 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() |
| for fam in _FAMILIES: | ||
| if fam.name in needle or any(alias in needle for alias in fam.aliases): | ||
| return fam |
There was a problem hiding this comment.
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.
| 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
- 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: |
There was a problem hiding this comment.
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
):There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
Changes made while consolidating the diffusion PRs (not in any single PR)Fifteen diffusion PRs were squash-merged into 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
Native engine reject guards restoredThe image route passes Dead code / merge artifacts removed
Agent scratch strippedEach branch carried about 170 working files under 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 |
|
/gemini review |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| continue | |
| caption = meta_caption.get(img.name) or meta_caption.get(img.relative_to(root).as_posix()) |
There was a problem hiding this comment.
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((".", "/", "~")) |
There was a problem hiding this comment.
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())There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| self._client.close() | ||
| except Exception: # noqa: BLE001 | ||
| pass | ||
| if self._scratch_dir: | ||
| shutil.rmtree(self._scratch_dir, ignore_errors = True) | ||
| self._scratch_dir = None | ||
|
|
There was a problem hiding this comment.
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.
| 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
- 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
_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.
|
/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.
|
Small one: the workflow icon now sits beside the heading on both pages. Images reads it straight off 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 |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
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.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
1 similar comment
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
@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.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
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.
|
Is it possible to generate images and videos through API requests? |
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
base_modeltag.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
sd-serverkeeps 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.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.
Inpaint with a painted mask, and Upscale
Video workflows
Text-to-video on its own
/videopage, sharing the loader, the GPU arbiter and the gallery withImages. Image-conditioned video is NOT in this PR:
VideoGenerateRequestcarries no image field, sothe families that can do image-to-video run text-to-video here. (LTX-2 appears under Hugging Face's
image-to-videopipeline tag, which is why that tag is in the Video picker's task list; it is adiscovery tag, not a claim of i2v support.) Five families, all generated end to end on one B200 at
20 steps unless noted:
LTX-2.3 generates synchronised audio: the sidecar reports
has_audio: trueand the WebM exportcarries 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:
torch.compileof 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.LoRAs at inference
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.
metadata.jsonl, per-image.txtsidecars, or a DreamBooth instance prompt; a caption edited in the grid always wins.Other details
Testing
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_shiftconfig: numeric linear shift orauto, which applies the scheduler's own exponentialtime_shiftwithmu = log 3plus theshift_terminal 0.02stretch). Previously training sampled unshifted sigmas: Qwen's scheduler config carriesuse_dynamic_shifting: true, so its staticshiftnever applies at init and nothing suppliedmuat train time. The official diffusers script has the same latent issue (itsshift=3.0init override is provably inert); kohya musubi-tuner (--discrete_flow_shift 2.2) and NVIDIA NeMo Automodel (2.23) both train shifted, andautoreproduces 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_decaykeeps an EMA shadow of the LoRA params only (warmup-ramped) and saves a second adapter under<out>/emaalongside the primary.cond_cache_direnables 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.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/generateaccepts apromptslist (one image per prompt, plain txt2img) or aseedslist (one prompt, one image per seed); the legacybatch_sizepath now derives per-image seeds asbase..base+n-1, matching the native sd.cpp engine and the gallery recipe replay. Every image gets its owntorch.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 explicitbatch_sizecaps 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 samePersistentConditioningCachestore) wraps the loaded pipeline'sencode_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.compilemode="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.