Skip to content

Studio: overlap streamed block onloads and stop copying a streamed DiT's top-level weights back every forward - #12389

Closed
danielhanchen wants to merge 8 commits into
mainfrom
fix/offload-streaming-prefetch
Closed

danielhanchen wants to merge 8 commits into
mainfrom
fix/offload-streaming-prefetch

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

When a diffusion model streams its DiT from host RAM, the copy of block i+1 is meant to overlap block i's compute on a side stream. I profiled this on Colab L4 and A100 with the VRAM budget capped so the planner picks the streamed tiers. The group tier does hide the copy, but two things waste time:

  1. The streaming tier does not overlap.
    • It applies group offload with low_cpu_mem_usage=True, so every onload re-pins the block on the CPU.
    • It sets record_stream=False, so each group's offload synchronizes the compute stream, and that pinning runs with the GPU idle.
    • On Wan2.2-5B capped at 12 GiB this cost 1.8 s of CPU pinning per 4 forwards and 1.35 s of GPU idle time.
  2. The DiT's top-level weights go through the slow path on every forward, on both tiers.
    • diffusers puts the weights outside the block lists (embedders, norm_out, proj_out) into one top-level group with no stream.
    • Every forward uploads them synchronously from pageable memory and copies them back into a new host buffer.
    • That is 117 MiB per forward on Wan2.2-5B, about 100 MiB on FLUX.1 and about 815 MiB on LTX-2.3. Inference never changes these weights, so the copy back is never needed.

Changes (diffusion_memory.py)

  • Streaming tier:
    • The streamed DiT, then the encoders, are pinned within the host pin budget the group tier already uses (_streamed_pin_plan).
    • When the load asked for background pinning, the existing background pinner does it.
    • record_stream is on, so an offload no longer drains the compute stream.
    • Kill switch: UNSLOTH_DIFFUSION_STREAMING_PREFETCH=0.
  • _pin_top_level_group:
    • Keeps one pinned host copy of a block-streamed DiT's top-level weights. Onload is a non-blocking copy on the compute stream, ordered before the forward's kernels. Offload only re-points the tensors at the pinned copy.
    • VRAM is unchanged: the group is resident for the same span as before.
    • Skipped for torchao weights, when the copy does not fit the pinnable host RAM, and when UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN=0 asks for no pinning.
    • A weight replaced while offloaded is re-pinned.
    • Kill switch: UNSLOTH_DIFFUSION_PIN_TOP_GROUP=0.

Results

Colab L4 and A100-SXM4-40GB, torch 2.11.0, diffusers 0.41.0.dev0, transformers 5.5.0, torchao 0.17.0. Pinned host-to-device copies measured 12.35 GB/s on both. Each arm runs in a fresh process, interleaved on the same card. The cap patches the memory the planner and the allocator see.

cell tier, precision before, s/step this PR, s/step change
Wan2.2-TI2V-5B, L4, 12 GiB cap, 1280x704x49 streaming, int8 6.35 (6.32 to 6.37, 3 runs) 5.66 (5.66 to 5.67, 3 runs) -11%
FLUX.1-schnell, L4, 8 GiB cap, 1024px streaming, bf16 3.03 (2.97 to 3.03, 3 runs) 2.21 (2.19 to 2.21, 3 runs) -27%
FLUX.1-schnell, L4, 12 GiB cap, 1024px group, bf16 2.30 (2.27 to 2.33) 2.20 (2.18 to 2.21) -4%
LTX-2.3, A100 40 GB, 768x512x121 group, bf16 3.78 (3.78 to 3.82) 3.13 (3.13) -17%

From the profiler traces:

cell copy hidden behind compute, before to after GPU idle waiting, before to after top-level copy back to host per 2 to 4 forwards
Wan2.2-5B, 12 GiB 0.76 to 0.96 1352 ms to 11 ms 439 ms to 0
FLUX.1, 8 GiB 0.59 to 0.71 2171 ms to 25 ms removed
LTX-2.3, A100 0.315 to 0.326 (the maximum possible is 0.317 before) 332 ms to 179 ms 1004 ms to 0
  • On the group tier the copy was already hidden. With copies forced to wait for compute instead, LTX-2.3 runs 5.23 s/step and FLUX.1 at 12 GiB runs 3.2 s/step.
  • LTX-2.3 and FLUX.1 at 12 GiB are copy-bound: they stream bf16 at the link's bandwidth. With this PR LTX-2.3 runs at 99% of that bound.
  • Accuracy:
    • With compile off, before and after are bit-identical for Wan2.2-5B, FLUX.1 at both caps, and LTX-2.3.
    • With compile on, the Wan difference (39.5 dB PSNR) matches what a run with both kill switches set shows against the old code. That is the known cross-process compile variation.

Costs

  • Reserved VRAM in streaming: with record_stream on, the CPU runs further ahead, so peak reserved VRAM grows (Wan2.2-5B under a 12 GiB cap: 5.7 to 9.3 GiB). Allocated memory is unchanged, and the group tier already behaves this way. No OOM was seen in the capped runs.
  • Load time: where the image path pins at load (FLUX.1 at 8 GiB), load takes 55 s to 110 s. The first image drops from 98 to 114 s down to 43 s, and host RSS goes from 35 to 44 to 47 GiB on a 53 GiB host.
  • After a LoRA load: diffusers re-applies the offload hooks, so the top-level group falls back to the old path.

Tests

  • test_diffusion_memory.py adds or changes 13 tests, some of which run on a GPU. They cover:
    • streaming pins the planned modules and turns record_stream on;
    • both kill switches;
    • the pin budget and the "pin nothing" override;
    • torchao skipping;
    • re-pinning a weight replaced while offloaded;
    • bit-identical output against the old path on CUDA.
  • All 13 fail on main and pass here.
  • Offload, keep-CPU, background pin, quantised video offload and LTX-2.3 plan suites: 303 passed (GPU tests included).

Not covered

  • No consumer GeForce card or desktop PCIe gen4 or gen5 host was tested. Both Colab hosts topped out at 12.35 GB/s, so a faster link would move some copy-bound cells toward compute-bound.
  • The VRAM cap is emulated, not a real 8 or 12 GB card. Windows, WSL (where pinned memory is capped) and AMD were not run.
  • A deeper prefetch (two blocks ahead) was not built. The traces bound its gain by the copy engine's remaining idle time: about 3% on LTX-2.3 and up to 6 to 9% on FLUX.1 at 8 GiB.
  • Under the cap on this stack, FLUX.1 streams bf16 instead of int8, and LTX-2.3 single-file loads bf16. Both double the bytes copied per step and are a separate issue.

The streaming offload tier applied diffusers group offloading with
low_cpu_mem_usage=True and record_stream=False. An unpinned host copy is
pinned again on the CPU at every onload, and record_stream=False makes
every group's offload synchronize the compute stream, so the next block's
pin ran with the GPU idle. Pin the streamed DiTs (then the encoders)
within the host budget the group tier already uses, off the load path
when the caller requested background pins, and keep record_stream on.
UNSLOTH_DIFFUSION_STREAMING_PREFETCH=0 restores the previous kwargs.
diffusers block-level offload keeps the weights outside the block lists
(embedders, norm_out, proj_out) in a top-level group with no stream:
every forward re-uploads them from pageable host memory and every
offload copies them back into a fresh host buffer, which inference never
needs. Keep one pinned host copy: the onload becomes an async H2D on the
compute stream and the offload only re-points the tensors. VRAM is
unchanged. Skipped for torchao weights and when the copy does not fit
the pinnable host RAM. UNSLOTH_DIFFUSION_PIN_TOP_GROUP=0 turns it off.
…aded

A .to() conversion or an adapter fused on the host swaps the tensor the
top-level group points at while it sits offloaded. The next onload now
pins and uploads what is there instead of the stale copy.
…he pin override

Round each tensor up to a power of two when checking the host budget, as
_module_host_mib does, and skip the pinned top-level copy when
UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN=0 asks for no pinning.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 1, 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-10-01T13:03:21.441119Z 9d31daa Manual request
🔒 Security Review ⚠️ Failed 2026-10-01T03:37:24.704591Z 5280ec1 PR opened
ℹ️ 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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
🔒 Security Review 🔄 Running since 2026-10-01T03:37:21.682938Z 5280ec1 PR opened
ℹ️ 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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 4a12384086

ℹ️ 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 3074 to +3075
if use_stream and "record_stream" in params:
kwargs["record_stream"] = False
kwargs["record_stream"] = prefetch

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Gate record-stream prefetch on the available VRAM

On low-VRAM CUDA systems where refine_memory_plan_for_components selects OFFLOAD_STREAMING, this now enables record_stream by default even though the planner only verifies that non-streamed resident components fit; it does not reserve space for the previous group's recorded allocation while later groups are prefetched. A model with sufficiently large blocks can therefore fit the former synchronized streaming path but OOM under this path, defeating the fallback specifically intended for components larger than the device budget. Please gate this optimization on an estimated overlapping-group peak or retain record_stream=False when that headroom cannot be established.

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.

Not reproducible. A block held by record_stream is only deferred: on a failed allocation the CUDA caching allocator runs release_cached_blocks, which calls synchronize_and_free_events before declaring OOM (c10/cuda/CUDACachingAllocator.cpp, malloc fallback chain and release_cached_blocks in v2.11.0), so pressure costs a sync, not an OOM. Measured on FLUX.1-schnell 1024px streaming with set_per_process_memory_fraction: at a 2.0 GiB cap both the old synchronized path and this path render (peak reserved 2.00 vs 1.99 GiB, bit-identical latents); at 1.9 GiB both OOM on the same 52 MiB request with 1.81 GiB allocated. The OOM point is unchanged.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 4a12384086

ℹ️ 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 +2327 to +2329
def offload_() -> None:
for tensor, pinned in host.items():
tensor.data = pinned

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 Preserve mutations to top-level buffers during offload

For a transformer whose forward updates a top-level buffer, this replacement offload_ discards the GPU-side update by repointing the buffer at the original pinned snapshot. Diffusers' original streamless offload copies tensors back to CPU, while this helper includes both parameters and buffers in host; consequently counters, running statistics, or inference caches reset after every forward and later outputs can be incorrect. Restrict the no-copy-back optimization to immutable parameters or otherwise preserve updated buffers.

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.

No reachable case. Inference never mutates a registered top-level buffer in place: across diffusers' transformers, embeddings and normalization modules (27 register_buffer sites) no forward writes one with copy_/fill_/add_ or index assignment; the forward-time caches that do exist (Wan Animate rope_freqs_cache / block_masks, GLM-Image k_caches) are plain dicts and lists, not buffers, so they are never in the pinned map. A buffer reassigned to a new tensor is likewise not in the map and stays where the forward put it. Studio's int8 weight buffers are read-only.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 9d31daaaf3

ℹ️ 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 +3093 to +3094
if use_stream and offload_type == "block_level":
_pin_top_level_group(module, logger, top_reserved_mib)

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 Track aggregate top-level pins across multiple DiTs

In a dual-DiT pipeline, such as one exposing transformer_2 or unconditional_transformer, this call runs once per block-level module with the same top_reserved_mib; a successful pin for the first DiT is never added to the reservation before evaluating the next. Consequently, when the combined DiTs do not qualify for planned pinning, two top groups that each fit individually can collectively exceed the host pin budget and cause swapping or allocation failure. The encoder-reservation fix does not cover this case; use a shared committed-pin total and update it after each successful top-group pin.

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.

Already tracked. Each top-group pin is made immediately (pin_memory on the load path, never deferred), and _pin_top_level_group re-reads the budget from live available host memory (_pin_budget_mib -> _available_system_memory_mib) on every call, so the second DiT's check already sees the first DiT's pinned pages. reserved_mib only covers pins that have not happened yet (the encoders, applied after the DiTs). Measured here: releasing a 4096 MiB pinned tensor returns 3175 to 4228 MiB of budget across three runs.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 9d31daaaf3

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant