Skip to content

Studio diffusion: key learned peaks on the unsloth mirror a fresh install downloads - #13847

Merged
danielhanchen merged 8 commits into
mainfrom
studio-diffusion-learned-peaks-mirror-key
Oct 21, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-diffusion-learned-peaks-mirror-key

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

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 Studio diffusion: learned activation peaks, OOM retry in group offload setup, pinned GGUF host copies, tied-weight groups #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.

…tall downloads

_peak_model_identity fingerprinted the vendor repo id (e.g. black-forest-labs/FLUX.2-klein-4B), but Studio fetches a mirrored base from its byte-identical unsloth/ mirror, so on a fresh install the vendor id has no cached revision, the key became unknown and learned peaks were never recorded nor read. Fall back to mirror_repo() for the denoiser repo and the companion base, and name the repo the revision came from.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-21T15:16:15.966259Z ba92924 Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T12:26:56.944512Z
We couldn’t complete this review. Comment @codex security review to try again.
741f0c5 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

@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: 741f0c55ad

ℹ️ 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 +2147 to +2148
if revision or filename:
return repo, revision

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 peaks to the repository actually fetched

When an upstream cache contains only model_index.json (for example after an interrupted or previously gated pull) while the complete weights are available only from the mirror, the download planner still selects the mirror because it checks every base_files entry, but this early return selects the upstream revision merely because its index is cached. The resulting key therefore names a repository whose weights were not loaded, misses peaks previously recorded under the mirror key, and can associate measurements with the wrong build. Pass the load's already-resolved fetch_base into the identity calculation, or apply the same full-file cache predicate used by the planner.

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 e51511c. The key now follows the load's own mirror decision: load_pipeline passes its fetch_base into _peak_model_identity, and when that names a different repo than the upstream id, the revision is read from the repo the bytes actually came from. A cached upstream model_index.json no longer wins when the weights were pulled from the mirror, and when the load read the upstream bytes the mirror's revision is never used (no revision there means the key stays unknown). Callers without a fetch decision keep the earlier fallback. Test: test_peak_model_identity_keys_on_the_repo_the_load_fetched.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: e51511ca4c

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

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: ba97f6b598

ℹ️ 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 +2646 to +2648
revision = checkpoint_fingerprint(repo, filename)
if revision or filename or fetched:
return repo, revision

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 Carry the video fetch repo into the peak key

For video loads whose upstream cache contains only model_index.json while _predownload_base selected the complete mirror, _calibration_revision still calls this helper without fetch_base; this revision branch therefore keys the persisted peak to the partial upstream snapshot even though the loaded weights came from the mirror. The image caller is fixed, but the video path drops _base_fetch_repo when constructing _VideoLoadState, so an old upstream peak can be reused for a different mirror build; retain the selected fetch repo in the video state and pass it 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 ba92924. The video load state now keeps the base repo the load actually fetched (_VideoLoadState.fetch_base, set from the same fetch_base that load_pipeline and the H3 modular loader read from), and _calibration_revision passes it into _peak_model_identity. A video load that staged the complete mirror while the upstream cache holds only model_index.json is now keyed to the mirror's revision. Callers without a load decision (the native H3 runtime) still fall back to the mirror only when the upstream has no cached revision.

New test test_video_peak_key_names_the_repo_the_load_fetched: fails at ba97f6b (the key names Wan-AI/Wan2.2-TI2V-5B-Diffusers@u1), passes here. Related CPU tests base vs head: 1 fixed, 785 unchanged, no new failures.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: ba9292477d

ℹ️ 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 fc91656 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-learned-peaks-mirror-key branch October 21, 2026 15:53
danielhanchen added a commit that referenced this pull request Oct 21, 2026
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