Repository navigation
Studio diffusion training: stream text encoders through the GPU when they do not fit (54-66% lower peak) - #18123
Conversation
…they do not fit The conditioning phase moved each whole bf16 text encoder onto the card before encoding the captions. The encoder is larger than the nf4 training loop for every DiT family (Qwen3-VL 16.3 GiB for Qwen-Image-2.1, UMT5-XXL for Wan2.2 TI2V-5B, Qwen3 7.5 GiB for FLUX.2 klein 4B), so it set the run peak and an encoder bigger than free VRAM failed the run with an OOM (swallowed by the move, then raised inside the embedding). Encoders that do not fit now keep their decoder layers on the host in one packed, page-locked arena and stream them through the card two layers ahead on a side stream, keeping as many leading layers resident as free VRAM allows. Compute stays on the GPU with the same weights and kernels, so the caption embeddings are bit-identical. UNSLOTH_DIFFUSION_TRAIN_TE_STREAM=auto (default) | on | off.
… states are bit-identical
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9e4f9f81f4
ℹ️ 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".
| streamer = TextEncoderStreamer( | ||
| enc, layers, list(range(keep, len(sizes))), device, pin_budget | ||
| ) |
There was a problem hiding this comment.
Roll back partially initialized streamers before falling back
If streamer construction fails after packing the weights—for example, a CUDA OOM during the initial _arm() prefetch—the constructor has already replaced layer parameters with empty tensors and installed forward hooks. However, STREAMER_ATTR is only assigned after construction returns, so the exception handler cannot find this partially initialized streamer and never calls _unstream() on it. The caller then attempts the whole-module move with missing weights and live streaming hooks, rather than restoring the original encoder. Make initialization transactional so constructor failures restore the packed parameters and remove any installed hooks before taking the fallback path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in de0f1a0. TextEncoderStreamer construction is now transactional: every weight moved into the host arena is recorded as it is packed, and any exception after that point (packing, pinning, hook registration, or the first _arm() prefetch, e.g. a CUDA OOM) runs _rollback() before re-raising. Rollback removes the installed hooks, unpins the arena, and restores each packed parameter from its host copy, so the caller's whole-module fallback sees the original weights. Covered by test_a_streamer_that_fails_part_way_puts_every_weight_back, which fails on the previous head.
…y restores every weight and removes its hooks [skip ci]
|
@codex review |
|
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". |
…oom (20-42% faster per step, bit-identical in deterministic mode) (#18301) ## Summary Diffusion LoRA training now keeps block activations instead of recomputing them when the card has room. Since #18123 streams the text encoders, memory is no longer the limit on L4 or A100. The main cost left is the second forward that gradient checkpointing runs for every block. Time per step, compiled training (Studio's default for 500-step runs). Each cell is 3 interleaved fresh processes per arm on the same Colab VM: | Card | Family | main s/step | this PR s/step | Change | Blocks kept | |---|---|---|---|---:|---| | L4 | FLUX.2 klein 4B | 0.983 / 1.017 / 1.014 | 0.700 / 0.700 / 0.707 | -30.9% | 25 of 25 | | L4 | Z-Image | 2.637 / 2.620 / 2.625 | 1.805 / 1.802 / 1.801 | -31.4% | 34 of 34 | | L4 | Qwen-Image-2.1 | 3.011 / 3.016 / 3.003 | 2.381 / 2.399 / 2.394 | -20.5% | 22 of 32 | | L4 | Wan 2.2 TI2V-5B | 0.551 / 0.556 / 0.546 | 0.374 / 0.372 / 0.375 | -32.1% | 30 of 30 | | L4 | FLUX.3 Klein base | 1.986 / 1.963 / 2.015 | 1.385 / 1.378 / 1.371 | -30.6% | 38 of 38 | | A100-40 | FLUX.2 klein 4B | 0.233 / 0.231 / 0.231 | 0.164 / 0.163 / 0.165 | -29.2% | 25 of 25 | | A100-40 | Wan 2.2 TI2V-5B | 0.488 / 0.469 / 0.464 | 0.276 / 0.278 / 0.278 | -40.7% | 30 of 30 | | A100-40 | Qwen-Image-2.1 | 0.663 / 0.664 / 0.664 | 0.467 / 0.466 / 0.466 | -29.8% | 32 of 32 | | A100-40 | Z-Image | 0.572 / 0.571 / 0.570 | 0.400 / 0.400 / 0.401 | -29.9% | 34 of 34 | Eager training (runs under 200 steps) on L4: | Family | main s/step | this PR s/step | Change | |---|---|---|---:| | FLUX.2 klein 4B | 1.503 / 1.540 / 1.542 | 1.070 / 1.075 / 1.082 | -30.2% | | Wan 2.2 TI2V-5B | 0.866 / 0.881 / 0.875 | 0.520 / 0.509 / 0.504 | -41.8% | **Deterministic mode** (math attention, deterministic algorithms): losses, LoRA weights and the end-of-run sample are bit-identical to main for every family on both cards. ## How it works New `core/training/diffusion_gc_budget.py`, wired into `diffusion_dit_trainer.py`: 1. **Step 1** runs with every block checkpointed except the first block of each block type. That block's saved activations are measured. 2. **From step 2**, blocks keep their activations in order while they fit the budget. - The budget is (free memory + PyTorch's cached memory - step 1's peak - the optimizer state - max(2 GiB, 10% of the card)) x 0.85. - Bucketed runs scale the estimate to the largest bucket. 3. **On out-of-memory**, the plan switches off, gradients are zeroed, and the same step reruns from the inputs already drawn with every block checkpointed, with a warning. On klein and Wan on L4, with memory taken away right after the plan, loss and LoRA came out bit-identical to deterministic main. **Scope:** - It engages only on CUDA, and only on diffusers models whose checkpointing hook takes a custom function. That covers every DiT family here. - ROCm, XPU and CPU are unchanged, as are the `plain` and `partial` modes. The SDXL and MiniMax-H3 trainers are not touched. **Kill switch:** `UNSLOTH_DIFFUSION_GC_MODE=plain` restores the old behaviour. With it set, every L4 family ran at main's speed and peak. ## Memory This trades free VRAM for speed, so the training peak goes up on cards with room. Allocated training peak, GiB: | Card | Family | main | this PR | |---|---|---:|---:| | L4 | FLUX.2 klein 4B | 3.01 | 8.71 | | L4 | Z-Image | 4.55 | 13.68 | | L4 | Qwen-Image-2.1 | 5.70 | 16.91 | | L4 | Wan 2.2 TI2V-5B | 3.90 | 6.75 | | L4 | FLUX.3 Klein base | 6.23 | 16.68 | | A100-40 | Qwen-Image-2.1 | 5.70 | 21.50 | - **Reported peak:** the `peak_memory_gb` Studio shows rises to match. On L4, the whole Qwen-Image-2.1 and FLUX.3 runs, including the preview render, reached 21.7 of 22 GB. - **Requirements unchanged:** the advertised per-family VRAM requirements still hold, because tight cards keep full checkpointing. - **Other processes:** a process that grabs VRAM mid-run (for example a desktop compositor) only has the 2 GiB / 10% margin. If our process runs out it falls back safely, but the other process may not. ## Accuracy in normal mode bf16 attention backward is nondeterministic, so main differs from itself from run to run. Against that: - **Loss:** the largest loss difference against main stays inside the main-vs-main range for klein, Wan and FLUX.3. Z-Image and Qwen sit slightly above it, while their kill-switch arms reached similar values. - **Samples:** LPIPS against main is inside the main-vs-main and head-vs-head spread for every family. The deterministic bit-identity above is the stronger evidence. ## Testing - **New:** `tests/test_diffusion_gc_budget.py`, 19 CPU tests. They include LoRA gradients matching an uncheckpointed run in every state on a tiny Z-Image. - **Existing suites:** the DiT trainer and text-encoder streaming suites pass. After merging current main, the new file plus the DiT trainer tests give 243 passed, 17 skipped. - **Wider sweep:** `test_diffusion*` and `test_decision_training*` show the same failing test IDs on main and on this branch. They are environment failures in inference modules. ## Not covered - **T4:** main refuses DiT training on cards without native bf16, so no family runs there. This PR does not change that. - **Not run:** - FLUX.3 on A100, and the kill-switch and forced-fallback arms on A100 (Colab A100 VMs were killed three times). - G4 or 8 GB cards. - LTX-2, MiniMax-H3 and H3-Image. - More than 12 steps, bucketing, gradient accumulation above 1, or mid-run previews on GPU. - ROCm, XPU and Windows (the change does not engage there).
…type and message only (#18567) #18123 added text-encoder layer streaming for DiT training captioning. When the streaming setup fails, `place_text_encoders` undoes any half-streamed encoder and lets the caller move the encoders whole, but first it stores the exception object in the module global `diffusion_te_stream.LAST_ERROR`. The exception's traceback keeps the placement frame alive, and that frame references the training pipeline, the candidate encoders and, when the streamer constructor failed, its partially built state (the host arena). So after one failed setup, the pipeline and those host / GPU buffers stay referenced for the life of the worker, even once training releases its own references. Nothing reads the object itself: `LAST_ERROR` is only a diagnostic. ## Change `LAST_ERROR` now holds `"Type: message"` (a plain string) instead of the exception. The status a reader would need is still there. The traceback, its frames and anything they reference are dropped when the handler returns. Nothing else changes: the fallback, the undo of a half-streamed encoder and the return value stay the same. ## Tests `test_a_failed_setup_records_the_error_without_keeping_the_pipeline_alive` makes the streamer constructor allocate a buffer and then raise through the real `place_text_encoders` entry point. It checks that the error type and message are recorded, then drops the last caller reference to the pipeline, runs `gc.collect()`, and checks that the pipeline and encoder are freed. On main it fails because the pipeline is still alive through `LAST_ERROR`. With this change it passes. `tests/test_diffusion_train_te_stream.py`: main 13 passed, 2 skipped (CUDA) plus the new test failing. Head: 14 passed, 2 skipped. ## Not proven here The test is CPU-only and uses a fake streamer. The real CUDA arena release after a failed setup (memory returned to the allocator / unpinned) was not measured on a GPU. That would need a run that injects a failure into `TextEncoderStreamer` on a CUDA card and compares `torch.cuda.memory_allocated()` and the pinned host total before and after `gc.collect()`.
Summary
The VRAM peak of a Studio DiT LoRA training run is not the training loop. It comes earlier: caption encoding moves the whole bf16 text encoder onto the card, so the encoder decides whether a run fits.
The nf4 training loop that follows peaks at 3 to 5 GiB.
When the encoders do not fit in free VRAM, they now stream their layers through the card:
UNSLOTH_DIFFUSION_TRAIN_TE_STREAM=auto(default) streams only when the encoders do not fit, and only as many layers as needed.onstreams every layer, andoffrestores the whole-module move. Withautoon ROCm, streaming never engages, so ROCm behaviour is unchanged.Results
Colab A100-40, Studio LoRA training, 512 px, 12 steps, nf4 (the default). Base and head ran one after another on the same card. Peaks are whole-device NVML readings and include about 0.4 GiB of CUDA context.
auto)Smaller cards were simulated on the A100 by holding the rest of its memory in an unused allocation.
Training speed is unchanged:
Caption encoding takes about 3.5 to 4.4 s longer on klein and about 11 s on Qwen-Image-2.1 for 9 prompts, but only when layers stream. Wan showed no change. Disk caching moved encode time between 7 and 55 s across base repeats, so these figures are approximate.
When the encoder fits (
autoon the full A100), the encode peak and the losses match main.Correctness
Testing
test_diffusion_train_te_stream.py. It covers mode parsing, layer discovery, the resident-layer plan,autostreaming only the layers that do not fit,onstreaming every layer, non-CUDA devices keeping the whole-module move, the kill switch and ROCm underauto, quantized and already-placed encoders being left alone, and the trainer skipping the whole-module move for a streamed encoder. They fail on main because the module does not exist there. The existing diffusion trainer suites pass: 539 passed.Not covered
auto, streaming does not engage there.