Skip to content

Studio diffusion: stream the LTX-2.5 encoder, cache and trim FLUX.3 prompt encodes - #16750

Merged
danielhanchen merged 8 commits into
mainfrom
studio-diffusion-encoder-memory
Nov 5, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-diffusion-encoder-memory

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Four prompt-encoder memory and latency fixes for Studio diffusion and video inference. Every changed path produces the same embeddings and pixels as before, bit for bit.

  1. LTX-2.5: stream the Gemma 4 encoder layer by layer when it cannot be onloaded whole (video_ltx25_te_worker.py). Before, when the card had no room for the whole encoder plus the encode margin, the worker ran the entire encode on the CPU.
  2. LTX-2.5: pass use_cache=False to the hidden-state forward (video_ltx25_te_worker.py). Before, every encode built a KV cache it never read.
  3. LTX-2.5: skip the identity repeat(1, 1, 1) copy of the packed prompt (video_ltx25.py).
  4. FLUX.3: route the modular text step through a facade encode_prompt (diffusion_flux3.py). This turns on the cross-render prompt cache and the dead-tail truncation for FLUX.3. Before, neither applied.

1. LTX-2.5 layer-streamed encode

What. _encode_on now picks a route with _encode_plan:

  • If the whole encoder fits (same check as _encode_device), it onloads the whole encoder, as before.
  • Otherwise, if the card fits the resident modules (embeddings, final norm, buffers) plus two decoder layers plus the same ENCODE_MARGIN_MIB, it keeps those resident for the encode. A pre-hook onloads each decoder layer right before it runs, and a post-hook puts the original host tensors back after it.
  • Otherwise it encodes on the CPU, as before.

More details:

  • Parameters keep their identity because only .data is swapped, so the tied head still shares the embedding weight.
  • Returning a layer to the host copies nothing back from the card.
  • Vision and audio towers stay on the host.
  • Modules that override _apply decline streaming. The int8 ConvRot Linear keeps its codes and scales as buffers, so int8 encoders can stream.
  • Resident encoders, MPS, and CPU are unchanged.
  • Kill switch: UNSLOTH_LTX25_TE_STREAM=0.

Why. On 16 to 24 GB cards, every uncached LTX-2.5 prompt paid a full 12B Gemma 4 forward on the CPU. The plan already prices the encoder as streamed on the group/streaming tiers. The worker was the only piece that could not stream.

For the real config (48 layers, 3840 hidden, 262k tied vocab), the streamed need is about 2 GB of embeddings + 2 layers (~0.9 GB) + the 4 GiB margin, roughly 7 GB. The whole encoder needs 23.9 GB + 4 GiB.

Evidence. Tiny random Gemma4Unified with LTX's layout (sliding + full layers, attention_k_eq_v, tied head), 8 layers, hidden 1024, vocab 65536, 1024 tokens with left padding. Run on an L4, torch 2.14.1, transformers 5.10.2 (the sidecar pin):

encode path device memory median time (3 reps) output
whole encoder already on card 373 MiB weights + 164 MiB peak 20.1 ms reference
streamed (new) 292 MiB peak, 8 MiB resident before 115.6 ms bitwise equal to whole-on-card
CPU (what base does when the whole encoder does not fit) 0 5792 ms CPU kernels
  • I also drove _encode_on with a load budget that fits the streamed need but not the whole one. It chose cuda:0 streamed, the output was bitwise equal to the whole-on-card encode, and every parameter was back on the host afterwards.

  • On a card too small for the whole encoder, base embeddings came from CPU kernels. Head embeddings are now exactly what the same card produces when the encoder fits whole. How far apart the two are, on the same tiny model (random weights, bf16, 1024 tokens, 324 real; A100 run):

    metric (GPU-streamed vs CPU bf16 packed embeddings) value
    relative Frobenius error, all 9 hidden states 13.9%
    mean abs error / mean abs value 5.8%
    max abs error (reference max abs 17.1, rms 2.14) 7.05 (12.3 on the L4 run)
    min per-token cosine similarity over real tokens 0.915
    relative error per hidden state, embeddings to last layer 0, 0.3%, 1.2%, 3.0%, 6.7%, 10.9%, 15.7%, 21.1%, 21.4%
    each bf16 path vs an fp32 CPU encode of the same weights GPU 24.0%, CPU 24.4%

    The gap grows layer by layer, as bf16 rounding differences compound through a random untrained stack. It stays below the error each bf16 path has against fp32 on its own, so the CPU encode was not the more accurate one. Real Gemma 4 weights were not run, so their gap is not measured here.

  • CPU parity (forced copies, transformers 5.10.2 and 5.14.1): bitwise equal. During each layer's forward only that layer is onloaded, all host storage is restored afterwards, and the hook count is unchanged.

2. use_cache=False in _pack_hidden_states

What / why. The LTX-2.5 encoder config sets use_cache: true, so Gemma4UnifiedModel.forward builds a DynamicCache, which stays alive through the hidden-state stacking. The helper does a single forward that reads only hidden states. The load-time dead-tail probe goes through the same helper, so it now matches.

Evidence.

  • Bitwise-equal packed states on CPU (transformers 5.10.2 and 5.14.1) and on the L4.
  • The returned cache goes from DynamicCache to None.
  • L4 peak during the encode: 186.1 to 164.0 MiB on the tiny model (8 layers x 1024 tokens).
  • For the real config, the KV payload is about 336 MiB at 1024 tokens.

3. Skip the identity repeat in the LTX-2.5 encode_prompt

What / why. With num_videos_per_prompt == 1, _one did .to(device, dtype) and then repeat(1, 1, 1), which made a second full copy (367.5 MiB at 1 x 1024 x 49*3840 bf16). Head skips the repeat when .to already made private, contiguous storage.

It keeps the repeat when .to is a no-op, because then the result would alias the client's cached tensor (CPU, same dtype). Counts above 1 are unchanged.

Evidence.

  • Bytes allocated inside the real encode_prompt (dispatch-mode count, LTX shape, one video): base 735 MiB (_to_copy + repeat), head 367.5 MiB.
  • L4: peak 736 to 368 MiB for upload + identity repeat vs upload alone.
  • The test checks that an in-place edit of the returned tensor cannot reach the cache when .to is a no-op.

4. FLUX.3 encode_prompt bridge

What. The facade gains encode_prompt(prompt, max_sequence_length, device, pad_multiple, hidden_states_layers), which calls the text step's own _get_qwen3_vl_prompt_embeds helper. When None, the pad multiple and layer selection default to the step's own values.

When the modular pipeline is built, the step's helper is routed through pipe.encode_prompt, but only for this pipe's own encoder and tokenizer. If a diffusers build's helper takes other arguments, the step stays unbridged and the probe declines, as today.

Why. Before, prompt_cache.install returned False for FLUX.3, so the cache was off and every render re-ran the Qwen3-VL encoder. truncate_text_encoders also declined ("encode_prompt cannot be called generically"), so each encode still computed:

  • the 151936-wide logits (23.2 MiB at the 80-token window, 2.3 GiB at 8192)
  • 4 of 36 decoder layers after hidden_states[32], which the step never reads

Evidence. diffusers 0.42.1 (the pin), transformers 5.5.0. Tiny random Qwen3-VL text encoder with 36 layers and the real 151936 vocab, tiny Flux3Transformer2DModel and AutoencoderKLFlux2. Both block graphs, renders: seed 0, seed 1, seed 0 again, then a new prompt:

base head
pixels, all 8 renders reference bitwise equal to base
encoder forwards per render, distilled 1, 1, 1, 1 1, 0, 0, 1
encoder forwards per render, base graph (CFG) 2, 2, 2, 2 2, 0, 0, 1 (the negative is cached too)
decoder layers run per encode 36 32
logits shape [1, 80, 151936] [1, 80, 0]

Tests

  • tests/test_video_ltx25.py, new tests:
    • no KV cache in the hidden-state encode
    • a streamed encode runs each layer onloaded alone, matches the plain encode bitwise, keeps the tie, and leaves towers on the host
    • routing on fake budgets: whole, streamed, CPU, unreadable reading, resident, MPS, kill switch, and an encoder with no stack
    • a streamed encode never moves the whole encoder
    • repeat skip with alias protection
  • tests/test_diffusion_flux3_encode_bridge.py, new:
    • the text step encodes through encode_prompt with unchanged arguments
    • a returning prompt skips the encoder once the prompt cache is on
    • a foreign encoder runs the step's own helper
    • the probe can call encode_prompt generically
    • an unknown helper signature stays unbridged
    • the installed diffusers step matches the bridge (runs under the 0.42.1 pin)
  • All 5 new LTX tests and 5 of the 6 bridge tests fail on base. The sixth bridge test is the upstream signature check, which only fails on base for the missing constant.
  • Related suites: test_video_ltx25*, test_diffusion_flux3*, test_flux3_*, test_diffusion_prompt_cache, test_diffusion_te_truncate, test_diffusion_text_encoder_trim, test_diffusion_cond_cache, test_diffusion_cond_blocks, test_diffusion_multistage, test_diffusion_vram_budget_workspaces, test_shared_memory_offload_keeps_the_prompt_cache.
    • Base: 733 passed, 9 failed.
    • Head: 738 passed, 9 failed. The failures are the same 9 test IDs on both sides: they come from the local diffusers 0.40 dev build vs the 0.42.1 pin.
    • Under the 0.42.1 pin, the FLUX.3 / truncate / prompt cache / cond blocks set passes in full on head (396 passed). Base fails the 5 bridge tests.

Not proven here

  • No real LTX-2.5 or FLUX.3 checkpoint was loaded. Real encode latency and peak VRAM on 16/24 GB cards are not measured. The streamed path's cost is one pageable host-to-device pass of the weights per uncached prompt (no prefetch overlap yet), compared against a full CPU forward.
  • ROCm, XPU, MPS and Windows were not run. XPU takes the same streamed branch when its free memory or budget can be read. MPS and CPU never stream.
  • transformers 5.10.2 and 5.14.1 were checked for Gemma 4. The FLUX.3 bridge was checked on diffusers 0.42.1 only.
  • The FLUX.3 encoder speedup is shown as operation counts (logits width, layers run, encoder forwards), not wall time on a real encoder.

…not onload whole

The encoder worker onloaded the whole encoder for an encode when the card had room for
it plus the encode margin, and otherwise ran the entire encode on the CPU (a 12B forward
per uncached prompt on 16-24 GB cards). It now keeps the embeddings, final norm and
buffers on the card for the encode and onloads one decoder layer at a time, putting the
host tensors back after each layer (no device-to-host copy), when the resident modules
plus two layers and the same margin fit. Whole onload still wins when it fits; the CPU
path stays when neither fits. Vision and audio towers stay on the host.
UNSLOTH_LTX25_TE_STREAM=0 turns it off.

Also pass use_cache=False to the hidden-state forward: the encoder config sets use_cache,
so every encode built a DynamicCache it never read and held it through the stacking.
With one video per prompt, encode_prompt's repeat(1, 1, 1) copied the packed embeddings
(367.5 MiB at 1024 x 49 x 3840 bf16) right after the .to that already made a private
device copy. Skip it when .to moved or cast; keep it when .to is a no-op and would alias
the client's cached tensor.
The FLUX.3 facade had no encode_prompt, so the cross-render prompt cache never installed
and the dead-tail probe declined: every render re-ran the Qwen3-VL encoder, including the
151936-wide logits projection and the four decoder layers after hidden_states[32] that
the text step never reads. The facade now has an encode_prompt that calls the text step's
own helper, and the step's helper is routed through it, so both engage as for a classic
pipeline. Outputs are bit-identical.
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T10:43:11.856751Z a3ea67e 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.

@danielhanchen danielhanchen self-assigned this Nov 5, 2026
[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 284b518946

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: a3ea67ebbf

ℹ️ 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 added a commit that referenced this pull request Nov 5, 2026
…ed-load retry (#16768)

## Summary

`Chat UI Tests (extra)` fails on unrelated PRs several times a day at
the same place, for example #16722, #16741 and the staging run for
#16750:

```
File "tests/studio/playwright_multi_account.py", line 173, in run
    open_login(page)
File "tests/studio/playwright_multi_account.py", line 67, in open_login
    page.goto(url)
playwright._impl._errors.TimeoutError: Page.goto: Timeout 30000ms exceeded.
Call log:
  - navigating to "http://127.0.0.1:18894/login", waiting until "load"
```

#16437 added a recorded retry for exactly this stalled `/login` load,
but it never runs in these failures. None of the failing logs print its
`WARN: /login did not fire load ...` line, and the whole step lasts
about 33 s, i.e. one 30 s timeout. `open_login` gives aborts and
timeouts one shared two-attempt budget: right after a log-out the app's
own 401 redirect (`redirectToAuth`) aborts the first `goto` with
`ERR_ABORTED`, which spends attempt 1, and the stalled load then happens
on attempt 2, where it is fatal.

## Change

`tests/studio/playwright_multi_account.py`, `open_login` only:

- Aborts and timeouts each get their own single retry, so an abort can
no longer use up the retry #16437 added for a stalled load. A second
abort, a second timeout, or any other error still fails the run as
before.
- When the abort came from the app's redirect and that redirect has
already loaded `/login`, the page is used as it is instead of navigating
to `/login` a second time. A redirect that ends anywhere else (for
example `/change-password`) still navigates to `/login`.

Nothing outside this Playwright driver changes.

`tests/studio/test_playwright_multi_account_open_login.py` drives
`open_login` with a scripted page and the real Playwright error types:

| goto outcomes | expected |
|---|---|
| abort, redirect already on `/login` | returns after one goto |
| abort elsewhere, timeout, load | returns after the third goto (the CI
failure) |
| abort to `/change-password`, load | navigates to `/login` |
| two aborts / two timeouts / abort then two timeouts | raises |
| an error other than an abort | raises, no retry |

## Testing

- New test: 7 passed. Against the driver on main: 3 failed, including
`test_a_timeout_after_an_abort_still_gets_its_retry`, the sequence the
CI logs show.
- `tests/test_ci_repo_cpu_shards.py`,
`tests/studio/test_playwright_suites_run_in_ci.py` and
`tests/studio/test_pwsh_calls_use_the_shared_runner.py` pass.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@danielhanchen
danielhanchen merged commit 89db0db into main Nov 5, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-encoder-memory branch November 5, 2026 15:42
danielhanchen added a commit that referenced this pull request Nov 6, 2026
…he server cache release only

#16750 added a layer-streamed encode to video_ltx25_te_worker.py, which supersedes this branch's per-module streaming, so the worker now matches main. What remains is the server side: empty the CUDA cache before a non-resident encode request, so the worker's room check (budget minus the server's reserved memory) does not count blocks the previous render only cached. Tests move to test_video_ltx25.py next to the client tests.

[skip ci]
danielhanchen added a commit that referenced this pull request Nov 6, 2026
… a fixed 6 GiB floor

Main's streamed encode (#16750) needs the resident embeddings, two layers and the 4 GiB encode margin, about 7 GiB for the real Gemma 4, so lending up to 6 GiB could leave the encode on the CPU. The worker now reports stream_need_mib in its ready message (None when it never streams: resident, not CUDA / XPU, kill switch, unstreamable layout) and the lend targets that. The server's room check now calls the worker's _encode_room_mib, so both sides compute room the same way.

[skip ci]
Penguinjanator pushed a commit to Penguinjanator/unsloth that referenced this pull request Nov 6, 2026
…de, so later prompts stop encoding on the CPU (unslothai#16804)

## What

Since unslothai#16750, the LTX-2.5 Gemma 4 encoder worker streams its layers
through the GPU when the whole encoder does not fit. Its room check is
the load budget minus what the server process holds
(`torch.cuda.memory_reserved`). After the first render, the server still
holds that render's cached allocator blocks, so the room drops below the
streamed-encode need and every new prompt after the first one encodes on
the CPU (165-231 s per prompt on Colab L4 / A100 hosts).

This PR empties the server's CUDA (or XPU) cache right before a
non-resident encode request, so the worker's room check counts only
memory the server is using. Cache hits and resident encoders are
untouched. Placement only: the worker's own routing (whole, streamed,
CPU) is main's.

The first version of this PR also added its own per-module streaming in
the worker; unslothai#16750 landed an equivalent layer-streamed encode first, so
the worker now matches main and only the server-side release remains.

## Numbers (Colab, LTX-2.5 two-stage distilled 1280x704x121, GGUF Q4_K_M
DiT, 2 new prompts per arm, fresh process per arm, same VM per card)

Where each prompt encoded (worker log `encoded on ... streamed`):

| card | main | this PR |
|---|---|---|
| A100-40 | 1st prompt: GPU streamed; every later prompt: **CPU** (both
arms) | every prompt GPU streamed (both arms) |
| L4 24 GB | by encode time: 1st prompt 69.8 s, later prompts 227-231 s
(CPU speed) | every prompt 39-74 s |

| card | | main | this PR |
|---|---|---|---|
| A100-40 | encode per new prompt | 165.8-171.4 s | **6.4-6.5 s** |
| | clip per new prompt | 189.7 / 191.2 / 191.3 / 195.3 s | **30.1 /
30.4 / 30.4 / 30.4 s** |
| | s/step | 1.110-1.111 | 1.109-1.112 |
| L4 | encode per new prompt | 227.4 / 231.4 s | **73.6 / 39.3 s** (64.3
/ 66.2 s on a second L4 VM, `streamed: True`) |
| | clip per new prompt | 319.5 / 323.3 s | **166.4 / 132.2 s** (157.8 /
159.6 s) |
| | s/step | 4.68-4.70 | 4.75 |

Frames: A/A bit-identical on both sides (A100, 16 of 16 frames, both
prompts). main vs this PR: LPIPS 0.185 / 0.019, because main's later
prompts used CPU bf16 math and this PR's use the GPU path that main
already takes for the first prompt of a process.

## Tests

`tests/test_video_ltx25.py`: a non-resident cache miss empties the cache
before the server reservation is read and sent (fails on main); a
resident encoder and a cache hit release nothing; no release on CPU /
MPS / a host without a card. `test_video_ltx25.py` +
`test_video_ltx25_te_int8.py`: 155 passed; the 7 failures are the same
test IDs on main in this environment (two-stage i2v fakes, real-header
converters).
Penguinjanator pushed a commit to Penguinjanator/unsloth that referenced this pull request Nov 6, 2026
…nslothai#16845)

## What

LTX-2.5 was outside the per-request DiT residency fit
(`video_stream_residency`) that Wan, HunyuanVideo-1.5 and LTX-2 (unslothai#16787)
use on the `group` / `streaming` tiers. On cards that stream the LTX-2.5
DiT (L4, 16-24 GiB budgets) every forward copied all 48 blocks from the
host while part of the card stayed idle: 11.55 GiB of H2D per forward
for GGUF Q4_K_M and 23.6 GiB for the INT8 DiT on an L4.

1. `ltx-2.5` joins `RESIDENT_FAMILIES` (exact name), so the leading
blocks stay resident per request, sized from the measured request peak
with the existing margin, and only the rest stream through the existing
prefetch.
2. LTX-2.5's Gemma 4 encoder runs in a worker process on the same card.
Before an encode that is not a cache hit,
`video_ltx25.lend_resident_dit_for_encode` streams resident blocks again
when that makes the encoder fit: the whole encoder if lending gets it
there, else the worker's own layer-streamed need (`stream_need_mib`,
reported in its ready message; unslothai#16750's streamed encode), and pins them
back right after the encode. The room check is the worker's
`_encode_room_mib`, so both processes compute it the same way.
3. A cancelled encode that borrowed blocks stops the worker before they
are pinned back (it may still be computing on the lent memory); the next
encode restarts it.

Placement only: the same weights and kernels run. Kill switch: the
existing `UNSLOTH_VIDEO_DIT_RESIDENT=0` (also disables the lending).

## Numbers (Colab L4 24 GB, LTX-2.5 two-stage distilled 1280x704x121,
GGUF Q4_K_M, 2 new prompts per arm, fresh process per arm, main
73984c4)

| arm | s/step | denoise s per new prompt | encode s per new prompt |
|---|---|---|---|
| main | 4.68-4.70 | 85.2 / 85.2 | 227.4 / 231.4 (CPU) |
| this PR, arm 1 | **3.82-3.84** | **76.2 / 76.3** | 81.3 / 82.1 (GPU) |
| this PR, arm 2 | **3.82-3.87** | **76.3 / 76.0** | 67.4 / 37.8 (GPU) |
| second VM: main + unslothai#16804 | 4.85-4.86 | 86.5 / 86.5 | 64.3 / 66.2 (GPU)
|
| second VM: this PR | **3.89-3.92** | **76.7 / 76.6** | 43.7 / 8.3
(GPU) |

s/step is 18-20% lower (A/A within 1.3%); the fit kept 4006 MiB (15
groups) resident. Frames against main + unslothai#16804 on the same VM:
bit-identical (16 of 16 frames, both prompts). Against main alone the
frames differ only because main encodes the later prompts on the CPU
(fixed separately by unslothai#16804; this branch's lending path also releases
the server cache when blocks are resident).

Earlier A/B on main e2daf16 (with the then-open encoder changes):
Q4_K_M 4.67 -> 3.86 s/step, INT8 2.13 -> 1.98, H2D per forward 11.55 ->
9.57 GiB (Q4) and 23.61 -> 21.88 GiB (INT8), frames bit-identical with
and without the change and with the kill switch, no-op on an A100-40
(nothing streams there).

The lending path did not engage on these cards (the encoder already fit
its streamed need once the server's cache was released); it is covered
by CPU tests.

## Tests

`tests/test_video_stream_residency.py` (ltx-2.5 applies on group /
streaming, not on model offload or a custom name; fails on main) and new
tests in `tests/test_video_ltx25.py`: blocks are lent only when the
encoder then fits whole or reaches the worker's streamed need, never for
an encoder that cannot stream, a resident encoder or a non-CUDA device;
the worker reports its streamed need only when it can stream; the encode
wrapper lends before a cache miss, restores after it (also on failure)
and skips cache hits; a cancelled encode stops a busy worker before the
restore. `test_video_ltx25.py` + `test_video_stream_residency.py`: 164
passed, 7 failed, the same 7 test IDs that fail on main in this
environment (two-stage i2v fakes, real-header converters).
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