Skip to content

Studio: pre-seed the float specialisations of an image load's first compiled render - #16917

Merged
danielhanchen merged 1 commit into
mainfrom
studio-diffusion-compile-cache-persist
Nov 6, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
studio-diffusion-compile-cache-persist

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

When an image model compiles inside its first render (the default speed tier on a card where the denoiser fits, for example FLUX.2-klein-4B on an A100), every Studio start threw away a whole Dynamo attempt per block type before compiling:

  • The default tier compiles the repeated blocks with dynamic=True, so every Python float a block reads becomes a SymFloat: the norm eps, dropout p, the attention dispatch default.
  • Those ops guard the float to a constant, the tensorify pass raises TensorifyScalarRestartAnalysis, and Dynamo retraces each block type with the floats specialised (compile_attempt_0 and compile_attempt_1 for both FLUX.2 block types).
  • On a returning start (warm compile cache) the first attempt also misses the AOTAutograd cache, since its graph still has the float inputs. It cost 5.7 s of the 8.3 s compile on FLUX.2-klein-4B.

The background compile (#15393) and video's first clip (#15406) already keep the SymFloat names a compile specialised in the compile-cache key dir and pre-seed them on the next load. The image path that compiles inline in the render never did. This PR wires the same InlineFloatSeeds into the image generate:

  • seeded at the denoise entry (and at the first DiT forward, for a loop without a progress bar), kept at the decode entry, so only the denoiser's names are saved;
  • same file and key dir as the background compile (bg_compile_float_specializations.json in the compile-cache context dir), stamped with the torch version and the block forward bytecode, so a mismatch falls back to the current restart;
  • only for loads with no background compile, compiled in the speed optims, a compile-cache context, and a DiT compiled with dynamic=True; a deferred load is asked again once it compiles;
  • float_seed_dits and seed_before_first_forward moved from video.py into diffusion_bg_compile.py so both backends share them (video keeps the old names as aliases);
  • kill switch: the existing UNSLOTH_DIFFUSION_BG_COMPILE_FLOAT_SEEDS=0.

A first-ever start (empty cache) still learns the names through the restart, as on main.

Results

Colab A100-SXM4-40GB, one VM, torch 2.13.0+cu130, diffusers 0.42.1, Studio installed with install.sh --local. FLUX.2-klein-4B, 1024x1024, 4 steps, 3 prompts after the first render. Base = ccc8a827d2, head = base + this change. 3 reps, base and head interleaved (B H, H B, B H). Fresh = new process, empty Studio home and inductor / Triton caches; returning = a second and third process on that home.

base head
first render, returning (6 processes each) 12.01 / 12.07 / 12.08 / 12.09 / 12.11 / 12.32 s 7.77 / 7.80 / 7.83 / 7.84 / 7.86 / 7.88 s
first render, fresh home 23.27 / 23.50 / 23.96 s 22.93 / 23.14 / 23.23 s (unchanged by design)
Dynamo _compile.compile_inner, returning 5.66 + 2.59 s (2 attempts per frame) 2.55 + 1.09 s (1 attempt)
AOTAutograd cache, returning 2 miss + 2 hit 2 hit, 0 miss
steady renders 0.716-0.778 s 0.712-0.770 s
process wall, returning 34.2-34.6 s 29.8-30.1 s

Returning first render: -4.2 s (-35%), median 12.09 s to 7.84 s, outside the A/A spread of either arm (0.31 s base, 0.11 s head).

Same images, same graphs

  • Every PNG md5 is identical across all 19 cells (base and head, fresh and returning), per prompt.
  • A seeded head start hits the AOTAutograd entries written by the unseeded fresh compile with 0 misses. The AOT cache key hashes the graph, so the seeded trace produces the same graph as the restarted one.
  • Graph count stays 2 (unique_graphs), 0 recompiles, 0 graph breaks on every cell.

Tests

  • tests/test_diffusion_inline_float_seeds.py (new, CPU, aot_eager): a returning load traces its first render once into the same output (0 restarts, torch.equal), the file is the background compile's, one seeder per load until kept, no seeder for a background compile / not compiled / static compile / no cache context / kill switch, and a deferred load is asked again once it compiles.
  • tests/test_diffusion_backend.py: generate seeds before the first denoiser forward and keeps before the decode, seeds at the first DiT forward without a progress bar, and an auxiliary pass takes no seeds.
  • 13 new tests fail on main and pass here. test_video_float_seeds.py, test_video_backend.py, test_diffusion_bg_compile_float_seeds.py, test_diffusion_backend.py: 1240 passed, 1 skipped.

Not proven

  • Only FLUX.2-klein-4B on an A100 was timed. Other families compiled inline with dynamic=True (FLUX.1, Qwen-Image where it fits) take the same path; the background compile PR measured FLUX.1 and Qwen-Image-2.1 with the same seeding, not this inline path.
  • Loads that compile with dynamic=None or False (U-Net, torchao stream-merging DiTs) do not restart and are untouched; not timed here.
  • ROCm, Windows and macOS were not run. The change is host-side Python around the compile and does not touch device code.

…ompiled render

A load that compiles inside its first render (no background compile, e.g. FLUX.2-klein on an
A100) threw away a whole Dynamo attempt per block type on every start: dynamic=True turns the
blocks' eps / dropout floats into SymFloats, tensorify fails and Dynamo retraces. The background
compile and video's first clip already keep the learned names in the compile-cache key dir; the
image inline path now seeds from and writes to the same file.
@danielhanchen danielhanchen self-assigned this Nov 6, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 6, 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-11-06T14:17:13.994954Z 2b25ff0 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

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. Already looking forward to the next diff.

Reviewed commit: 2b25ff0d86

ℹ️ 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 06d5015 into main Nov 6, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-compile-cache-persist branch November 6, 2026 16:34
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
…t compiled render traces once (unslothai#16939)

## Summary

unslothai#16917 pre-seeds the Dynamo float specialisation names (norm `eps`,
dropout `p`, ...) that an image load's first compiled render learned, so
a returning start traces each block type once. A first-ever start has no
saved file yet, so it still paid the full restart: the default tier
compiles the repeated blocks with `dynamic=True`, the first attempt
fails on the float values (`TensorifyScalarRestartAnalysis`) and Dynamo
traces every block type again.

This PR ships those names per known denoiser, so a fresh install starts
from the same seeds a returning user already has:

- `_FLOAT_SEED_DEFAULTS` in `diffusion_bg_compile.py`: the names a real
first compile learns, for FLUX.2-klein 4B / 9B (and base), FLUX.2-dev,
FLUX.1-dev / schnell / Krea / Kontext, Qwen-Image / 2512, Z-Image /
Turbo, Wan2.1-T2V-1.3B, Wan2.2-T2V-A14B and Wan2.2-TI2V-5B.
- Used only when the seed file of that compile-cache key has no names
for this code; saved names always win. After the first compile the
built-in names are written to the seed file like learned ones, so later
loads take the existing returning path.
- Keyed by `_default_float_seed_key`: torch minor, diffusers version,
the transformer config less its layer counts, and per repeated block
class every submodule class, the source of every forward and attention
processor it runs, and the module-level helpers they call by name. A
Studio load patch (arch fusions, fused RoPE, int8 swaps), a LoRA,
another diffusers or torch version or any other config moves the key, so
nothing is seeded and the compile restarts exactly as on main.
- Kill switches: the existing
`UNSLOTH_DIFFUSION_BG_COMPILE_FLOAT_SEEDS=0` (all seeding), and
`UNSLOTH_DIFFUSION_FLOAT_SEED_DEFAULTS=0` (only the built-in names).
- The same seeding path serves the background compile and video's first
clip, so those get the built-in names too.

How the table was recorded: one layer of each model (real config, random
weights) on an A100 through this backend's own load patches and
`_compile_repeated_blocks`, under the Studio install (torch
2.13.0+cu130, diffusers 0.42.1). Dynamo numbers a SymFloat from a hash
of its source name (`ShapeEnv._generate_unique_id`), not from tensor
sizes, so the names do not depend on the layer count or resolution
(checked: 64 vs 256 tokens, real vs shrunk widths give the same names).
For the two families timed below, the recorded names equal what a real
fresh start wrote to its seed file.

## Results

Colab A100-SXM4-40GB, one VM per run, Studio installed with `install.sh
--local` (python 3.13.16, torch 2.13.0+cu130, diffusers 0.42.1). Base =
`06d5015f28` (main), head = base + this change. 1024x1024, 3 prompts
after the first render, 3 reps with base and head interleaved (B H, H B,
B H). Fresh = new process, empty Studio home and inductor / Triton
caches; returning = later processes on that home.

FLUX.2-klein-4B, this PR's code (the later commits only touch tests and
comments):

| first compiled render | base | head |
|---|---|---|
| fresh | 21.63 / 21.81 / 22.56 s (median 21.81) | 17.02 / 17.11 / 17.27
s (median 17.11) |
| returning, 2nd process | 6.31 / 6.35 / 6.42 s | 6.39 / 6.39 / 6.49 s |
| returning, 3rd process | 6.34 / 6.38 / 6.39 s | 6.39 / 6.43 / 6.44 s |

Z-Image-Turbo, an earlier revision with the same table and key (it
differed only in not yet writing the built-in names to the seed file, so
its returning runs seeded from the table again rather than the file; the
+0.37 s median there is inside both arms' 0.50 / 0.56 s spread):

| first compiled render | base | head |
|---|---|---|
| fresh | 22.76 / 22.88 / 23.34 s (median 22.88) | 19.72 / 20.16 / 20.64
s (median 20.16) |
| returning | 8.19 / 8.62 / 8.70 s | 8.61 / 8.99 / 9.18 s |

- Fresh first render: klein -4.70 s (-22%), Z-Image -2.72 s (-12%), each
well outside both arms' spread (klein 0.93 / 0.25 s, Z-Image 0.58 / 0.92
s). The same klein comparison on the earlier revision gave 22.21 to
17.18 s.
- Dynamo `_compile.compile_inner` on a fresh klein start: base 10.24 +
5.07 s with a `compile_attempt_1` per block type, head 7.01 + 3.48 s
with none. The head logs `diffusion.float_seeds: 11 built-in float
specialisation(s) pre-seeded for the Flux2Transformer2DModel compile` (7
for `ZImageTransformer2DModel`); its returning runs then read the same
11 names from the seed file, like base.
- Returning first render: within 0.05 s of base at medians, inside the
spread of each arm. Steady renders unchanged (klein 0.71-0.77 s, Z-Image
2.20-2.36 s on both arms).
- The names base's fresh starts wrote to their seed files are exactly
the shipped ones for both models.

## Same images, same graphs

- Every PNG md5 is identical across all cells of a model, base and head,
fresh and returning, per prompt: klein 57 PNGs over 19 cells and 3
distinct (one per prompt); Z-Image 39 PNGs over 13 cells and 3 distinct.
- A head start in a base fresh home (`head_inbase`) hits both
AOTAutograd entries the unseeded base compile wrote, 0 misses, so the
seeded first trace produces the same graphs as main's restarted one.
- 0 graph breaks (blocks compile with `fullgraph=True`). Recompiles: 0
for klein; 1 for Z-Image on both arms alike (a pre-existing guard on
`adaln_input` being `None`).
- Per family on CUDA (one layer, random weights, the same load patches):
with the built-in names every listed model traces with 0 restarts.
- Cost on a miss: computing the key takes about 5 ms once per load, only
when the seed file has no names for this code.

## Tests

- `tests/test_diffusion_float_seed_defaults.py` (new, CPU, `aot_eager`):
a fresh compile with a matching key traces once into the same output as
main's restarted compile and writes the names to the seed file; the next
load reads them from the file; saved names win over the table; both kill
switches keep the restart; a name no float carries is never consulted
and a missing one is still learned by the restart, output unchanged; the
key ignores layer counts but moves with the config, a swapped submodule,
an instance forward, a class forward patch, a swapped helper function,
and is absent for a LoRA-adapted or config-less module; the table is
well formed.
- With the one functional line reverted (no built-in lookup), the
fresh-compile and stale-name tests fail; the other new tests are
negative controls and pass on both.
- `test_diffusion_inline_float_seeds.py`, `test_video_float_seeds.py`,
`test_diffusion_bg_compile_float_seeds.py`, `test_diffusion_backend.py`,
`test_video_backend.py`: 1249 passed, 1 skipped (torch 2.12.1). The four
seed test files also pass on torch 2.10.0, 2.13.0 and 2.14.1.

## Not proven

- Timed on FLUX.2-klein-4B and Z-Image-Turbo with real weights only.
FLUX.1, FLUX.2-dev, klein-9B, Qwen-Image and Wan were checked with one
random-weight layer through the same load patches and compile (0
restarts, the learned names equal the table), not with a full Studio
render.
- The Wan entries assume the pipelines' timestep layout (per-token
timesteps for TI2V-5B, as its `expand_timesteps` flag sets); the video
backend's own first-clip path was not timed.
- Another speed tier on the same model (for example an int8 or fp8
transformer) swaps block modules, so its key differs and it keeps main's
restart.
- ROCm, Windows and macOS were not run. The change is host-side Python
around the compile; on a host where the key does not match, nothing is
seeded.
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