Skip to content

Studio diffusion training: stream text encoders through the GPU when they do not fit (54-66% lower peak) - #18123

Merged
danielhanchen merged 4 commits into
mainfrom
studio-diffusion-train-te-stream
Nov 17, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-diffusion-train-te-stream

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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.

  • Qwen3-VL for Qwen-Image-2.1 needs 16.3 GiB of weights on the card.
  • UMT5-XXL for Wan2.2 needs 10.6 GiB.
  • Qwen3 for FLUX.2 klein 4B needs 7.5 GiB.

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:

  • Placement: the non-layer weights (embeddings, norms, any vision tower) go to the card. The decoder layers stay in one packed, page-locked host buffer. Each layer is copied in two layers ahead on a side stream and dropped after its forward.
  • Partial streaming: as many leading layers as fit stay resident.
  • Same embeddings: compute still runs on the card with the same weights and kernels, so caption embeddings are bitwise equal to the whole-module path.
  • Out of memory: the old whole-module move swallowed an out-of-memory error and left the encoder split across the card and the host. The run then died inside the embedding. That path is now only taken when the encoder fits.

UNSLOTH_DIFFUSION_TRAIN_TE_STREAM=auto (default) streams only when the encoders do not fit, and only as many layers as needed. on streams every layer, and off restores the whole-module move. With auto on 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.

run peak, GiB FLUX.2 klein base 4B Qwen-Image-2.1 Wan2.2 TI2V-5B
main 8.35 17.07 11.37
this PR, every layer streamed 3.81 (-54%) 5.73 (-66%) 3.95 (-65%)
main on a smaller card out of memory at 8 GiB out of memory at 14 GiB out of memory at 10 GiB
this PR on a smaller card (auto) fits in 6 GiB, peak 4.21 fits in 8 GiB, peak 6.14 fits in 8 GiB, peak 6.32
  • Smaller cards were simulated on the A100 by holding the rest of its memory in an unused allocation.

  • Training speed is unchanged:

    s/step main this PR
    klein 0.3845 to 0.3869 0.3844
    Qwen-Image-2.1 0.7446 to 0.7625 0.7415 to 0.7511
    Wan 0.842 to 0.863 0.8545 to 0.869
  • 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 (auto on the full A100), the encode peak and the losses match main.

Correctness

  • Caption embeddings: bitwise equal to main in every arm.
  • Deterministic mode: math attention with deterministic algorithms; 2 main arms, 2 arms with every layer streamed, and 1 arm capped at 8 GiB. Main against main is bit-identical. This PR against main is also bit-identical: every loss step matches, the LoRA weights have a max relative difference of 0.0, and the rendered sample has LPIPS 0.0.
  • Normal mode: loss deltas are 0.0002 to 0.0025, inside the main-against-main range of 0.0004 to 0.0028.

Testing

  • CPU: new test_diffusion_train_te_stream.py. It covers mode parsing, layer discovery, the resident-layer plan, auto streaming only the layers that do not fit, on streaming every layer, non-CUDA devices keeping the whole-module move, the kill switch and ROCm under auto, 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.
  • GPU: GPU-marked tests pass on B200, with tiny Qwen3, UMT5 and Qwen3-VL encoders streamed fully and partially; hidden states are bitwise equal. That run checks correctness only, not timing or memory.

Not covered

  • Measured on A100-40 only. Smaller cards were simulated; no L4, G4 or real 8 GB consumer-card runs.
  • The MiniMax-H3 and H3-Image trainers still move their whole encoder through their own code paths.
  • The other DiT families that share this function were not measured: FLUX.1, FLUX.2-dev, LTX-2, Z-Image, Qwen-Image, Krea 2 and FLUX.3.
  • ROCm and AMD hardware were not run; with auto, streaming does not engage there.
  • The per-family VRAM figures Studio advertises are unchanged.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T10:45:11.837356Z de0f1a0 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 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".

Comment on lines +365 to +367
streamer = TextEncoderStreamer(
enc, layers, list(range(keep, len(sizes))), device, pin_budget
)

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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: de0f1a0bb2

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

@danielhanchen
danielhanchen merged commit 86617bf into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-train-te-stream branch November 17, 2026 11:46
danielhanchen added a commit that referenced this pull request Nov 18, 2026
…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).
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…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()`.
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.

1 participant