Repository navigation
Studio diffusion: stream the LTX-2.5 encoder, cache and trim FLUX.3 prompt encodes - #16750
Conversation
…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.
Codex Review SummaryThis 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. |
[skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…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>
…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]
… 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]
…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).
…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).
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.
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.use_cache=Falseto the hidden-state forward (video_ltx25_te_worker.py). Before, every encode built a KV cache it never read.repeat(1, 1, 1)copy of the packed prompt (video_ltx25.py).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_onnow picks a route with_encode_plan:_encode_device), it onloads the whole encoder, as before.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.More details:
.datais swapped, so the tied head still shares the embedding weight._applydecline streaming. The int8 ConvRot Linear keeps its codes and scales as buffers, so int8 encoders can stream.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/streamingtiers. 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):I also drove
_encode_onwith a load budget that fits the streamed need but not the whole one. It chosecuda:0streamed, 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):
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=Falsein_pack_hidden_statesWhat / why. The LTX-2.5 encoder config sets
use_cache: true, soGemma4UnifiedModel.forwardbuilds aDynamicCache, 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.
DynamicCachetoNone.3. Skip the identity repeat in the LTX-2.5
encode_promptWhat / why. With
num_videos_per_prompt == 1,_onedid.to(device, dtype)and thenrepeat(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.toalready made private, contiguous storage.It keeps the repeat when
.tois a no-op, because then the result would alias the client's cached tensor (CPU, same dtype). Counts above 1 are unchanged.Evidence.
encode_prompt(dispatch-mode count, LTX shape, one video): base 735 MiB (_to_copy+repeat), head 367.5 MiB..tois a no-op.4. FLUX.3
encode_promptbridgeWhat. 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_embedshelper. WhenNone, 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.installreturned False for FLUX.3, so the cache was off and every render re-ran the Qwen3-VL encoder.truncate_text_encodersalso declined ("encode_prompt cannot be called generically"), so each encode still computed:hidden_states[32], which the step never readsEvidence. 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
Flux3Transformer2DModelandAutoencoderKLFlux2. Both block graphs, renders: seed 0, seed 1, seed 0 again, then a new prompt:Tests
tests/test_video_ltx25.py, new tests:tests/test_diffusion_flux3_encode_bridge.py, new:encode_promptwith unchanged argumentsencode_promptgenericallytest_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.Not proven here