Repository navigation
Studio: Qwen-Image-2.1 placement from measured sizes, int8 under offload on torchao 0.17, balanced fit check - #12408
Conversation
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.
… GPU An int8 / fp8 pre-quantized denoiser seeded into pipeline assembly was always moved onto the GPU whole, even when the memory plan streams or offloads it. On an 8 GB card Qwen-Image-2.1's int8 DiT (~7 GiB) just fits that spike, and the streaming hooks then fail to allocate their first block, so the auto load dies with 'granular streaming offload could not be enabled'. Load the seed onto the host when the plan does not keep the denoiser resident (the end state every offload tier starts from, and what the runtime-quantise path already does). Kill switch: UNSLOTH_DIFFUSION_PREQUANT_SEED_ON_HOST=0.
The gallery PNG is encoded between the last denoise step and the HTTP response. At Pillow's default level 6 that encode cost about 0.4 s on a 1024x1024 render; level 1 costs about 0.1 s for a file roughly 10% larger. Lossless: pixels and the embedded recipe are unchanged. UNSLOTH_IMAGE_PNG_COMPRESS_LEVEL=6 restores the old encode.
balanced always planned group offload with every companion resident and never checked the budget, so Qwen-Image-2.1 + int8 loaded at 16 / 12 / 8 GB and then ran out of device memory at the first generate (the resident 9 GiB fp8 text encoder plus activations); at 8 GB the group apply itself OOMed into whole-module offload, which onloads that encoder whole. After the load, size the resident companions as loaded and walk down the streamed tiers auto already uses when they do not fit beside the runtime headroom: stream the text encoders too, else whole-module offload (granular streaming for a torchao denoiser, and refine_memory_plan_for_components still turns an oversized component into streaming). The denoiser is never moved back to resident, and a balanced load that fits (24 GB) keeps its placement: the check reads loaded sizes, not the pre-load estimate, which prices a quantised text encoder at its dense size. Kill switch: UNSLOTH_DIFFUSION_BALANCED_FIT_CHECK=0.
…t step pins in its prefix cache Inductor turns the extract step's key[:, :prefix].clone() into a view of the full sequence buffer, so every cached layer holds the whole (text + image) K and V until the first step ends: step 0 peaked 2.7 GiB above the weights at 1024x1024 against 0.66 GiB for every later step. Copy each entry in the eager block loop when it is a view into a larger storage. Bit-identical values; UNSLOTH_DIFFUSION_Q21_COMPACT_KV=0 turns it off.
…ed activation peak, keep what fits resident The load-time plan prices every image family with a flat 8192 MiB runtime headroom and family-table sizes, so Qwen-Image-2.1 (int8 DiT + fp8 encoder, 16.5 GiB loaded) streamed its text encoder on every new prompt on a 24 GB card and streamed every DiT block at 16 and 12 GB. After the pipeline is built, an auto load on a streamed tier re-places from the loaded storage sizes and the family's measured worst phase (1849 MiB at 1 MP, x1.15, plus the flat base overhead and the safe-budget reserve): everything resident, else the DiT resident with the encoders streamed, else as many DiT offload groups resident as fit (top-level group first, then blocks in order) with only the rest streamed. Only moves toward residency; only auto, CUDA, torchao denoisers, measured family and compiled speed tiers. UNSLOTH_DIFFUSION_MEASURED_ACTIVATION=0 restores the flat plan, UNSLOTH_DIFFUSION_PARTIAL_RESIDENT=0 streams every group again.
…nced fit check Driven through entry points main already has (the seed call and the post-load refinement as written in diffusion.py, the prequant loader with faked checkpoint I/O), so main fails them by assertion: the seed lands on cuda under an offloading plan, and balanced keeps the 9 GiB fp8 text encoder resident at 16 / 12 / 8 GB.
…d the Q21 prefix K/V compaction
…nd keep the copy-stream wait on resident groups On the tier that keeps the denoiser resident, the room left after it holds as many text encoder leaf groups as fit, so a card whose 10% reserve leaves the whole encoder just short (an L4 reports 23034 MiB) streams only the remainder on a new prompt. A streamed group that prefetched its successor relies on the successor's onload_ to synchronize the copy stream before it computes; a resident successor now keeps that wait instead of a bare no-op, so a group streamed between resident ones never reads weights still in flight. Groups are filled greedily in order (a group too large for the room streams, a later smaller one may still fit).
A fresh install pins torch below 2.12, which resolves torchao 0.17, and the planner only let int8 stream under offload from torchao 0.18. Every offloading load on a fresh install therefore took the fp8 transformer instead of int8 (Qwen-Image-2.1 at 16 / 12 GB). torchao 0.17 already ships the pinnable Int8Tensor (0.18 only made it the int8 config's default): the hosted int8 checkpoints load as it on 0.17 and stream bit-identically to resident. Allow int8 streaming from 0.17 when Int8Tensor implements the pin ops, and rebuild 0.17's unpinnable v1 int8 weights (runtime quantise, legacy pickles) as Int8Tensor before the group offload hooks are built, so they keep the copy stream instead of falling back to synchronous copies. Kill switch: UNSLOTH_DIFFUSION_INT8_STREAM_TORCHAO17=0.
…f rebuilding them Rebuilding 0.17's v1 int8 weights as Int8Tensor before streaming changed the dynamic activation quant, so a streamed module no longer matched the same weights resident (max abs 0.005 on a toy stack; the GPU survival test caught it). The v1 classes lack only is_pinned and pin_memory; register those two ops (re-wrapping the same int8 data, scale and zero point through the classes' own _apply_fn_to_data), only where torchao ships the classes without them. The v1 weights then pin up front and copy on the stream: bit-identical to resident and about as fast as Int8Tensor streaming, where the synchronous fallback was ~10x slower. Same kill switch, UNSLOTH_DIFFUSION_INT8_STREAM_TORCHAO17=0.
… it leaves matmul precision alone
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. |
…offload, and count pinned encoders in the streaming tier's pin budget
…ivation placement
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17c2ed5575
ℹ️ 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".
| if use_stream: | ||
| _pin_top_level_group(module, logger) |
There was a problem hiding this comment.
Exclude the top group from deferred pinning
When background pinning is requested, as it is by the video loader, the branch immediately above registers every offload group with _GroupPinner, but this call then replaces the top group's hooks and creates a separate pinned host copy without removing that group from the pinner. When the background worker starts, it still pins the old entries in group.cpu_param_dict, so the top-level weights remain pinned twice for the pipeline lifetime and can exceed the host-memory budget that _streamed_pin_plan calculated. Reuse/update the group's CPU copy or exclude this group from deferred pinning before installing the custom hooks.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable: _pin_top_level_group only takes a group with no stream, and diffusers gives such a group an empty cpu_param_dict (_init_cpu_param_dict returns {} when self.stream is None). _GroupPinner pins only cpu_param_dict entries, so it pins nothing for the top group and the weights are pinned once.
…esident groups again for requests past the measured reserve
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 886b480bd8
ℹ️ 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".
| budget = None if _pinned_memory_capped() else _pin_budget_mib() | ||
| if budget is None or need_mib > budget: | ||
| return False |
There was a problem hiding this comment.
Reserve pending encoder pins before pinning the top group
When _streamed_pin_plan returns (False, True) because the DiT exceeds the host-pin budget but its encoder fits, this standalone check still sees the encoder's memory as available: _pin_top_level_group runs before the encoder is pinned, and background pinning can defer that allocation further. It can therefore approve a top-group pin whose bytes plus the subsequently pinned encoder cross the reserve enforced by _pin_budget_mib, risking host-memory pressure or OOM on tightly provisioned systems. This is distinct from the earlier duplicate-copy concern: the issue is the unaccounted future encoder allocation, so the reserved encoder bytes or a shared running pin total should be included here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 15ba4d2: the top-group pin now checks and adds to the same running pin total the encoders and torchao denoisers use, on both the group and streaming tiers.
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
Builds on #12389 and includes its commits, so that should merge first.
Problem
I compared Qwen-Image-2.1 in Studio against ComfyUI on Colab. Studio was installed through
install.sh, which gives torch 2.11 and torchao 0.17. VRAM was capped at 24, 16, 12 and 8 GB. Studio was slower or failed outright at every cap:memory_mode=balancedwith int8Six causes:
memory_mode=balancednever checked the budget. It kept the 9 GiB fp8 text encoder resident and ran out of memory at the first image.key[:, :prefix].clone()into a view of the whole text plus image buffer. Step 0 therefore peaked 2.7 GiB above the weights at 1024x1024, against 0.66 GiB for every later step.Changes
UNSLOTH_DIFFUSION_MEASURED_ACTIVATION=0andUNSLOTH_DIFFUSION_PARTIAL_RESIDENT=0.UNSLOTH_DIFFUSION_PREQUANT_SEED_ON_HOST=0.balancedchecks the loaded companions against the budget. When they do not fit, it walks down the streamed tiers auto already uses. A balanced load that fits keeps its placement. Kill switch:UNSLOTH_DIFFUSION_BALANCED_FIT_CHECK=0.Int8Tensor, which already pins.is_pinnedandpin_memory. Those two ops are registered, re-wrapping the same int8 data, scale and zero point, and only where torchao ships the class without them.UNSLOTH_DIFFUSION_INT8_STREAM_TORCHAO17=0.UNSLOTH_DIFFUSION_Q21_COMPACT_KV=0.UNSLOTH_IMAGE_PNG_COMPRESS_LEVEL=6restores the old encode.Results
Setup:
install.sh(torch 2.11, torchao 0.17); ComfyUI v0.38.0 with its int8 Qwen-Image-2.1 graph.Each cell gives warm seconds per image, repeat 1 / repeat 2.
G4:
L4 (22.5 GB, no cap): main 24.96 / 24.93, this PR 23.77 / 23.83, ComfyUI 20.77 / 20.86. The L4 arm ran the branch before the two torchao 0.17 commits. On a full L4 the denoiser stays resident, so those commits do not touch it.
L4 with the VRAM capped (seconds per image): 16 GB 27.23 to 24.10 (ComfyUI 21.33), 12 GB 39.02 to 24.92 (22.07), 8 GB 39.01 to 26.22 (23.03).
A100 40 GB (no fp8, so main streams bf16 under offload): 16 GB 33.23 to 7.37 (ComfyUI 6.87), 12 GB 50.65 to 9.10 (7.73). This is where keeping int8 under offload on torchao 0.17 matters most.
Pinned versions (torch 2.12.1, torchao 0.18), G4, seconds per image:
UNSLOTH_DIFFUSION_INT8_STREAM_TORCHAO17=0an offloading fresh install gets the fp8 transformer as before. On G4 that runs 3.41 to 3.60 s at 16 and 12 GB, faster than int8's 3.8 to 4.0 s, because Blackwell's fp8 GEMMs are faster. This PR keeps int8 so that the precision auto picks does not depend on whether the model had to offload.Accuracy
Tests
test_diffusion_measured_placement.py,test_diffusion_offload_seed_balanced.py,test_diffusion_offload_seed_balanced_behaviour.pyandtest_diffusion_int8_stream_torchao17.py, plus additions totest_image_gallery.pyandtest_diffusion_offload_precision.py.test_diffusion_offload_seed_balanced.pyfails at import.test_diffusion_memory.py: 557 passed, including the GPU tests (B200, torchao 0.17).Not covered
install.shstack this PR is still about 10% slower than ComfyUI at 8 GB on G4 and 7 to 14% slower on L4. Before and after the denoise loop Studio is now ahead; the rest is per step (0.908 vs 0.739 s/step on L4). Profiling puts it in the int8 GEMM writing int32 output, the activation quant and norm glue, and cuDNN vs flash attention. Closing it needs a fused int8 GEMM, which is not in this PR.