Repository navigation
Diffusion training base precision modes: bf16 speed mode (2.3-2.6x), int8, fp8, auto - #6839
Conversation
SDXL is the first U-Net family in the diffusion backend: its denoiser is
pipe.unet (UNet2DConditionModel), not a DiT pipe.transformer, and a single-file
.safetensors is the whole pipeline rather than a transformer-only file. The
backend previously assumed a DiT transformer everywhere, so add the two hooks a
U-Net family needs and register SDXL.
DiffusionFamily gains denoiser_attr ("transformer" for DiT, "unet" for SDXL) and
single_file_is_pipeline (SDXL loads a single file via pipeline_class.from_single_file
with the base repo as config, instead of transformer_class.from_single_file plus a
companion assembly). _align_vae_dtype now reads the denoiser generically so img2img
and inpaint keep the VAE and U-Net dtypes aligned.
The non-GGUF trust gate is extended with a short, exact-match, safetensors-only
allowlist of official base repos (the SDXL base/refiner and sdxl-turbo), because
SDXL ships only as a full pipeline and has no unsloth-hosted GGUF. Local paths stay
trusted as before; a random repo, even one that detects as SDXL, is still rejected.
The image-conditioned and ControlNet workflows are the standard SDXL pipelines,
built around the resident modules via from_pipe like every other family, so SDXL
gets txt2img, img2img, inpaint, outpaint, upscale, LoRA and ControlNet. There is no
native sd.cpp mapping yet, so the no-GPU route falls back to diffusers.
Frontend catalog gains SDXL Base 1.0 and SDXL Turbo entries with SDXL step/guidance
defaults (Turbo: few steps, no CFG; base: ~30 steps, real CFG).
Tests: new test_diffusion_sdxl.py (family shape, detection, trust allowlist, model
kind, U-Net VAE-dtype alignment, LoRA gate) plus loader-branch tests in
test_diffusion_backend.py (pipeline-kind from_pretrained, single-file whole-pipeline
from_single_file, allowlist accept/reject). Verified live on GPU: sdxl-turbo loads
both as a pipeline and as a single file and generates coherent txt2img + img2img.
The backend has always accepted a bare Hugging Face repo id (owner/name, or owner/name:weight-file.safetensors) as a LoRA, downloading and applying it. But the picker only rendered when the curated catalog had entries, and the catalog is empty, so there was no UI path to apply any LoRA. Show the LoRA section whenever the loaded model supports LoRA, and replace the curated-only dropdown with a text input: type a Hub repo id, or pick a discovered adapter from a datalist of suggestions when the catalog is populated. Also restore LoRAs when loading a recipe. restoreSettings now parses the recipe's "id:weight" strings (splitting on the last colon, since the id itself may contain one for a specific weight file) back into the selection, so replaying a saved image reproduces its adapters. The generate payload trims hand-typed ids and drops empty / zero-weight rows, and a model swap clears the selection (a LoRA is family-specific) without discarding a free-text pick that is not in the curated list.
First diffusion training path in Studio: train a LoRA on the SDXL U-Net from an image + caption dataset and export it as a diffusers .safetensors that the existing diffusion LoRA loader (and any diffusers pipeline) can load. core/training/diffusion_lora_trainer.py: - DiffusionLoraConfig with validation/defaults (rank, alpha, targets, lr, steps, grad accumulation, resolution, min-SNR gamma, gradient checkpointing, lr scheduler, seed, mixed precision). - discover_image_caption_pairs: captions from metadata.jsonl / captions.jsonl, per-image .txt/.caption sidecars, or a dreambooth instance_prompt fallback (pure, unit-tested). - run_diffusion_lora_training: the loop -- freeze base, PEFT-wrap the U-Net attention projections, VAE-encode (fp32 VAE to avoid the SDXL fp16 overflow), sample noise + timesteps, predict, MSE loss with optional min-SNR weighting (epsilon / v-prediction), AdamW + get_scheduler + grad accumulation + grad clipping, then export via save_lora_weights. Emits worker-protocol events (model_load_*, progress, complete) and polls should_stop for a clean stop with a partial save. - run_diffusion_training_process: mp.Queue subprocess adapter (event_queue / stop_queue), so the training worker can spawn it; plus a CLI entry point. Only SDXL (U-Net) is trained here; DiT families and the Studio UI form + route wiring are follow-ups. The trainer is decoupled and worker-ready. Tests: test_diffusion_lora_trainer.py covers caption discovery (metadata / sidecar / instance prompt / skip-uncaptioned / errors), config normalisation + validation, the SDXL add-time-ids, and the dict->config adapter. Verified live on GPU: a 60-step SDXL LoRA run lowers the loss, exports a ~45 MB adapter, and loading it back shifts generation from baseline (mean abs pixel diff ~55/255).
… compatibility) The Studio training pump reads 'learning_rate' from progress events; the diffusion trainer emitted 'lr'. Rename the field (and the CLI reader) so the trainer's events are directly consumable by the existing training status/SSE machinery when it is wired into the worker, without a translation shim.
…i/unsloth into diffusion-lora-training # Conflicts: # studio/backend/core/training/diffusion_lora_trainer.py
Make the SDXL LoRA trainer reachable from the app with a small, self-contained job service and JSON routes, deliberately separate from the LLM TrainingBackend (whose lifecycle -- LLM config build, per-run SQLite rows, matplotlib plots, transfer-to-chat- inference -- is text-training specific and would mis-handle a diffusion run). core/training/diffusion_training_service.py: DiffusionTrainingService runs one job at a time -- validate the config cheaply (before any spawn), spawn the trainer subprocess (spawn context, parent-lifetime bound), pump its events (model_load_* / progress / complete / error) into an in-memory status snapshot, and support a clean stop. The subprocess context and target are injectable so the full start -> pump -> status -> complete path is unit-tested without real multiprocessing or torch. routes/training.py: POST /api/train/diffusion/start (400 on a bad config, 409 when a job is already running), POST /api/train/diffusion/stop, GET /api/train/diffusion/status (JSON poll). models/training.py: DiffusionTrainingStartRequest + response schemas mirroring DiffusionLoraConfig, so model_dump() passes straight through. Tests: test_diffusion_training.py -- service happy path, bad-config-before-spawn, concurrent-job rejection, clean stop, crash-without-terminal-event, event transitions; plus route wiring via the FastAPI TestClient (start / 422 / 400 / 409 / status / stop) with a mocked service. The diffusion trainer's progress events already use the field names this path expects.
…ffusion-phase6-features
…diffusion-phase7-perf
…usion-phase8-quant
…fusion-phase9-prequant
…diffusion-phase10-attention
Surface the diffusion training API in the Images page. A "Train LoRA" button in the top bar opens a self-contained dialog to fine-tune an SDXL LoRA on a folder of images: pick the base model, dataset folder, output folder, an optional instance prompt, and the core hyperparameters (steps, rank, resolution, batch, learning rate), then Start. The dialog polls the training status while open and shows a progress bar, step count, live loss, and the saved adapter path, with a Stop button for a clean stop. The dialog is independent of the loaded generation model (training runs in its own subprocess), and prefills the base model with the loaded checkpoint when it is SDXL, else the SDXL base. api.ts gains startDiffusionTraining / stopDiffusionTraining / getDiffusionTrainingStatus plus their types, matching the /api/train/diffusion routes.
…o diffusion-phase11-consumer-int8
… into diffusion-phase12-fbcache
…diffusion-phase14-int8-modulation
…n' into diffusion-phase15-int8-prequant
… into diffusion-phase16-native-engine-routing
…routing' into diffusion-image-workflows
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 78a6ad3fff
ℹ️ 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".
| # load); SDXL uses its own mixed_precision path and ignores base_precision entirely, | ||
| # so the dense-mode gates (prequant base / non-bf16 compute) apply only to the DiT | ||
| # families. The mode-name validity check above still runs for every family. | ||
| if resolved_family != "sdxl" and base_precision in ("bf16", "int8", "fp8"): |
There was a problem hiding this comment.
When resolved_family == "qwen-image", this validation still accepts base_precision="fp8", but the existing quantization policy in core/inference/diffusion_transformer_quant.py explicitly denies Qwen+fp8 because measured on-the-fly fp8 produces black frames from Qwen activation outliers. The trainer then applies fp8 linears in every forward via _apply_fp8_training, so these runs can train against corrupted predictions instead of a valid Qwen base. Please reject/filter fp8 for Qwen here and from the advertised family modes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6bd3e87. normalized() now rejects fp8 for the Qwen-Image family (mirroring the inference _family_denied set) and family_train_infos() drops fp8 from the advertised modes, so an fp8 run cannot silently learn against a corrupted forward pass. int8 (per-token) stays allowed.
| if base_precision == "int8": | ||
| _int8_quantize_base(transformer) |
There was a problem hiding this comment.
Gate explicit int8 on functional torchao
When a direct or stale client explicitly requests base_precision="int8" on a host where only the Windows-ROCm torchao stub is installed, this path still runs even though /info and auto would exclude int8; the stubbed quantize_ is a no-op, leaving the dense bf16 transformer in memory while compile is disabled and the event reports int8. On a host with no torchao it fails here after model load. Please apply the same has_functional_torchao() gate to explicit int8 before reaching this call.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6bd3e87. _resolve_base_precision() now gates an explicit int8 on has_functional_torchao() (the same probe auto and /info already use), so a missing torchao or the Windows-ROCm stub fails fast instead of loading dense with compile disabled.
| if torch.cuda.is_available(): | ||
| modes.append("bf16") |
There was a problem hiding this comment.
Do not advertise dense modes without bf16 support
On CUDA devices that are not bf16-capable (for example T4/V100/RTX 20xx), this still advertises bf16 and recommends auto, but run_dit_lora_training immediately rejects those GPUs with torch.cuda.is_bf16_supported(). Because the route validates before freeing resident GPU workloads and the bf16 check only happens in the child, users can be offered a start option that evicts their loaded models and then fails. Gate these modes on the same bf16-support probe used by the trainer.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6bd3e87 on both facets: train_precision_modes() gates the dense modes on torch.cuda.is_bf16_supported() so /info offers only nf4 on a non-bf16 CUDA GPU, and start_diffusion_training preflights bf16 for the DiT families BEFORE _free_gpu_for_diffusion_training(). The preflight also covers nf4, since the DiT trainer requires bf16 unconditionally on CUDA, so no DiT start evicts resident models then fails.
| base_precision: Literal["nf4", "bf16", "int8", "fp8", "auto"] = Field( | ||
| "nf4", |
There was a problem hiding this comment.
Wire base_precision through Studio UI
This request field defaults to nf4, but the only Studio UI caller still cannot send anything else: I checked studio/frontend/src/features/images/api.ts and studio/frontend/src/features/images/train/diffusion-train-panel.tsx, and the request type/payload omit base_precision while the family info type also ignores the new precision fields. As a result, Train-tab users always start DiT jobs with the nf4 default even on machines where /info recommends auto, making the new bf16/int8/fp8 speed modes unreachable from the product UI unless they call the API manually.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed this is a real gap, but it is a UI-wiring enhancement rather than a correctness bug: the nf4 default is a safe, working choice and the API path already accepts base_precision. Tracking the frontend plumbing (api.ts payload, family-info precision fields, selector) separately so this PR stays focused on the backend precision gates.
… torchao, gate advertised dense modes + route on bf16 - normalized() + family_train_infos() mirror the inference fp8 deny for Qwen-Image (activation outliers exceed fp8's range and corrupt the trained result); int8 stays allowed and the UI no longer advertises fp8 for it. - _resolve_base_precision() gates an explicit int8 on a FUNCTIONAL torchao, the same gate auto and /info already apply, so a missing/stub torchao fails fast instead of silently loading dense with compile disabled. - train_precision_modes() gates the dense modes (bf16/int8/fp8/auto) on torch.cuda.is_bf16_supported(), so a non-bf16 CUDA GPU (T4/V100/RTX 20xx) is offered only nf4 instead of a start that evicts resident models and then fails. - start_diffusion_training preflights bf16 support for the DiT families BEFORE _free_gpu_for_diffusion_training(), so any DiT start (nf4 included, since the trainer requires bf16 unconditionally on CUDA) fails fast without eviction.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cc6d7c96a6
ℹ️ 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".
| _bf16_reason = bf16_unsupported_reason(normalized_cfg.resolved_family) | ||
| if _bf16_reason: | ||
| raise HTTPException(status_code = 400, detail = _bf16_reason) |
There was a problem hiding this comment.
Preflight explicit int8 before evicting models
When an API client explicitly sends base_precision="int8" on a DiT run but this host lacks a functional torchao install, normalized() accepts the request and the first torchao check is _resolve_base_precision() inside the trainer child. That happens only after this route has passed its preflight checks and later calls _free_gpu_for_diffusion_training(), so a stale/direct client can still unload the user's resident chat/Images model and then fail immediately. Please add the same has_functional_torchao() gate to the pre-free validation path for explicit int8 requests.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The start route now calls training_precision_preflight_error, which folds the explicit-int8 torchao check into the same preflight as the bf16 gate, so an int8 request on a host with a missing or stub torchao is rejected before _free_gpu_for_diffusion_training evicts resident workloads (rather than only in the trainer child, where its int8 base quantizer has no fallback).
| precision_modes: List[str] = Field(default_factory = list) | ||
| recommended_precision: str = "nf4" |
There was a problem hiding this comment.
Plumb precision modes through the Train UI
These new /diffusion/info fields never affect Studio starts today: the Train tab request body still sends only mixed_precision and no base_precision (studio/frontend/src/features/images/train/diffusion-train-panel.tsx lines 432-441), and its request type has no base_precision field (studio/frontend/src/features/images/api.ts lines 276-285). As a result, users launching from the UI always hit the backend default nf4 and cannot select the newly added bf16/int8/fp8/auto modes despite the backend advertising them. Please carry these fields into frontend state and include base_precision in the start request.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The base_precision/precision_modes fields are already returned by /info and consumed by the trainer; the missing piece is only the Train tab dropdown, which is a frontend UI enhancement outside this backend PR's scope. The backend contract (validation, preflight, family info) is complete and covered. Tracking the UI wiring separately.
| modes = ["nf4"] | ||
| recommended = "nf4" |
There was a problem hiding this comment.
Stop advertising DiT modes on non-bf16 GPUs
On a CUDA device without bf16 support (for example T4/V100), this still returns ['nf4'], and family_train_infos() exposes that as a selectable precision for the DiT families. The same commit's bf16_unsupported_reason() rejects every DiT family on that host before start, so /diffusion/info advertises an nf4 training option that always 400s. Please make the advertised DiT modes/families match the bf16 preflight gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. family_train_infos now empties precision_modes for any DiT family whose bf16 preflight would reject it, surfaces the reason in vram_note, drops supports_compile, and degrades recommended_precision to nf4. /info no longer advertises an nf4 DiT option the start route always 400s on a non-bf16 GPU.
…s-400 DiT modes on non-bf16 GPUs The start route preflight only rejected non-bf16 GPUs; an explicit int8 request on a host with a missing or stub torchao passed the preflight, evicted resident GPU workloads, then died in the trainer child (its int8 base quantizer has no fallback). Fold both gates into training_precision_preflight_error so int8-without-torchao fails fast before eviction. Also empty the advertised DiT precision_modes (and surface the reason in vram_note, drop compile) whenever the bf16 preflight would reject the family, so /info never offers an nf4 DiT option the route always 400s.
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa54a062ec
ℹ️ 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".
| True, description = "TF32 matmuls + cudnn autotuning (near-lossless speedup)" | ||
| ) | ||
| base_precision: Literal["nf4", "bf16", "int8", "fp8", "auto"] = Field( | ||
| "nf4", |
There was a problem hiding this comment.
Wire base_precision through the Train UI
For Studio Train starts from the UI, this default is always what the backend receives: a repo-wide search shows the frontend request type/body in studio/frontend/src/features/images/api.ts and studio/frontend/src/features/images/train/diffusion-train-panel.tsx were not extended to carry base_precision or render the new precision_modes. As a result, UI-launched DiT runs omit the field and stay on nf4 even when /info recommends auto, making the new bf16/int8/fp8 modes effectively API-only.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Re-raise of 3528399614: the backend is complete (start request accepts base_precision; /info returns precision_modes/recommended_precision/supports_compile per family; the generic dict path carries base_precision through, covered by tests). The only missing piece is a frontend Train-tab dropdown, which is an enhancement out of scope for this backend PR; with no selector the start request defaults to the safe nf4 floor and nothing breaks.
| if torchao_ok and (major, minor) >= (8, 9) and hasattr(torch, "float8_e4m3fn"): | ||
| modes.append("fp8") |
There was a problem hiding this comment.
Check the fp8 torchao API before advertising fp8
On an sm89+ bf16 CUDA host with a torchao build that has torchao.quantization/int8 symbols but lacks torchao.float8.Float8LinearConfig or convert_to_float8_training, this still advertises fp8 in /diffusion/info. The actual fp8 path imports those float8 symbols in _apply_fp8_training() and silently falls back to bf16 on failure, so clients can select a mode the machine cannot actually run as fp8.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The fp8 training path is explicitly non-fatal: _apply_fp8_training wraps the torchao.float8 import+convert in try/except and on any failure warns and downgrades base_precision to bf16 (diffusion_dit_trainer.py). That is why fp8 is gated differently from int8 (int8 has no fallback, so it gets the hard has_functional_torchao gate; fp8 does not, by design). And torchao.float8 and torchao.quantization co-ship in the same package (verified on torchao 0.17.0), with the only installed-but-nonfunctional case (the Windows-ROCm stub) already rejected by has_functional_torchao. Worst case is a bf16 fallback + a warning, not a crash.
| "vram_note": dit_block or _FAMILY_VRAM_NOTES.get(name, ""), | ||
| "precision_modes": fam_modes, | ||
| "recommended_precision": "nf4" if (not is_dit or dit_block) else dit_recommended, | ||
| "supports_compile": bool(is_dit and not dit_block), |
There was a problem hiding this comment.
Report compile support only when CUDA can use it
On CPU-only hosts, bf16_unsupported_reason() returns None, so every DiT family reports supports_compile: true here even though train_precision_modes() only returns nf4 and _should_compile() immediately returns false when device != "cuda". Any client that trusts this new per-machine flag will offer a compile option that the trainer can never apply in that environment.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The supports_compile/CUDA mismatch only occurs on a CPU-only host, where DiT training is entirely non-functional anyway (the CPU/fp32 path exists solely for import/unit tests; nf4 QLoRA needs bitsandbytes+CUDA). On every realistic GPU path the flag is accurate, and _should_compile guards the actual behavior (compile simply never engages on non-CUDA). Cosmetic hint on a host that cannot train DiTs.
| "defaults": train_defaults(name), | ||
| "vram_note": _FAMILY_VRAM_NOTES.get(name, ""), | ||
| "vram_note": dit_block or _FAMILY_VRAM_NOTES.get(name, ""), | ||
| "precision_modes": fam_modes, |
There was a problem hiding this comment.
Filter dense modes for prequant default bases
For Qwen-Image and Z-Image, /diffusion/info pairs a prequantized default_base with the full machine-level precision_modes, so it can advertise bf16/int8/fp8 for the very repo it tells clients to use by default. Those explicit dense modes are then rejected by DiffusionLoraConfig.normalized() because repo_is_prequantized(self.base_model) is true, so a client following this metadata can present choices that always 400 unless the user also switches to the dense base repo.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The advertised dense modes are not always-failing: each family's base_repos also contains its dense repo (Qwen/Qwen-Image, Tongyi-MAI/Z-Image-Turbo; flux.1 is dense-only), so every advertised dense mode has a valid target in the same payload, and the recommended auto/nf4 default resolves to nf4 at runtime for a prequant base (no failure). The only failing combo (prequant default base + explicit dense mode) is already fail-fast 400'd in normalized() before any GPU eviction. Filtering modes per selected repo is a frontend enhancement.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa54a062ec
ℹ️ 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".
| # base_precision modes this machine supports for the family (empty = the family has no | ||
| # precision selector, e.g. SDXL), plus the recommended pick and whether regional | ||
| # torch.compile applies. Defaults keep older backends' payloads valid. | ||
| precision_modes: List[str] = Field(default_factory = list) |
There was a problem hiding this comment.
Wire precision modes through the Train UI
The backend now exposes precision_modes/recommended_precision, but the only Studio consumer still drops them: studio/frontend/src/features/images/api.ts does not include these fields or base_precision in DiffusionTrainingStartRequest, and diffusion-train-panel.tsx starts training without sending base_precision. As a result, UI starts always fall back to the new request default nf4, so users cannot select the advertised bf16/int8/fp8/auto modes from /diffusion/info.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
As on 3528399614 / 3529384045: the backend is complete (the start request accepts base_precision; /info returns precision_modes/recommended_precision/supports_compile per family). The only missing piece is a frontend Train-tab dropdown, an enhancement out of scope for this backend PR; with no selector the request defaults to the safe nf4 floor and nothing breaks. Tracking the UI wiring separately.
| # corrupts must not offer it: with fp8 in the machine list, Qwen-Image drops fp8 while | ||
| # FLUX keeps it, so the UI never surfaces a mode normalized() would reject. | ||
| monkeypatch.setattr( | ||
| common, "train_precision_modes", lambda: (["nf4", "bf16", "int8", "fp8", "auto"], "auto") |
There was a problem hiding this comment.
Stabilize family-info tests across GPU types
On CUDA hosts without bf16 support (for example T4/V100), family_train_infos() also calls bf16_unsupported_reason() and empties the DiT modes, but this positive-path test only patches train_precision_modes; the assertions below therefore fail on that hardware despite the patched mode list. Patch bf16_unsupported_reason to return None in this test (and the later positive-path family-info test) to keep the unit tests hardware-independent.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. test_family_train_infos_carries_precision_fields and test_family_train_infos_drops_denied_fp8_for_qwen now monkeypatch bf16_unsupported_reason to None, so these positive-path assertions are deterministic across GPU types (a non-bf16 CUDA box would otherwise empty every DiT family's advertised modes), matching the sibling test_family_train_infos_empties_dit_modes_on_non_bf16 which pins it the other way.
| "vram_note": dit_block or _FAMILY_VRAM_NOTES.get(name, ""), | ||
| "precision_modes": fam_modes, | ||
| "recommended_precision": "nf4" if (not is_dit or dit_block) else dit_recommended, | ||
| "supports_compile": bool(is_dit and not dit_block), |
There was a problem hiding this comment.
Don’t advertise compile on CPU-only hosts
When /diffusion/info runs on a CPU-only host, bf16_unsupported_reason() returns None because CPU is exempt, so this line reports supports_compile=true for every DiT family even though _should_compile() immediately returns False unless device == "cuda". Any client that consumes the new field will enable regional compile on machines where the trainer can never use it; gate this on CUDA availability (or the same precision probe) instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
As noted last round (3529384065): the supports_compile/CUDA mismatch only occurs on a CPU-only host where DiT training is entirely non-functional anyway, supports_compile is a purely advisory /info field, and _should_compile device-gates the actual behavior (compile never runs on non-CUDA). With the dense-mode CUDA preflight added this round, a DiT start on a CPU-only host is now also rejected up front, making the advisory field moot there. Cosmetic.
| if ( | ||
| (resolved_family or "").strip().lower() in _DIT_TRAIN_FAMILIES | ||
| and (base_precision or "").strip().lower() == "int8" | ||
| and not has_functional_torchao() |
There was a problem hiding this comment.
Reject dense precision before teardown without CUDA
For a direct/stale client requesting a DiT with base_precision='bf16' or 'fp8' on a host where CUDA is unavailable, this preflight returns None: bf16_unsupported_reason() exempts CPU-only hosts and the only explicit-mode check here is int8/torchao. The child later hits _resolve_base_precision(..., 'cpu') and raises only after start_diffusion_training() has called _free_gpu_for_diffusion_training(), so resident Images/chat models can be unloaded and the route can report a started job for a run that cannot execute. Add the CUDA-only dense-mode check here before teardown.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. training_precision_preflight_error now has the third gate mirroring _resolve_base_precision: a DiT family with a dense base_precision (bf16/int8/fp8) on a host where torch.cuda.is_available() is False is rejected before _free_gpu_for_diffusion_training evicts residents, rather than only in the child. bf16_unsupported_reason exempts CPU-only (the fp32 import/test fallback), which is exactly the gap this closes. nf4/auto and SDXL still pass. Covered by an added non-CUDA case in test_training_precision_preflight_error.
…abilize family-info tests The start-route preflight caught the bf16-GPU and int8-torchao requirements but not the dense precisions' CUDA requirement: on a GPU-less host bf16_unsupported_reason exempts CPU-only, so a bf16/fp8 (or int8-with-torchao) DiT request passed the preflight, evicted resident workloads, then raised only in the trainer child. Add the dense-mode CUDA gate mirroring _resolve_base_precision so the doomed run is rejected up front. Also pin bf16_unsupported_reason in the two positive-path family-info tests so they are deterministic across GPU types (a non-bf16 CUDA box would otherwise empty every DiT family's advertised modes).
|
@codex review |
1 similar comment
|
@codex review |
|
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. Chef's kiss. 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". |
Stacked on #6838. Adds the FP8/int8/bf16 base-precision investigation results as a
base_precisionconfig (nf4stays the untouched default), with per-machine gating advertised through/api/train/diffusion/info.Modes and measured results (B200, 40 steps, 512px FLUX / 768px Z-Image, batch 1)
autopicks it when it fitsThe nf4 story from #6838 still holds for low VRAM: batch 4 there gives 3-4x samples/s at the 4-bit memory floor. bf16+compile is the per-step speed lane when VRAM allows;
autoresolves from free VRAM measured before the load (dense-fits -> bf16, middle band -> int8, else nf4; prequant bnb repos always resolve nf4, and dense modes on them are rejected at validation with an actionable message).FP8 verdict (the investigation asked for)
torchao
convert_to_float8_trainingintegrates cleanly once ordered correctly (convert AFTERadd_adapter, filter excludinglora_modules /proj_out/ non-divisible-by-16 dims,pad_inner_dim), trains stably, and its adapters round-trip. But at LoRA-training shapes the dynamic-scaling overhead beats the fp8 tensor-core gains: consistently slower than compiled bf16 on the same GPU. It ships as an explicit opt-in;autonever picks it. int8 (torchao weight-only, the PEFT-attachable scheme) must quantize afteradd_adapter(peft 0.18's TorchaoLoraLinear is incompatible with the torchao 0.16 config API) and must run eager (inductor rejects the int8 subclass training graph with aliased outputs).Two crashes found and fixed
mha_graph.executefails and the CUDA context degrades into illegal memory accesses. Every dense FLUX mode crashed until the perf-flag guard pinned flash/mem-efficient SDPA for the run (mathematically equivalent backends, snapshot/restored on exit). The nf4 path had been escaping it by routing attention through bnb outputs.dynamic=True(the inference layer's proven default):dynamic=Falsespecialisation fused agemm_and_biasepilogue that failed withCUBLAS_STATUS_EXECUTION_FAILEDon the FLUX training graph, anddynamic=Trueis also outright faster (Z-Image 3.84 -> 6.38 steps/s).API surface
DiffusionLoraConfig.base_precision/ start-requestbase_precisionLiteral (defaultnf4)./infofamilies now carryprecision_modes(machine-probed: fp8 only listed on sm89+, everything but nf4 needs CUDA),recommended_precision, andsupports_compile, so the UI renders only what this box can run. SDXL advertises no selector (it keeps itsmixed_precisionlever).Verification
98 backend tests green (new
test_diffusion_base_precision.py: validation incl. prequant/dense conflicts, the pure auto-policy table, the fp8 module filter, compile gating per precision,/infofields, request models). Per-mode 40-step GPU runs on FLUX and Z-Image: loss means inside the nf4 envelope, no NaNs, and bf16-, fp8-, and int8-trained adapters all load and generate through the normal Images LoRA path.