Skip to content

Studio: Qwen-Image-2.1 placement from measured sizes, int8 under offload on torchao 0.17, balanced fit check - #12408

Merged
danielhanchen merged 27 commits into
mainfrom
studio/q21-offload-memory
Oct 1, 2026
Merged

danielhanchen merged 27 commits into
mainfrom
studio/q21-offload-memory

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

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:

cap Studio, warm image ComfyUI int8, warm image
24 GB 4.06 s 3.72 s
16 GB 4.99 s 3.78 s
12 GB 8.14 s 3.98 s
8 GB load fails: "granular streaming offload could not be enabled" 4.18 s
16 / 12 / 8 GB, memory_mode=balanced with int8 out of memory at the first image n/a

Six causes:

  1. The load-time plan prices every image family with a flat 8 GiB runtime headroom and family-table sizes. Qwen-Image-2.1 loads at 16.5 GiB (int8 DiT plus fp8 text encoder). Its worst activation phase is 1.8 GiB at 1 MP. So it streamed its text encoder on every new prompt at 24 GB, and streamed every DiT block at 16 and 12 GB.
  2. An offloaded pre-quantized denoiser was seeded onto the GPU whole. At 8 GB the ~7 GiB int8 DiT just fits that spike, and the streaming hooks then cannot allocate their first block.
  3. memory_mode=balanced never checked the budget. It kept the 9 GiB fp8 text encoder resident and ran out of memory at the first image.
  4. Fresh installs lose INT8 under offload. The planner only let int8 stream from torchao 0.18, so every offloading load on a fresh install (torchao 0.17) silently switched to the fp8 transformer.
  5. The compiled extract step pins the full-sequence K/V in its prefix cache. Inductor turns 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.
  6. The gallery PNG encode sits on the request path. At zlib level 6 it costs about 0.4 s per 1024x1024 image.

Changes

  • Placement from measured sizes: 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. Stated limits:
    • It tries everything resident first. If that does not fit, it keeps the DiT resident and streams the encoders. Failing that, it keeps as many DiT offload groups resident as fit (top-level group first, then blocks in order) and streams only the rest.
    • It only ever moves toward residency, and only for auto loads on CUDA with torchao denoisers, measured families and compiled speed tiers.
    • On the resident-denoiser tier, the room left also holds the text encoder's first layers.
    • A streamed group between resident ones still waits on the copy stream before it computes.
    • Kill switches: UNSLOTH_DIFFUSION_MEASURED_ACTIVATION=0 and UNSLOTH_DIFFUSION_PARTIAL_RESIDENT=0.
  • Seed placement: an offloaded pre-quantized denoiser is seeded on the host, as the runtime-quantize path already does. Kill switch: UNSLOTH_DIFFUSION_PREQUANT_SEED_ON_HOST=0.
  • Balanced fit check: balanced checks 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.
  • INT8 under offload on torchao 0.17: int8 streams on torchao 0.17.
    • The hosted int8 checkpoints load there as Int8Tensor, which already pins.
    • 0.17's v1 int8 class lacks only is_pinned and pin_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.
    • Streamed v1 weights then match resident bit for bit.
    • Kill switch: UNSLOTH_DIFFUSION_INT8_STREAM_TORCHAO17=0.
  • K/V compaction: each prefix K/V entry that is a view into a larger storage is copied. Values are bit-identical. Kill switch: UNSLOTH_DIFFUSION_Q21_COMPACT_KV=0.
  • PNG encode: gallery PNGs are encoded at zlib level 1, which takes about 0.1 s for a file roughly 10% larger. Lossless. UNSLOTH_IMAGE_PNG_COMPRESS_LEVEL=6 restores the old encode.

Results

Setup:

  • Colab RTX PRO 6000 (G4) and L4.
  • Studio installed through install.sh (torch 2.11, torchao 0.17); ComfyUI v0.38.0 with its int8 Qwen-Image-2.1 graph.
  • 1024x1024, auto precision and speed.
  • Each cell is a fresh process. The caps patch the memory the planner and the allocator see. Two interleaved repeats per arm.

Each cell gives warm seconds per image, repeat 1 / repeat 2.

G4:

cap main this PR ComfyUI
24 GB 4.06 / 4.08 3.68 / 3.70 3.72 / 3.75
16 GB 4.99 / 4.97 3.80 / 3.81 3.79 / 3.78
12 GB 8.14 / 8.14 3.96 / 3.98 3.99 / 3.97
8 GB load fails 4.62 / 4.58 4.18 / 4.18
24 GB, balanced int8 8.88 7.51 n/a
16 / 12 / 8 GB, balanced int8 out of memory 7.64 / 8.17 / 7.84 n/a

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:

cap main #12389 alone this PR ComfyUI
24 GB 4.05 3.95 3.59 3.73
16 GB 5.13 4.05 3.70 3.78
12 GB 5.84 4.16 3.98 3.99
8 GB load fails load fails 3.89 4.19
  • Peak VRAM goes up where more now stays resident: 13.0 to 19.3 GiB at 24 GB, and 12.3 to 13.3 GiB at 16 GB. Each stays under its cap.
  • Peak host RAM rises from about 19 GiB to 28 GiB at 12 GB (8 GB is similar), because the streamed groups are pinned.
  • INT8 vs FP8 under offload: with UNSLOTH_DIFFUSION_INT8_STREAM_TORCHAO17=0 an 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

  • Bit for bit: the K/V compaction, the PNG encode and v1 int8 streaming match the old path.
  • Placement changes (B200 A/B of the placement commits, same seeds): across 312 image pairs, this PR against main gives median LPIPS 0.0224. Main against itself gives 0.0206: the compiled Qwen-Image-2.1 path is not bit-reproducible across processes, even on main. In 5 of the 6 A/B cells, this PR's output matched one of main's own runs bit for bit.

Tests

  • New test_diffusion_measured_placement.py, test_diffusion_offload_seed_balanced.py, test_diffusion_offload_seed_balanced_behaviour.py and test_diffusion_int8_stream_torchao17.py, plus additions to test_image_gallery.py and test_diffusion_offload_precision.py.
  • On main they fail: measured placement 148 failed, the seed and balanced behaviour tests 7 failed (the seed lands on cuda under an offloading plan, balanced keeps the fp8 encoder resident at 16 / 12 / 8 GB), the torchao 0.17 tests 7 failed (int8 refused under streaming), and test_diffusion_offload_seed_balanced.py fails at import.
  • The new files plus test_diffusion_memory.py: 557 passed, including the GPU tests (B200, torchao 0.17).
  • The diffusion suites pass in a torchao 0.17 venv and a torchao 0.18 venv.

Not covered

  • The caps are emulated on a large card; no real 8, 12 or 16 GB card was used. Windows, WSL (where pinned memory is capped), AMD and Apple were not run.
  • On the install.sh stack 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.
  • Only Qwen-Image-2.1 is measured. The placement change is gated to families with a measured activation peak; others keep the flat plan.

danielhanchen and others added 21 commits September 30, 2026 20:35
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.
…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.
@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-01T11:56:30.178170Z 15ba4d2 Manual request
🔒 Security Review ⚠️ Failed 2026-10-01T08:49:16.620485Z a548b36 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

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

Comment on lines +3043 to +3044
if use_stream:
_pin_top_level_group(module, logger)

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

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

Comment on lines +2963 to +2965
budget = None if _pinned_memory_capped() else _pin_budget_mib()
if budget is None or need_mib > budget:
return False

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

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 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 15ba4d2eef

ℹ️ 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 cf89ed7 into main Oct 1, 2026
2 of 35 checks passed
@danielhanchen
danielhanchen deleted the studio/q21-offload-memory branch October 1, 2026 12:19
danielhanchen added a commit that referenced this pull request Oct 1, 2026
* Fix the tests left red on main by #12408, #12382 and #12436

* Trigger version-compat-ci on the trust-gate test and guard every file it runs
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