Skip to content

Studio diffusion: choose whole-module vs streamed offload per request from its step count - #15163

Merged
danielhanchen merged 6 commits into
mainfrom
studio-diffusion-offload-tier-per-request
Oct 24, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
studio-diffusion-offload-tier-per-request

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

#15129 keeps a bf16 denoiser that sits just above the streamed floor in whole-module offload instead of group streaming. Which of the two is faster depends on the request's step count, which a load cannot know:

This PR makes the choice per request.

Changes

  • At load:
    • Each mode is priced with a 0.1 s probe of this card's pinned host-to-device bandwidth and bf16 matmul rate, at the family's default step count:
      • whole-module = upload + steps x compute;
      • streamed = steps x max(compute, transfer).
    • Where whole-module wins (B200, A100), main's plan is placed unchanged.
    • Elsewhere the streamed plan is placed, and the probe readings are kept on the pipe.
  • Per request:
    • Each generate() is priced with its own steps, canvas, batch, CFG and condition images.
    • When that prices whole, every streamed offload group of the denoiser is made resident after the prompt encode, then streamed again when the decode starts. That is one upload per call, through the streamed tier's own hooks: no hook swap, and the pinned host copies are reused.
    • The blocks compile below the offload hooks, so compiled code never sees the move.
  • When it keeps the load's plan:
    • a background compile is pending;
    • a CUDA graph over the denoiser is still live or undecided;
    • a step cache is on;
    • the card does not have room right now for the weights plus this machine's learned pre-decode peak for the request's size.
  • Pre-decode peak lookup: after the deferred compile, the attention label and the speed tier in the peak key both change, and graph-captured renders record no peak. So the lookup falls back to the key the load's eager renders recorded.
  • Kill switches:
    • UNSLOTH_DIFFUSION_WHOLE_MODULE_PER_REQUEST=0 turns off the per-request part.
    • UNSLOTH_DIFFUSION_WHOLE_MODULE_OFFLOAD=1 restores main exactly.
    • UNSLOTH_DIFFUSION_WHOLE_MODULE_OFFLOAD=0 never uses whole-module offload.

Results

Colab G4 (RTX PRO 6000), real FLUX.2-klein-4B, 12.25 GiB cap.

  • Tree check: the notebook verified the installed studio/backend tree hash against the commit.
  • Arms:
    • main;
    • head_model: head with UNSLOTH_DIFFUSION_WHOLE_MODULE_OFFLOAD=1, the cross-tree A/A against main;
    • head;
    • head_group: head with the per-request part off.
  • Rounds: 3 rotated rounds of processes; each process did 2 warm-up rounds and 5 measured rounds, with a new prompt per round. Every measured 8-step render ran after the deferred compile and the CUDA-graph decision.
steps main head_model (A/A) head head_group
2 0.562 s 0.561 s 0.458 s (-18.5%) 0.458 s
4 0.624 s 0.623 s 0.617 s (-1.1%) 0.615 s
8 1.025 s 1.026 s 0.998 s (-2.6%) 1.182 s
  • 8-step spread: per-process medians were 0.997-0.999 s for head against 1.025-1.026 s for main.
  • Mode per request: head ran the denoiser whole on 15 of 15 measured 8-step renders, and streamed every 2- and 4-step render, as priced.
  • Images: md5 identical to main for all 21 images in every arm.
  • Compilation: 0 recompiles, 0 CUDA-graph captures and 0 FX cache misses on measured calls, in every arm.
  • VRAM (allocated / reserved MiB, cap 12544):
    • main: 7853 / 12294;
    • head streamed: 2266 / 11010;
    • head whole: 8021 / 11010.
  • B200 (local): the load picks whole-module, as main does, with identical images. This was checked on the first commit; the later commits change only the per-request peak lookup.

Tests

  • New tests/test_diffusion_offload_tier_per_request.py (12 CPU tests, 2 CUDA tests): the request pricing, the refusals, all-or-nothing pinning and release, the peak-key fallback, and the kill switches.
  • New tests/test_diffusion_placement_monotonic.py.
  • Memory planner, offload, background compile, cold start and CUDA graph files: 908 passed, 136 skipped.

Limits

  • After the compile engages, 8-step renders stream until the CUDA-graph decision is final, which on G4 is the 5th render.
  • Not measured: time to first image, A100 under the final commits, requests with CFG, a batch or reference images, and families other than FLUX.2-klein.

… for a bf16 denoiser

#15129 runs a plain bf16 denoiser just above the streamed floor with
whole-module offload. That wins where streaming is slow next to compute
(FLUX.2-klein-4B 1024^2 4 steps: B200 0.336 vs 0.595 s, A100 2.336 vs
3.429 s) but not on a card that streams fast at few steps: on an RTX PRO
6000 whole-module is 2.5% slower at 4 steps and 23% slower at 2, and 13%
faster at 8. Which tier wins depends on the request's step count, which
the load does not know.

The load now prices the switch with a one-off per-device probe (pinned
host-to-device bandwidth and bf16 GEMM rate, about 0.1 s):

  whole    = 1.5 * transfer + steps * compute
  streamed = steps * max(compute, transfer)

at the family's default step count. Where whole wins there (B200, A100)
the #15129 whole-module plan is placed unchanged. Where streaming wins,
the streamed plan is placed and the probe is kept on the pipe, and each
request is priced again with its own step count, canvas, batch and CFG.
A request that prices whole runs the denoiser whole for that call through
the streamed tier's own hooks: after the prompt encode every offload
group is pinned from its pinned host copy, and at the decode it streams
again, so the denoiser is uploaded once per call and the decode runs in
the streamed placement's room. Hooks, host copies and compiled code are
untouched: the blocks compile below their offload hooks, so a pin is a
weight move the compiled code never sees.

A request runs whole only when nothing compiled or recorded depends on
the placement: no background compile pending, every CUDA graph over the
denoiser declined or poisoned for the load and none alive on the card,
no step cache, and the card has room now for the unpinned weights plus
this machine's learned pre-decode peak for the request's size (the eager
tier's peak where a deferred compile tier records none). Otherwise the
call streams as placed. A whole call records no learned peak.

UNSLOTH_DIFFUSION_WHOLE_MODULE_OFFLOAD: auto (default), 1 = #15129's
unconditional switch, 0 = never. UNSLOTH_DIFFUSION_WHOLE_MODULE_PER_REQUEST=0
keeps the load's priced plan for every request.
…nders' learned peak

A deferred compile profile records no learned peak, and on an RTX PRO
6000 it also swaps the attention backend to cuDNN, so the live key after
the profile engaged matched nothing the eager renders recorded: every
later request that priced the denoiser whole streamed instead (Colab G4,
FLUX.2-klein-4B 8 steps: whole only on the second, eager render).

The pre-decode peak is now looked up under the live key, then under the
load's own label at its speed and at the eager tier, where the first
renders recorded it.
…est whole denoiser

On an RTX PRO 6000 the deferred profile rewrites the load's own learned
peak key (compiled tier, cuDNN attention), and a render after the
profile's graph capture records under no key, so the lookup by the load's
key still found nothing and every post-compile request that priced the
denoiser whole streamed (Colab G4, FLUX.2-klein-4B, 8 steps).

The first eager render's key is now kept with the per-request probe
readings and read last.
@danielhanchen danielhanchen self-assigned this Oct 24, 2026
@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 commented Oct 24, 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-24T21:28:19.873624Z 9723273 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.

@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: 50edd63114

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

steps = denoise_steps,
width = guard_width,
height = guard_height,
batch_size = guard_batch,

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 Price and budget the actual denoising chunk size

On non-Windows systems, guard_batch is always 1 because _activation_guard_batch() deliberately budgets only the singleton floor for OOM backoff. Reusing it here means multi-image chunks are both priced and checked for residency as single-image renders. For example, the new cost model selects whole-module residency for an 8-step RTX PRO 6000 request at batch 1 but streaming at batch 2, so an actual batch-2 render receives the slower placement. The activation lookup also uses the singleton peak, potentially pinning weights into memory needed by the batch and causing avoidable OOM retries. Make the tier decision using the actual chunk size rather than the activation guard's minimum batch.

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 9723273: the per-request choice is now priced and budgeted on the largest chunk the request actually runs (max(len(chunk) for chunk in chunks)), not the activation guard's singleton floor, so a batch-2 render is priced as batch 2 and its learned peak is read at that batch.

Comment on lines +3192 to +3195
batch_size = batch_size,
quant = key_label,
static_seed = False,
phase = "pre_decode",

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 Size whole-denoiser residency for the request workflow

For edit/reference requests, this lookup always reads the text-to-image peak: _live_peak_identity() does not include the workflow, while _record_peak_probe() explicitly stores non-txt2img measurements under with_workflow(...). Additionally, condition_pixels affects pricing but never increases this activation estimate. Consequently, after learning a small txt2img peak, a conditioned request can pin the entire denoiser using that smaller allowance even when its own recorded workflow peak requires more memory. This can undo the earlier guard's release of resident groups and OOM a singleton edit that would fit with streaming. Look up the workflow-specific peak and account for unmeasured conditioning, or decline whole-denoiser residency when that request is not covered.

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 9723273: the peak lookup is now keyed with with_workflow, so an img2img / inpaint request reads the peak recorded under its own workflow (and streams if none is learned). A request with condition images never runs the denoiser whole, since no recorded peak covers its condition sizes. Tests cover both.

…hunk and own workflow, never with condition images

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 972327324d

ℹ️ 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 90ccf12 into main Oct 24, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-offload-tier-per-request branch October 24, 2026 22:27
dayanruben pushed a commit to dayanruben/unsloth that referenced this pull request Oct 25, 2026
…ntegrated GPU (unslothai#15178)

## Summary

unslothai#15163 added a 0.1 s probe that times pinned host-to-device bandwidth
and bf16 matmul throughput, which the whole-module vs streamed offload
choice uses. The probe allocates a 256 MiB pinned host buffer without
asking `host_pinning_allowed()`. On an integrated GPU (an APU, where the
"VRAM" is system RAM), a pinned copy only takes RAM away from the card.
Every other pinning site already skips pinning there.


`tests/test_integrated_gpu_no_host_pin.py::test_every_pinning_site_asks_the_integrated_gpu_predicate_or_is_reached_through_one`
has failed on main since unslothai#15163:

```
pinning without asking host_pinning_allowed: core/inference/diffusion_memory.py:4072 _offload_cost_measurements
```

## Changes

- `_offload_cost_measurements` returns None when host pinning is not
allowed, as it already does off CUDA and on ROCm.
- An unpriced load keeps unslothai#15163's load-time behaviour: the whole-module
plan of unslothai#15129. That path's own host pinning already asks the predicate.
- Discrete GPUs are unchanged.

## Tests

- `tests/test_integrated_gpu_no_host_pin.py` passes again: it failed on
main with the message above.
- `tests/test_diffusion_offload_tier_per_request.py`: 52 passed, 2
skipped together with the guard test. The planner and offload suites
pass: 612 passed, 129 skipped.

## Limits

No run on a real integrated GPU here. The change only skips a probe on
the path the predicate already marks as integrated.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…rned peak (offloaded bf16 keeps its residency after compile) (unslothai#15198)

## Summary

On an offloaded dense bf16 load, the deferred speed profile (compile on
the 3rd image) made every compiled render keep less of the DiT resident
than the eager renders did.
- **Colab L4, FLUX.1-schnell bf16:** the load keeps 13498 MiB of the DiT
resident. From image 3 on, every render logged `streaming 3840 MiB of
resident groups for an oversized request` and kept 4321 MiB fewer. The
image-3 denoise moved 53.3 GiB host to device, against ComfyUI's 17.8
GiB.
- **Cause:** engaging the profile set `_unsloth_peak_static`. That sends
every later request in `measured_request_extra_mib` to the flat
estimate, 8192 MiB for FLUX.1 at 1024x1024, against the 4352 MiB the
load reserved. The compiled tier also never recorded a learned peak of
its own:
  - the identity kept `graphs:off` while the renders ran `graphs:step`;
- once a graph was captured unrecorded, every later probe saw it as
dirty.

## Changes

- **The compiled tier records its own learned peak.**
- After the profile engages, the identity's graph part follows the mode
the session runs (`_tier_graph_mode`). That mode stays the same through
the first capture: the armed mode until the graphs are captured and then
dropped, or settle eager, then `off`. So the render that captures the
graph records, and the renders after a dropped graph record under
`graphs:off`.
- **The request guard prices compiled renders from that peak.**
- `measured_request_extra_mib` takes `tier_peak_mib`, which is read only
under the live compiled key, graph mode included (`_tier_request_peak`).
- The price is the larger of that peak and the eager pricing the load
reserved. A compiled tier that measures lower never lowers it.
- The eager peak never stands in for the compiled tier here. Graph modes
do not stand in for each other either. Measured on B200: the render that
captured a graph recorded 1447 MiB, and the renders after the graph was
dropped recorded 2546 MiB.
- With no measurement yet (the first compiled render, a render waiting
on the background compile, LoRA adapters, CFG not covered by the peak),
the flat estimate stands in, as before.
- **No graph re-capture.** A CUDA graph captured over a release keeps
that release while the graph is live (`_hold_captured_release`), because
graphs key on weight addresses. Once no graph is live, the measured peak
places the renders.
- **Reuse of unslothai#15163:** its key list is now `_learned_peak_keys` /
`_learned_peak_for_keys`, shared by the whole-module per-request path
(unchanged: eager keys still stand in there) and the guard
(`eager_stand_in = False`).
- **Kill switch:** `UNSLOTH_DIFFUSION_TIER_PEAKS=0` restores the static
reserve and the flat estimate.

## Results

Local B200 with an L4-sized cap: the planner sees 23034 MiB, of which
450 MiB is held by others, and the caching allocator is capped there.
FLUX.1-schnell bf16 (`transformer_quant=none`), 1024x1024, 4 steps, a
new prompt per render, 9 timed renders plus 1 profiled render per
process, fresh learned-peak store per process. Timing arms had an
exclusive lease. Base is the merge base 3bf5e85.

Session 1 is a first session (empty store). Session 2 reuses the store a
session-1 process wrote.

| arm | DiT resident, images 3-9 (MiB) | H2D, profiled render | s /
image, image 9: median (range) over 3 processes | s / image, images 8-9
| images |
|---|---|---|---|---|---|
| base, session 1 (3 processes) | 9825 on every compiled render | 63.17
GiB | 1.393 (1.357-1.468) | 1.415 (1.366-1.482) | identical |
| head, session 1 (3) | 9825 for images 3-7, **13768** from image 8 |
**43.91 GiB** | **1.028** (1.028-1.046) | 1.226 (1.060-1.234): image 8
re-pins 3.9 GiB | identical |
| head, session 2 (3) | **13768** from image 4 (image 3 waits on the
background compile) | **43.91 GiB** | **1.093** (1.051-1.112) |
**1.074** (1.040-1.097) | identical |
| kill switch (1, shared lease) | 9825, as base | 63.17 GiB | not timed
| | identical |

- **Residency:** the load keeps 13768 MiB of the DiT resident (13498 on
the L4). Base streams 3840 MiB of it again on every compiled render.
Head does the same only until the compiled tier has its own measurement
and no graph captured over the release is live:
- in session 1, this B200 dropped the graph at image 6 (`replay measured
slower than the eager step`), so renders from image 8 keep it all;
- in session 2, the stored peak prices the first compiled render, so the
graph is captured over the full placement.
- **H2D:** the profiled render moves 30% less, which matches the
expected third.
- **Speed:** a steady compiled render takes about 25% less time
(1.03-1.11 s against 1.36-1.48 s). The base A/A spread over 3 processes
is 8%. Image 4 waits on the background compile in every arm: base
8.0-8.7 s, head session 1 7.8-11.2 s, head session 2 7.9-8.5 s. Its
placement is the same in both session-1 arms, so the one 11.2 s head
render is not explained by this change, but it was not re-run.
- **Images:** all 10 renders of every process are md5-identical to base:
10 processes, 100 images (the base session-2 process included).
- **Compile and capture:** 1 CUDA graph capture per process in every
arm. Dynamo counted 4 frames and 627 captured calls in base, head
session 1 and kill switch, and 3 frames and 492 calls in head session 2.
No arm recompiles or re-captures after the first compiled render.
- **Device memory (NVML, this process):** head never exceeds base. The
bg-compile and capture renders peak at 23.93-24.02 GiB in both arms.
Steady renders: base 19468 MiB; head session 2 17826-19468 MiB with 3.9
GiB more of the DiT resident.

**Compiled peak above eager (still handled).** Every compiled denoiser
forward holds 6000 MiB more (a pre-hook allocation), graphs off:

| arm | release per compiled render | DiT resident | peak allocated |
images |
|---|---|---|---|---|
| base | 3840 MiB (flat estimate) | 9825 | 18235 MiB | identical |
| head | 3840 MiB on image 4, then **5120 MiB** from the recorded 8129
MiB peak | **8529** | **16938 MiB** | identical |

The flat estimate under-prices this request, and head streams more to
cover it. With graphs on, the graph captured over the 3840 MiB release
stays live on that run, so head keeps that release. No arm hit an OOM.

**Other family:** Qwen-Image-2.1 bf16 at the same cap, 8 steps. The
transformer stays resident in both arms. The renders, the H2D (14.1
GiB), the graph capture and the dynamo counts (3 frames, 488 calls) are
identical to base. Head also records the compiled tier's 3061 MiB peak.

## Tests

- **New `tests/test_diffusion_tier_peaks.py` (21 tests):**
  - the flat estimate before the first measurement;
  - a compiled peak inside the reserve releasing nothing;
  - a larger compiled peak streaming exactly the difference;
  - a lower one never undercutting the eager pricing;
  - VAE-saver / LoRA invalidation still pricing flat;
- the eager key never standing in, and each graph mode answering only
for itself;
  - a pending background compile pricing flat;
  - the identity following the kept graph mode;
  - `_tier_graph_mode` across capture / drop / poison / decline;
  - the held release while a graph is live;
  - the kill switch.
- **Memory planner, learned peaks, offload, placement, CUDA graph, bg
compile and seed suites (45 files):** 1951 passed, 159 skipped. Base:
1935 passed, 159 skipped.

## Limits

- **Real L4 not run.** The cap emulates the planner's view and the
caching allocator. NVML peaks include VMM ranges and the graph pool,
which the cap does not bound. On this B200 the compile renders peak at
about 24.0 GiB in both arms, above an L4's 23034 MiB. So the absence of
an OOM is shown only for the allocator-capped part, and only relative to
base.
- **First session, graph kept:** on a card that keeps its CUDA graph
(this B200 in some runs), the first session keeps the release the graph
was captured over until a reload. The next session prices from the
stored peak from the first compiled render. On the L4 the graph is
dropped two renders after capture, so session 1 recovers there as on
this B200.
- **Mixed request sizes:** the held release follows the latest capture.
A request that captures a second shape over a different release can make
the first shape re-capture once.
- **Not measured:** the image-3 / image-4 stall (R3 (a)), ROCm, Windows,
and the speed effect on a real L4.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant