Skip to content

Studio: run Qwen-Image-2.1 int8/fp8 on 24 GB cards with the transformer resident and the text encoder streamed - #11883

Merged
danielhanchen merged 22 commits into
mainfrom
studio-q21-small-card-placement
Sep 25, 2026
Merged

danielhanchen merged 22 commits into
mainfrom
studio-q21-small-card-placement

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Builds on #11802 and contains its commits (merge #11802 first; this diff then shrinks to this PR's own change). #11802 adds the memory tier this PR uses: the transformer stays on the GPU and only the text encoders stream.

Why

Qwen-Image-2.1 on a 24 GB card, measured on a real Colab L4 (22.03 GiB), 1024x1024, 25 steps, today's main:

what the user picks what happens on main
Precision int8 or fp8 refused: "the memory plan picked 'group' offload, which moves the transformer via Module.to(); torchao quantised tensors reject that"
the default (Auto) on the Qwen/Qwen-Image-2.1 pipeline bf16 with the transformer streamed every step: 51.5 to 53.2 s per image
the GGUF (Q4_K_M) with Auto precision the hosted INT8 is swapped in under the plan sized for the 4 GB GGUF, with the 8.7 GiB fp8 text encoder resident: out of memory at the first image

The INT8 transformer is 7.1 GiB and the fp8 text encoder 8.75 GiB. Together they do not fit a 24 GB card next to the 1024x1024 VAE decode, but the transformer alone does, and the encoder runs once per image, before step 0. #11802 already plans that placement for GGUF transformers. torchao weights survive being placed on the GPU once (the loader already relies on that for resident loads); what they do not survive are the per-forward hooks that stream the transformer itself. This placement never puts a hook on the transformer, so there is no reason to refuse it.

What changes

  • diffusion_memory.plan_keeps_transformer_resident(plan): true for a resident plan, and for the group tier with stream_transformer=False. Every place that allowed a torchao build only when offload_policy == "none" now asks this instead:
    • the in-place quantisation of a pipeline pick after its replan,
    • the hosted pre-quantised seed of a pipeline pick (both the pre-download probe and the load-time plan),
    • the GGUF pick's quantised candidate replan and its auto retry.
  • Plan equals what loads. When the GGUF plan is resident but the hosted INT8 / FP8 checkpoint replaces the GGUF, the checkpoint is now sized and placed by its own plan (resident, or resident with the encoder streamed), instead of loading under the GGUF's. If even that plan would stream the transformer, the quant is declined (Auto keeps the GGUF, an explicit scheme is refused with the reason).
  • Every candidate replan (the GGUF pick's, the hosted seed's and the in-place quantisation of a pipeline pick) prices a hosted pre-cast encoder the way the load-level plan does (te_prequant_budget_scale), and passes the planner the encoder share so it can find the tier at all.
  • The host-RAM reserve that caps pinning for the streamed encoders (from Studio: count the hosted text encoder and keep the GGUF denoiser resident when only the encoder does not fit #11802) is sized from the cgroup capacity inside a memory-limited container, not the host total, which left a 64 GiB container on a 512 GiB host with no pin budget.
  • A torchao transformer is never handed to whole-module offload or streamed: if the encoder refuses group offload on this tier, the load fails with the reason instead of running a transformer that cannot move.
  • A declined GGUF-pick quant quotes the floor that would have kept it resident ("..., N MiB even with the text encoders streamed"). The pipeline-pick decline message is left as it is, since Studio: stop trading the denoiser's quantisation away to pay for offload #11558 rewrites it.

Results

Real L4 (22.03 GiB), Colab

Seconds per image after the first two (compile, and the first new prompt length), 1024x1024, 25 steps, CFG 1.

what the user picks main this PR (with #11802 and #11882) peak allocated
Precision int8 refused 24.8 to 25.4 s 13.70 GiB
Precision fp8 refused 26.4 to 26.7 s 13.58 GiB
Auto, Qwen/Qwen-Image-2.1 51.5 to 53.2 s (bf16, streamed) 24.8 to 25.3 s (int8) 9.04 -> 13.70 GiB
GGUF Q4_K_M, Auto out of memory at image 1 26.2 to 26.8 s (INT8 swapped in) 13.70 GiB
Precision off (bf16) 52.0 to 52.7 s unchanged 8.94 GiB

24 GiB cap simulated on a shared B200

Same renders, the VRAM cap simulated by patching torch.cuda.mem_get_info and capping the allocator with set_per_process_memory_fraction (1.2 GiB left for desktop and context). The GPU was shared with other jobs, so main's streamed rows are noisy; medians of 4 renders.

what the user picks main #11802 this PR
Precision int8 refused refused 1.53 to 2.60 s
Precision fp8 refused refused 1.66 to 1.86 s
Auto, pipeline 17.1 s (bf16 streamed) 1.74 to 3.53 s (int8)
GGUF Q4_K_M, Auto 28.3 s median (GGUF streamed) 4.58 s (GGUF resident, encoder streamed) 1.64 s (INT8 resident, encoder streamed)
int8 from a local folder (quantised in place on load) refused refused 1.59 s

The encoder pass costs 0.25 to 0.58 s per image on this host (pinned by #11802's gate).

16 GB

Nothing changes on 16 GB, on purpose. The resident-transformer floor for int8 is 18.3 GiB against a 12.8 GiB budget, so int8 / fp8 is still declined and the GGUF keeps streaming (#11802). Forcing the placement anyway rendered one image at a 13.73 GiB peak against a 14.8 GiB allocator cap and ran out of memory on the second from fragmentation, so the decline is the plan matching reality, not caution.

Tesla T4 (16 GB), Colab

Precision int8 is refused on the T4 by main and by this PR alike, before any memory planning: "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)". The T4 (sm 7.5) has no bf16, so on T4 the torchao paths this PR opens do not apply, and the GGUF keeps #11802's placement. A second T4 session for the GGUF and Auto picks (which on a T4 need the dense bf16 text encoder, since the fp8 one needs sm 8.9) lost the load process within one to two minutes with no output, on main and on this branch alike, so there is no T4 timing here; I did not diagnose it further.

Accuracy

Same weights and the same kernels: the placement only decides where the text encoder lives between calls. With deterministic kernels (cuDNN benchmark off, native attention), the encoder-streamed placement and the fully resident one gave bit-identical images for all 4 prompts after the warm-up render. The warm-up render itself is not reproducible across processes on either placement (LPIPS 0.005 to 0.006 between two runs of the same placement), and neither is a repeat of one placement with cuDNN benchmark on, so the table above is timing only.

The prompt embeddings themselves are bit-identical between the streamed and the resident text encoder (compared with torch.equal on the same prompts), so the denoiser sees exactly the same input either way.

Coordination

Tests

  • test_diffusion_memory.py: the pin reserve sized from the container; the placement predicate over every policy (including plans that predate the field), telling torchao weights from GGUF and plain ones, a refusing encoder never sending a torchao transformer to whole-module offload or streaming it, and a dense transformer keeping the old fallback.
  • test_diffusion_backend.py: the in-place pipeline replan pricing the encoder the load opens; a pipeline quantising where only the encoders stream and staying dense where the transformer would stream; a GGUF pick building the quant where only the encoders stream and declining where it would stream; a resident GGUF plan sizing the checkpoint that replaces it, and declining one that would stream; the encoder pricing of the candidate overrides.
  • test_diffusion_pipeline_prequant.py: the seed probe and the load-time seed accepting the encoder-streamed plan and still declining a streamed transformer.
  • With the functional hunks of diffusion.py and diffusion_memory.py reverted, 11 of the 15 new tests fail; the 4 that pass are the negative controls (unchanged behaviour).
  • test_diffusion_backend.py, test_diffusion_memory.py, test_diffusion_auto_policy.py, test_video_backend.py, test_diffusion_pipeline_prequant.py, test_diffusion_speed.py, test_diffusion_te_prequant.py: 1170 passed. test_diffusion_memory.py also passes on torch 2.6 (129 passed).

Not measured

…er resident when only the encoder does not fit
…, pin at allocator size, stream the transformer if a late encoder refuses
load_prequant_text_encoder can return None for a cached checkpoint too, and
assembly then opens the dense shards on disk, so budget max(pre-cast, scanned
dense) whether or not the checkpoint is cached. The prefetch skips covered
shards, so the usual case is unchanged, and the resident-denoiser tier only
streams encoders, so the 24 GB placement holds even with dense shards cached.
…artly offloaded encoder before falling back

WDDM and WSL2 cap page-locked host memory near 1 GiB whatever RAM is free, so pinning a multi-GB encoder or transformer failed part way. On the resident-transformer tier the leaf hooks left by that failure made enable_model_cpu_offload reject the pipeline and the load failed. Those hosts keep the unpinned streaming they had before, and a first-encoder refusal now drops its hooks before whole-module offload takes over.
@danielhanchen
danielhanchen changed the base branch from studio-gguf-resident-transformer to main September 25, 2026 02:13
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 25, 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-09-25T19:20:26.379802Z c0c16a3 Manual request
🔒 Security Review ✅ Completed 2026-09-25T15:38:35.615940Z 45ad41c 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

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026

@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: a058c61048

ℹ️ 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 +922 to +925
elif _resident_transformer_fits():
policy = OFFLOAD_GROUP
stream_text_encoders = True
stream_transformer = 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 Honor explicit whole-module offload in the new tier

When requested_mode is unset and cpu_offload=True, a load whose full model does not fit but whose resident_transformer_floor does now enters this branch with OFFLOAD_GROUP. The legacy override below only changes plans whose policy is OFFLOAD_NONE, so the explicit request no longer forces whole-module offload as the function contract promises; the transformer instead remains resident and can consume most of the device memory. The explicit-offload override should also cover this new automatically selected group tier while continuing to let an explicit memory mode win.

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 a change in behaviour. The legacy cpu_offload override has only ever applied to a plan that picked 'none', and that check (required <= 85% of the budget) still runs before this tier, so the set of loads it forces to whole-module offload is the same as on main. A load that reaches this tier was already a group plan on main (transformer streamed, companions resident), which the override also left alone.

elif _resident_transformer_fits():
policy = OFFLOAD_GROUP
stream_text_encoders = True
stream_transformer = 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 Keep denoiser speed gates enabled for encoder-only offload

When this tier sets stream_transformer=False, only the text encoders receive offload hooks and the denoiser's weights and pointers remain fixed. However, load_pipeline still keys the compile-cache fullgraph setting and apply_speed_optims(offload_active=...) on plan.offload_policy != OFFLOAD_NONE; this unnecessarily disables full-graph compilation and makes graph_eligible reject CUDA graphs as "offload active" for the new resident-denoiser path. These denoiser-specific speed gates should use plan_keeps_transformer_resident(plan) so encoder-only streaming does not forfeit the optimizations the resident placement can safely use.

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.

Correct that fullgraph and the CUDA graph gate still key on offload_policy. Leaving it for a separate, measured change: for Qwen-Image-2.1 the graph wrapper refuses every call anyway (the kv_cache argument is an object, 25/25 refused even fully resident), so here it would only flip fullgraph, and on the tier this applies to the graph memory pool is not priced by the planner, which is exactly where the card is tight. Tracked as an open item.

Comment on lines +1221 to +1225
total, _available = _system_memory_mib()
available = _available_system_memory_mib()
if total is None or available is None:
return None
reserve = max(_PIN_RESERVE_MIN_MIB, int(int(total) * _PIN_RESERVE_FRACTION))

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 Base the pin reserve on cgroup-limited capacity

Inside a memory-limited container, _available_system_memory_mib() is capped by the cgroup, but _system_memory_mib() returns the host's physical total. Computing the 15% reserve from that larger host total can consume the entire container allowance—for example, a 64 GiB container on a 512 GiB host gets a 76.8 GiB reserve and therefore a zero pin budget despite ample available memory. This forces low_cpu_mem_usage=True and loses the measured streamed-weight speedup on common container deployments; the total used for the reserve should be capped by the same cgroup capacity as the available reading.

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.

Right, the available reading is capped by the cgroup but the reserve was sized from the host total, so a 64 GiB container on a 512 GiB host got no pin budget. Fixed in 5f4b613: the total used for the reserve is capped by the cgroup capacity. Regression test: test_the_pin_reserve_is_sized_from_the_container_not_the_host (fails without the fix); the existing budget test now pins the cgroup reading so it does not depend on the host.

Comment on lines +5484 to +5486
companion_override_mib = estimate.companions_mib,
text_encoder_override_mib = estimate.text_encoders_mib,
text_encoder_quant = text_encoder_quant,

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 Reprice the in-place pipeline quantization replan

This replan still passes estimate.companions_mib and estimate.text_encoders_mib, which describe the dense encoders, even when text_encoder_quant makes assembly inject a much smaller hosted pre-cast encoder. Passing text_encoder_quant here does not correct those values because _plan_memory only applies _precast_text_encoder_mib when companion sizes came from cache, not when caller overrides are present. Consequently an in-place quantized pipeline can be assigned encoder streaming or have quantization declined on a card where its actual pre-cast weights fit fully resident; this call should use _candidate_companion_overrides, as the other candidate replans now do.

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.

Agreed, that was the one candidate replan still passing the dense encoder terms. Fixed in 5f4b613: it now uses _candidate_companion_overrides like the GGUF and seed replans. Regression test: test_a_pipeline_quant_replan_prices_the_encoder_the_load_opens (fails without the fix).

…lans; size the pin reserve from the cgroup capacity
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 25, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 5f4b613196

ℹ️ 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 self-assigned this Sep 25, 2026
# Conflicts:
#	studio/backend/tests/test_diffusion_backend.py
# Conflicts:
#	studio/backend/core/inference/diffusion_memory.py
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

@shimmyshimmer

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 45ad41cd20

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 45ad41cd20

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

# Conflicts:
#	studio/backend/core/inference/diffusion.py
#	studio/backend/core/inference/diffusion_memory.py
#	studio/backend/tests/test_diffusion_backend.py
#	studio/backend/tests/test_diffusion_memory.py
#	studio/backend/tests/test_diffusion_pipeline_prequant.py
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@shimmyshimmer

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c0c16a3c5d

ℹ️ 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 f2a9375 into main Sep 25, 2026
35 of 37 checks passed
@danielhanchen
danielhanchen deleted the studio-q21-small-card-placement branch September 25, 2026 22:15
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…er resident and the text encoder streamed (unslothai#11883)

* Studio: price the hosted pre-cast text encoder and keep the transformer resident when only the encoder does not fit

* Studio: pin the streamed-encoder tiers when host RAM allows, transformer first

* Studio: price only the encoder folders a pre-cast checkpoint replaces, pin at allocator size, stream the transformer if a late encoder refuses

* Format

* Studio: never price a cached pre-cast encoder below its dense shards

load_prequant_text_encoder can return None for a cached checkpoint too, and
assembly then opens the dense shards on disk, so budget max(pre-cast, scanned
dense) whether or not the checkpoint is cached. The prefetch skips covered
shards, so the usual case is unchanged, and the resident-denoiser tier only
streams encoders, so the 24 GB placement holds even with dense shards cached.

* Studio: do not pin streamed modules on Windows or WSL, and unhook a partly offloaded encoder before falling back

WDDM and WSL2 cap page-locked host memory near 1 GiB whatever RAM is free, so pinning a multi-GB encoder or transformer failed part way. On the resident-transformer tier the leaf hooks left by that failure made enable_model_cpu_offload reject the pipeline and the load failed. Those hosts keep the unpinned streaming they had before, and a first-encoder refusal now drops its hooks before whole-module offload takes over.

* Studio: keep a torchao denoiser resident with the text encoder streamed on small cards

* Studio: tests for the torchao resident-transformer placement

* Studio: quote the encoder-streamed floor when a torchao build is declined

* Studio: leave the pipeline replan's encoder sizing as it was

* Format

* Price the in-place pipeline quant replan's encoder like the other replans; size the pin reserve from the cgroup capacity

* Studio: trim comments

* Studio: do not add a pre-cast encoder on top of a bf16 table-priced pipeline

* Format

* Trim comments

* Format

* Keep main's native-quant tests whole beside this PR's placement tests
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.

2 participants