Skip to content

Studio diffusion: learned activation peaks, OOM retry in group offload setup, pinned GGUF host copies, tied-weight groups - #13724

Merged
danielhanchen merged 37 commits into
mainfrom
studio-diffusion-learned-peaks-offload-fixes
Oct 15, 2026
Merged

danielhanchen merged 37 commits into
mainfrom
studio-diffusion-learned-peaks-offload-fixes

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Memory planner and offload fixes for diffusion and video, found while auditing Studio on 8 / 12 / 16 / 24 GB cards.

  1. Learned activation peaks. The planner reserved a flat 8 GiB per megapixel for any family missing from the measured-peak table, so FLUX.2-klein streamed its whole DiT at 16 GB while using 4.6 GiB. New diffusion_measured_peaks.py records the real peak of each successful image and video render (per model, quant, resolution bucket and frames) in <cache_root>/diffusion_measured_peaks.json and uses it on later loads. The static tables stay as the seed; a learned value can only raise it, never lower it, and stored values only rise. A render that absorbed a failed CUDA-graph capture does not record a peak. The per-request memory guard keeps the static seed for families that have one. Opt-out: UNSLOTH_DIFFUSION_LEARNED_PEAKS=0.
  2. OOM retry during group-offload setup. A transient CUDA OOM while setting up group offload (for example another app briefly taking VRAM) used to become a hard load failure. Studio now empties the cache and re-plans once at a lower placement; image and video callers use the re-planned result.
  3. Pinned GGUF host copies. The background pinner skipped GGUF parameter copies, and those unpinned host copies made the offloaded CUDA graph refuse to capture. They are now pinned within the existing pin budget.
  4. Tied-weight offload groups (bug). With part of a model kept resident, two offload groups that share a tensor could be split between resident and streamed. Klein's Qwen3 text encoder ties lm_head to embed_tokens, so the second prompt crashed with index on cuda:0 ... cpu. Groups that share a tensor now stay resident or stream together.
  5. The resident text-encoder room is clamped to the encoders' real size, and the placement log names a transformer the plan already keeps resident.

Results

Case Hardware main this PR Speedup Output vs main
FLUX.2-klein-4B, 16 GB card, 1024 px, 4 steps B200, allocator capped to 16 GiB 0.261 s/step (DiT streamed, peak 2.3 GiB) 0.039 s/step first load, 0.046 s/step reusing the learned file (3865 MiB DiT resident, peak 9.3 GiB) 5.7x to 6.7x 67-68 dB PSNR, within the A/A spread
FLUX.2-klein-4B, 16 GB card RTX PRO 6000, capped to 16 GiB 0.0998 / 0.1018 s/step (peak 2361 MiB) 0.1018 / 0.0978 s/step (DiT and 7673 MiB of encoders resident, peak 9563 MiB) none (streaming already hidden behind compute) bit-identical / 60.8 dB, same as base A/A
FLUX.2-klein-4B, 24 GB card RTX PRO 6000, capped to 22 GiB 0.102 / 0.051 s/step (peak 5585 MiB) 0.1018 / 0.0977 s/step (text encoder resident, peak 13312 MiB) none first run bit-identical; a second run differed at 32-36 dB PSNR, not root-caused
Wan GGUF, 8 GB card, one clip B200, capped to 8 GiB 79.1 s per clip (0 GiB pinned, CUDA graph refused) 47.8 s per clip (3.0 GiB pinned, CUDA graph kept) 1.65x n/a
Wan GGUF, 8 GB card Kaggle T4, 29 GB host RAM 5.5 s/step 5.5 s/step none (only 4 GiB of host RAM pinnable) bit-identical
Wan2.2-TI2V-5B auto route, 24 GB card, 832x480x33 RTX PRO 6000, capped to 22 GiB 0.1840 s/step 0.1844 / 0.1844 s/step none (route unchanged) n/a
FLUX.2-klein-4B, transient OOM during group-offload setup RTX PRO 6000, capped to 16 and 22 GiB, filler allocations load fails at both caps logs group offload setup hit OOM, re-plans, loads, renders at 0.1018 s/step load failure becomes a working render bit-identical to a normal render
  • The speedups come from keeping more of the model on the GPU (learned peaks) and from keeping the CUDA graph under offload (pinned GGUF host copies). Where streaming was already hidden behind compute, or the host cannot pin enough RAM, the PR is speed-neutral and the output is unchanged.
  • Checked and left unchanged: the stream_transformer flag after refine_plan_from_loaded_weights does not block fused int8 GEMM or graphs (both engaged at 16 and 22 GiB). The Wan2.2-TI2V-5B auto route at 24 GB is the right one: low_vram with a graph measured 0.1976 s/step, about 7% slower.
  • These numbers were measured on the PR's first revision. The later review rounds narrowed where learned peaks apply (no LoRAs, no whole-module offload, no peaks after a compile fallback, peaks dropped on a torch or diffusers upgrade) and were not re-timed.

Tests

  • New studio/backend/tests/test_diffusion_learned_peaks.py; updated test_diffusion_measured_placement.py. The GGUF-pinning and tied-weight tests fail on main and pass here.

Not covered: no real 12 / 16 / 24 GB consumer card (the capped runs are a larger card with a capped allocator); timings are single runs on shared hosts.

…d setup, pinned GGUF host copies

- Record the real CUDA peak above resident weights per (family, denoiser quant,
  speed tier, resolution bucket, frames) at each completed render and persist
  it under the Studio cache dir; later loads place from it. Static tables stay
  the seed (a learned peak raises a seed, never lowers it), and a quantised
  family missing from the peak table is seeded from its per-phase calibration,
  so FLUX.2-klein keeps its DiT resident on a 16 GB card.
- Video request peaks persist through the same store.
- A transient OOM while setting up group offload re-plans once with the
  transformer and text encoders streamed before refusing.
- The background pinner pins GGUF host copies so a streamed GGUF denoiser can
  record its copies in a CUDA graph.
…led graph capture

A failed capture (an OOM caught by the graph layer) leaves the render's peak at
the failed attempt, so recording it would make later loads stream more than
they need. Image and video recording both check the process failure count.
A learned peak recorded by a session's own render places the next load; it must
not stream resident groups for a request the size of one that just completed.
Families without a seed still check against their learned peak.
A text encoder that ties its LM head to the embedding (Qwen3, used by
FLUX.2-klein) has the shared weight in two leaf groups. Partial residency could
pin one and stream the other; the streamed group's offload then pointed the
shared tensor back at the host copy, and the next prompt encode failed with a
device mismatch. Groups that share a tensor are now made resident and released
as one unit.
…ident transformer in the placement log

With the DiT already resident in the flat plan, the log read '0 MiB of the
transformer and 10970 MiB of the 7673 MiB encoders stay resident'.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 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-14T23:41:47.284071Z 91ad6bc Manual request
🔒 Security Review ⚠️ Failed 2026-10-14T13:17:58.805287Z 72254ac 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[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits October 14, 2026 13:44
…, lock the store; OOM after partial hooks retries

A render whose prompt came from the prompt or conditioning cache skipped the
text encoder, so its peak is not recorded. Learned peaks are keyed by the GPU
name. Store updates take an interprocess file lock and re-read the file under
it. An OOM after some group-offload hooks exist unwinds them so the one
lower-residency retry runs instead of the load failing.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…y attention backend, LRU-capped; request guard scales the load-time learned peak; video peaks re-read from the store and keyed by GPU name
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…d scales the load-time peak from the bucket it covers
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…e card, let a partial-hook failure in the setup OOM retry propagate, key learned peaks by VAE savers
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…er precision, engaged VAE savers, attention) and records nothing when a render differs; normalise peaks to the streamed baseline, scale math-attention peaks squared, window the video residency fit, return torchao weights tensor-wise in the setup OOM retry
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 14, 2026
@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: 903b13dd5b

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

for mode in ("step", "blocks")
]
found = [f for f in found if f is not None]
return max(found, key = lambda f: f[0]) if found else None

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 the conservative envelope across graph modes

When graphs:step and graphs:blocks have peaks from different source buckets, selecting the currently larger value also selects only that entry's coverage metadata. For example, a 3000 MiB step peak covering 4 MP wins over a 2900 MiB block peak covering 1 MP at load time; if placement then arms block graphs, a later 2 MP request treats the reserved 3000 MiB as already covering it, even though the block entry scales to 5800 MiB. This can retain too many resident groups and OOM, so the two modes need a shared conservative scaling envelope or the request guard must query the engaged mode.

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 b6d5780. A graphs:on lookup now returns one envelope over both modes: the larger peak, the smaller covered size, and squared scaling if either mode scales squared, so a later request scaled from the reservation never needs less than whichever mode placement armed.

Comment on lines 377 to 378
shared = _key_peaks(key)
shared[work] = max(extra, shared.get(work, 0))

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 Normalize the in-process video peak before reuse

Fresh evidence after the persisted-baseline fix is that the process-local keyed table still receives raw extra, while only record_work() receives extra + pad. When persistence is disabled, unavailable, or intentionally skipped for an unknown revision, subsequent requests reuse this raw value; if the measured request kept groups resident and a later request streams them, the reused peak omits the prefetch window and can leave too many groups resident. Store the normalized value in shared as well, while retaining the raw per-module diagnostic value if needed.

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 b6d5780. The in-process keyed table now stores the same padded value that is persisted; the module's own table keeps the raw peak for diagnostics, and when the pad cannot be sized the keyed table records nothing.

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

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


def note_capture(device_index: Optional[int]) -> None:
"""Count a recorded graph (whole-step or per-block) on ``device_index``; see ``capture_generation``."""
_CAPTURES[device_index] = _CAPTURES.get(device_index, 0) + 1

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 Serialize capture-generation increments

When image and video render threads capture graphs concurrently on the same device, this read-modify-write can lose an increment. If both captures replace entries in full caches, live_graph_count() also remains unchanged, so a failed or cancelled request's replacement can go undetected and the next probe may persist a peak whose baseline already includes that graph allocation. Protect the per-device increment with a lock or another atomic counter.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 14, 2026 •

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 82b129d. note_capture now updates the per-device capture count under a module lock, so concurrent image and video captures cannot lose an increment.

Comment on lines +372 to +375
# a failed capture absorbed an OOM: this peak is that attempt's, keep it out of the keyed and persisted peaks
if key is not None and _failed_captures() == getattr(
module, "_unsloth_video_failed_captures", 0
):

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 poisoned graph loads out of video calibration

After a video request suffers a transient CUDA-graph capture failure, this check correctly excludes that request, but the graph wrapper remains poisoned and subsequent requests run eager without increasing failed_capture_count(). Those later eager peaks are therefore accepted under the same calibration key whose speed_optims still says CUDA graphs are enabled; a fresh process that successfully captures the graph can reuse the smaller eager peak, retain too many groups, and OOM on graph statics or pools. Reject calibration while the keyed graph mode is no longer live, as the image probe does.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 14, 2026 •

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 82b129d. When a video request's calibration key lists cuda_graph, its peak is now recorded only if live_status says the load's graphs still run, the same rule as the image probe, so eager requests after a failed capture no longer calibrate a graph key.

@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: 82b129d256

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

except Exception: # noqa: BLE001
pass
peak_vae = planned_vae_saver_tag(pipe, plan)
peak_te = str(te_quant or "dense")

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 Key partially quantized text encoders separately

When automatic text-encoder quantization only succeeds for some encoders, or precision fallback is allowed, quantize_text_encoders() returns the requested mode with partial=True and the load continues with a mixture of quantized and dense encoders. Reducing that state to te_quant gives it the same learned-peak key as a fully quantized load; a lower peak recorded by the fully quantized build can therefore be reused before placing the mixed build, whose dense encoder may require more activation/workspace memory, leaving too many groups resident and causing an OOM. Include the per-encoder applied formats or mark partial outcomes as unidentified.

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 91ad6bc. A partial text-encoder cast now puts te:unknown in the learned-peak key, so a mixed build neither reads nor records a learned peak and places from the static estimate.

@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: 91ad6bc032

ℹ️ 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 1f74450 into main Oct 15, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-learned-peaks-offload-fixes branch October 15, 2026 10:37
danielhanchen added a commit that referenced this pull request Oct 15, 2026
#13749 and #13828 (#13846)

#13724 landed with three CI jobs red, #13749 left a picker contract test
behind, and #13828 added a test file the formatter and encoding checks
reject, so main fails `(Python 3.13, a-k)`, `(Python 3.13, rest)`, `Repo
tests (CPU, rest)` and `Repo tests (CPU, studio)` on every PR. This
brings those tests back to green. No runtime behaviour changes beyond
naming the peak store's encoding.

## What was failing on main (`59ab069b5`)

- `test_text_io_names_its_encoding[diffusion_measured_peaks.py]` and
`test_shipping_code_names_an_encoding`: the learned-peak store reads
with `read_text()` and writes through `os.fdopen(fd, "w")` without an
encoding, so the locale decides it (cp1252 on Windows, ASCII under a C
locale).
- `test_calibration_records_and_reuses_for_any_family`,
`test_retagged_peak_is_recorded_under_the_mode_that_ran`:
`record_request_peak` now records a keyed peak only when
`stream_window_pad_mib(pipe)` can size the placement ("an unknown
placement enters neither the keyed table nor the store"). The tests'
fake pipe has no placement, so nothing was recorded and
`measured_extra_mib` returned `None`.
- `test_oom_inside_the_first_offload_apply_unwinds_its_hooks` imports
`diffusers.hooks` directly, and the Backend CI runners have no
diffusers, so it errors with `ModuleNotFoundError` there instead of
skipping.
- `test_diffusion_capability_labeled_image_video_gen`
(`tests/studio/test_model_picker_contracts.py`) still expects
"Image/video gen" in all three Hub files. #13749 split the Hub filter
into "Image gen" and "Video gen" and only rewrote the comments that held
the old label in the other two.
- `test_every_tracked_python_file_is_already_formatted` and
`test_checked_in_file_reads_name_an_encoding`:
`tests/test_triton_fp_fusion.py` (#13828) is not a fixed point of
`scripts/run_ruff_format.py` and reads four kernel sources with
`read_text()` and no encoding.
- `test_calibration_revision_includes_the_companion_base`:
`_calibration_revision` now uses `_peak_model_identity`, which keys on
`source@revision` plus `+base@base_revision` for a GGUF or single-file
load, not the old bare fingerprint and `|base=` suffix.

## Fix

- `diffusion_measured_peaks.py`: `encoding = "utf-8"` on the read and on
the write. `json.dump` writes ASCII by default, so existing peak files
read the same.
- The two peak tests run under a known on-card placement
(`stream_window_pad_mib` patched to 0), the case #13724 still records.
- The OOM test uses `pytest.importorskip("diffusers.hooks")`, the same
guard the rest of the file uses for optional dependencies. It still runs
where diffusers is installed.
- The label test still checks that no Hub file says "Image to text". It
now asserts the filter label `{ value: "diffusion", label: "Image/video
gen" }` in `model-type-filter.ts` and the split `Image gen` / `Video
gen` options in `view-models.ts`.
- `tests/test_triton_fp_fusion.py`: `encoding = "utf-8"` on its four
reads, then `python scripts/run_ruff_format.py` on it.
- The revision test asserts the new identity format. It still checks the
same three things: no base for a pipeline load, the base for a GGUF
load, and a different base giving a different key.

## Tests

With no GPU visible (as on the CI runners),
`test_diffusion_component_sizes.py`, `test_text_io_encoding.py` and
`test_diffusion_learned_peaks.py`: 4 failed on main, 984 passed and 0
failed here (with current main merged in).
`tests/test_runtime_text_encoding.py`: 9 passed.
`tests/studio/test_model_picker_contracts.py`: 201 passed.
`tests/test_triton_fp_fusion.py`, `tests/test_formatter_fixed_point.py`,
`tests/test_source_read_encoding.py`,
`tests/test_runtime_text_encoding.py`: 43 passed, 2 skipped. The OOM
test skips cleanly when diffusers is not importable, and passes where it
is.
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…tall downloads (#13847)

## Problem

#13724's learned activation peaks never engage on a default install.

- **The key:** learned peaks are keyed on the exact model build.
`_peak_model_identity` reads it from `checkpoint_fingerprint(repo_id)`,
using the vendor repo id the family names, for example
`black-forest-labs/FLUX.2-klein-4B`.
- **What Studio downloads:** for every mirrored base, Studio fetches
from the byte-identical `unsloth/` mirror instead
(`unsloth/FLUX.2-klein-4B`, `prefer_ungated_mirror`).
- **What goes wrong:** on a machine that never cached the vendor repo,
the fingerprint is empty and the key becomes `unknown`. No peak is ever
recorded or read, and the planner keeps streaming the DiT exactly as
before #13724.
- **Why tests missed it:** they only engaged where the vendor repo
happened to be in the HF cache.

Still true on main today (`c08dfbbe64`): `_peak_model_identity(repo_id,
gguf_filename, kind, base)` reads only the vendor id.

## Change

- The image load passes `fetch_base` (the repo it actually read) into
`_peak_model_identity`. The key names that repo and its revision: the
mirror on a fresh install, the vendor repo when the vendor cache
satisfied the load. This holds for the pipeline itself and for the
companion base of a GGUF or single-file load.
- A caller without a load decision (the video calibration key) falls
back to the `unsloth/` mirror's revision when the vendor repo has no
cached revision.
- A GGUF file's own fingerprint is unchanged, and a repo that is neither
cached nor mirrored still keys as `unknown`.

## Results

Fresh-install layout: an HF cache holding only the `unsloth/` mirrors
(vendor repos absent), offline, FLUX.2-klein-4B on the default speed
tier at 1024x1024, 16 GiB allocator cap, two loads per process in a
fresh Studio home.

| | main | this PR |
|---|---|---|
| Model part of the key | `model:unknown` |
`model:unsloth/FLUX.2-klein-4B@04e0a8a...` |
| Render 1 records a peak | no (`record -> False`) | yes, 3223 MiB |
| Load 2 reads it | no | yes: `3865 MiB of the 3865 MiB transformer and
3216 MiB of the 5940 MiB encoders stay resident (measured peak 3840
MiB)` |
| Output | identical | identical |

Speed, Colab A100 40 GB, same cell (default tier: torchao int8,
compiled, CUDA graphs), 16 GiB cap, order base, head, head, base, each
arm two loads, median s/step of 3 renders:

| Arm | load 1 | load 2 |
|---|---|---|
| main (arms 1, 4) | 0.602, 0.601 | 0.602, 0.600 |
| this PR (arms 2, 3) | 0.601, 0.601 | **0.552, 0.552** |

That is 1.09x on load 2 (0.601 to 0.552), with peak allocation 2314 MiB
on main and 6416 MiB here (more of the model resident). Within a process
the image is bit-identical between load 1 and load 2. Across processes
the compiled int8 tier already gives different bytes on main itself (arm
1 vs arm 4), so that comparison is not a placement effect.

On a Colab A100 VM (a real fresh install that downloads from the
mirror), the stored keys were `model:unsloth/FLUX.2-klein-4B@04e0a8a...`
and
`model:unsloth/Z-Image-Turbo-GGUF/z-image-turbo-Q8_0.gguf@6c80814...+unsloth/Z-Image-Turbo@dd53895...`,
never `unknown`.

## Tests

- `test_peak_model_identity_reads_the_unsloth_mirror_on_a_fresh_install`
and `test_peak_model_identity_keys_on_the_repo_the_load_fetched` (new)
and `test_peak_model_identity_names_the_whole_build` (call-site check,
now whitespace-free so the formatter cannot break it): all 3 fail on
main and pass here.
- `test_diffusion_learned_peaks.py`,
`test_diffusion_measured_placement.py`,
`test_video_stream_residency.py`, `test_video_backend.py` on CPU, main
vs this branch: 3 fixed, 782 unchanged, 0 new failures. 4 tests fail on
both sides and are not touched here
(`test_background_pinner_pins_gguf_host_copies` and three video peak
persistence tests).

## Not covered

- Video keys: the mirror fallback applies, but no video load was run.
- Only FLUX.2-klein-4B and Z-Image-Turbo were run. The change applies to
every pair in the mirror table.
- Windows: `checkpoint_fingerprint` uses `try_to_load_from_cache` and
matches the snapshot on the POSIX form of the path, so a cache without
symlinks resolves the same way. Not run on Windows.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…eir learned peak (#13860)

Stacked on #13847 (learned peaks keyed on the unsloth mirror). Without
it a fresh install keys every build as `unknown`, so nothing here
engages. Merge #13847 first. Both branches now carry current main
(`c08dfbbe64`), merged cleanly.

## Problem

#13724 records a learned activation peak at every completed image
render, and `refine_plan_from_loaded_weights` reads it on the next load
to keep more of the model resident. For a dense denoiser that function
still returns before the learned lookup on main when:

- the compute dtype is bf16 (`_denoiser_compute_bytes` is None), or
- the weights are GGUF or int8 packed (`_pipe_denoisers_hold_packed`).

The early return exists because the static dense eager table was
measured on fp16 / fp32 unpacked weights only. That is a reason to skip
the table, not the learned peak, which is a real measurement of the
exact build (model revision, quant label, VAE savers, attention backend,
graphs, GPU name). These loads recorded a peak on every render that no
later load ever read: every dense load on a bf16 card (Ampere and newer)
and every GGUF image load kept the flat 8 GiB/MP estimate and streamed
the whole denoiser.

## Change

- `measured_image_runtime_mib(..., static_seed=True)`: with
`static_seed=False`, every static table is skipped and the answer comes
from the learned peak alone (None when nothing was recorded).
- `refine_plan_from_loaded_weights`: a bf16 or packed dense denoiser
sets `static_seed=False` instead of returning. With no learned peak the
lookup answers None and the flat plan stands, which is today's
behaviour. Dense loads keep the conservative branch: the whole-DiT and
wide-window pins stay torchao-only.
- The reserve the request guard reads carries the flag
(`_unsloth_measured_reserve[8]`), so a learned-only load never sizes
requests from the fp16 table. Older 8-field reserves read as before. A
layer split still drops the reserve (#14412), unchanged.
- A family that can run classifier-free guidance used to skip recording
every render without it, so Z-Image-Turbo at its default guidance 0
never learned a peak. Such a render now records under `<label>|cfg:off`.
A load reads that key only when no CFG peak exists, and marks the
reserve. The request guard then sizes any request that runs CFG, or
whose guidance mode is unknown, from the flat estimate, because the
doubled denoiser batch was never measured. Kill switch:
`UNSLOTH_DIFFUSION_LEARNED_PEAKS_CFG_OFF=0`.
- Unchanged: fp16 / fp32 dense and torchao loads, "a learned value only
raises a seed", non-CUDA and unified-memory devices (the refine is a
no-op there), and every kill switch
(`UNSLOTH_DIFFUSION_LEARNED_PEAKS=0`,
`UNSLOTH_DIFFUSION_MEASURED_ACTIVATION=0`,
`UNSLOTH_DIFFUSION_MEASURED_ACTIVATION_DENSE=0`,
`UNSLOTH_DIFFUSION_PARTIAL_RESIDENT=0`).

## Results

Colab A100 40 GB, allocator capped, fresh VM (models downloaded from the
`unsloth/` mirrors). Base is main + #13847, head is this branch, both at
current main. Order base, head, head, base. Each arm loads twice in a
fresh Studio home: load 1 has no learned peak and records one, load 2
reads it. Median s/step of 3 renders at 1024x1024, speed tier off.

| Case | base load 1 / load 2 (arms 1, 4) | head load 1 / load 2 (arms
2, 3) | head placement on load 2 | Peak alloc base / head | Output |
|---|---|---|---|---|---|
| FLUX.2-klein-4B bf16, 10 GiB | 0.643 / 0.643, 0.641 / 0.641 | 0.643 /
**0.491**, 0.641 / **0.489** | 1943 of 7393 MiB DiT resident (learned
peak 2816 MiB reserved) | 2620 / 4397 MiB | bit-identical |
| FLUX.2-klein-4B GGUF Q8_0, 8.75 GiB | 0.687 / 0.687, 0.689 / 0.688 |
0.686 / **0.311**, 0.689 / **0.310** | 663 of 4102 MiB DiT resident |
2620 / 3245 MiB | bit-identical |
| Z-Image-Turbo GGUF Q8_0, guidance 0, 10 GiB | 0.621 / 0.623, 0.621 /
0.622 | 0.622 / **0.484**, 0.621 / **0.484** | 1946 of 6888 MiB DiT
resident, from its `cfg:off` peak | 2611 / 4562 MiB | bit-identical |
| FLUX.2-klein-4B GGUF Q8_0, 10 GiB | 0.239 to 0.241 throughout | 0.239
to 0.241 throughout | unchanged: the plan is whole-module offload, out
of scope | 4842 / 4842 MiB | bit-identical |

- Speedups on learned loads: klein bf16 1.31x, klein GGUF 2.21x, Z-Image
GGUF 1.28x. Every load without a learned peak matches base within 0.5%,
which is also the base-vs-base spread.
- No OOM in any arm. The stored keys name the mirror
(`model:unsloth/FLUX.2-klein-4B@04e0a8a...`), and the Z-Image peak is
stored with a trailing `cfg:off` part. Base records no Z-Image peak at
guidance 0.
- A local B200 run (host heavily loaded, so timings are noisy) with an
offline HF cache holding only the mirrors showed the same placements and
bit-identical images: klein GGUF 0.80 to 1.01 s/step down to 0.13, while
klein bf16 (0.148 vs 0.154) and Z-Image (0.16 to 0.19 vs 0.17) moved
within that host's noise. On a card this fast the streamed bf16 copy
hides behind compute, so the gain depends on the card's compute to PCIe
ratio.

## Tests

- `test_diffusion_learned_peaks.py`: the CFG test now asserts the
`cfg:off` key (it pinned the old skip), plus 2 new tests for the load
fallback / guard and the wiring (the wiring check is whitespace-free so
the formatter cannot break it).
- `test_diffusion_measured_placement_dense.py`: 5 new tests, all failing
without this change:
- bf16 and GGUF denoisers place from a recorded learned peak, and each
kill switch restores the flat plan.
- An fp16 load keeps its 3072 MiB table seed over a lower learned peak.
- The request guard of a learned-only load scales the learned peak and
ignores the fp16 table.
  - The load stores the flag in the reserve.
- CPU, base (main + #13847) vs this branch, over
`test_diffusion_learned_peaks.py`,
`test_diffusion_measured_placement.py`,
`test_diffusion_measured_placement_dense.py`,
`test_diffusion_small_host_planner.py`, `test_offload_planner.py`,
`test_diffusion_gguf_offload_route.py`,
`test_diffusion_stream_residency.py`, `test_video_stream_residency.py`,
`test_diffusion_offload_seed_balanced.py`,
`test_group_offload_background_pin.py`: 6 fixed, 2 new, 573 unchanged, 6
skipped (CUDA only), 0 new failures. 4 tests fail identically on main
and are not touched here (`test_background_pinner_pins_gguf_host_copies`
and three video peak persistence tests).

## Not covered

- Video: this PR changes no video path.
- LoRA loads still skip learned peaks. Runtime adapters attach after
placement, so this needs a measured per-adapter overhead term, not just
a key.
- On the default speed tier a streamed load is labelled `graphs:on` but
can render graph-free and record under `graphs:off`, so that peak is not
read back. Follow-up: re-refine after the graph decision.
- CFG requests on a load placed from a `cfg:off`-only peak are sized
from the flat estimate (resident groups stream again for that request)
until a CFG render records its own peak. Covered by CPU tests, not by a
GPU run.
- No real 8 / 10 / 12 GB consumer card, no AMD card and no Windows run:
a larger card with a capped allocator. macOS / MPS and CPU are untouched
(the refine returns before any of this on non-CUDA and unified memory).

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant