Skip to content

Studio: diffusion auto-optimizer core shared by the image and video load paths - #13520

Merged
danielhanchen merged 3 commits into
mainfrom
studio-diffusion-autoopt
Oct 13, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-diffusion-autoopt

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

First step toward one generalized optimization layer for every Studio diffusion and video model, so a new model plugs in with data and at most a small hook instead of edits across many call sites. The design follows unsloth-zoo's compiler.py where it fits: per-model behaviour lives in tables, source rewrites are fingerprint gated and reversible, and every lever reports what it did.

This PR is behaviour preserving. Every registered family resolves exactly the optimization set it resolved before (624-case parity test below), and real-weight renders are byte-identical to main.

New package core/inference/diffusion_autoopt/:

  • patches.py: a PatchSpec registry with one install / uninstall lifecycle and one fingerprint helper (the duplicated _digest / _body_has copies now alias it, same algorithm, so pinned fingerprints still match). The per-arch patches (eager, arch, Qwen-Image-2.1 fast step / RoPE / fused, Qwen RoPE, FLUX.2 RoPE, ROCm fused, Z-Image fused, Wan fused) register as specs and install in the original order. Every existing UNSLOTH_DIFFUSION_* kill switch keeps working, and each spec also answers UNSLOTH_DIFFUSION_PATCH_<NAME>=0. The hand-kept teardown list becomes teardown groups. splice_source adds the in-memory source rewrite helper (exactly-once needles, unresolved-globals check, closures refused, fingerprint gate, reversible); nothing uses it yet.
  • targets.py: the denoiser attribute lists that were hard-coded in several places, with the old semantics, plus a by-type resolver that only feeds the profile, the audit and families with no registry data.
  • profile.py: per denoiser class, the repeated blocks (declared, verified or discovered) and a static graph-break screen of each block's forward, cached by class, source digest and diffusers version.
  • plan.py: the ordered steps with their reasons, from the same checks the primitives use, and one builder for the compile-cache kwargs (it replaces two inline dicts that had to stay in sync).
  • apply.py: run_speed_layer, the single entry for the image load, the deferred third-image profile, video and MiniMax-H3. The existing apply_speed_optims call is passed in unchanged. LTX static compile, the LTX STG adapter and the cuDNN-benchmark opt-out move from inline branches into family hooks. A family with no registry data gets a guarded trial compile of its discovered blocks; a block whose forward shows graph-break suspects is declined with the reason (UNSLOTH_DIFFUSION_AUTOOPT_DISCOVER=0 turns this off).
  • runtime.py: the auto step cache is judged against the pipeline that actually runs the request, reusing diffusion_multistage for multi-call runners.

Audit in status. Each load records every step as engaged, declined with a reason, or failed with the error, under resolved.speed_mode.steps (an optional steps field on DiffusionResolvedControl). A Z-Image load shows 23 entries, for example "tf32: max tier only" and "compiled_dequant: not a GGUF transformer".

One behaviour change. In diffusers 0.41, FluxImg2ImgPipeline, FluxInpaintPipeline and the Z-Image img2img / inpaint pipelines never open cache_context, so an auto first-block cache left on by the base load would raise "No cache context is set" there. The auto cache now stays off for those calls, with the reason in status. This is read from the diffusers source, not reproduced on a live run; an explicitly requested fbcache on those workflows is unchanged.

Not touched: the quant, ConvRot and policy tables, prequant validation, and video memory planning.

Testing

  • Parity: tests/test_diffusion_autoopt_parity.py with tests/fixtures/diffusion_autoopt_parity.json, captured from main by replaying the old load sequence over stub pipes (real class names, modules and _repeated_blocks). 24 families (15 image, 9 video) x 4 speed tiers x bf16 / fp16 x offload on / off x GGUF on / off = 624 cases, comparing the installed patches, applied flags, compile kwargs per DiT, LTX static compile, auto-dynamic, int8 GEMM and the CUDA-graph decision and reason. Passes with the GPU hidden and visible. It also asserts the old sequence still reproduces the fixture and that every registry family is covered.
  • tests/test_diffusion_autoopt_core.py: 27 unit tests.
  • After rebasing on current main: the parity, core, video, multistage, speed, single-file registry and prequant suites give 2537 passed, 96 skipped, 0 failed.
  • Full backend suite, one pytest process per file (15-minute limit each), base vs head: 193 vs 194 failing IDs, all shared except test_diffusion_single_file_registry.py::test_a_packed_norm_weight_comes_out_as_real_values[Q8_0], a NaN-flaky torch.equal in a file this PR does not touch that passed 4 of 4 reruns on both base and head.
  • Real weights, base vs head, two seeds each:
Arm speed_optims (identical on base and head) Output vs base
Z-Image-Turbo 512px, speed off [] byte-identical
Z-Image-Turbo 512px, default channels_last, vae_fused, compiled, cuda_graph byte-identical
Wan2.2-TI2V-5B 512px 17 frames, speed off [] byte-identical
Wan2.2-TI2V-5B 512px 17 frames, default channels_last, vae_fp16_decode, vae_fused, compiled, vae_untiled_when_fits byte-identical

Left for follow-ups

  • Video does not use the compile cache, per-block graphs or the deferred compile yet. The compile cache repoints the process-wide TORCHINDUCTOR_CACHE_DIR, which an image backend in the same server shares, and nothing was measured, so they stay off; the audit says so on every video load.
  • ROCm query chunks, HiDream traceable MoE, the H3 levers, the Q2.1 attention patches, the fp16 guard and MPS fp16 are not registry specs yet, and the wrapped patch modules still keep their own fingerprint and stash logic internally.
  • The family side tables (quant excludes, preview factors, VAE coefficients and the rest) and header-derived video sizes come in separate PRs.

…oad paths

Adds core/inference/diffusion_autoopt (targets, profile, patches, plan, apply,
runtime): one orchestrator over the existing speed primitives for image and
video loads, a PatchSpec registry with a single install / uninstall lifecycle
and one fingerprint util for the per-architecture patches, a static profile of
each denoiser class, a per-load audit surfaced as resolved.speed_mode.steps,
and a runner-aware auto step cache check for from_pipe workflows and I2V swaps.

Every registered family resolves the same optimizations as before: the parity
fixture was captured from 5f38afb and is asserted for every image and video
family across speed tiers, dtypes, offload and GGUF.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 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-13T03:23:42.519709Z 2d6bdbd 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

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 🔄 Running since 2026-10-13T03:20:28.988013Z 2d6bdbd 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 2d6bdbd773

ℹ️ 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 a7516db into main Oct 13, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-autoopt branch October 13, 2026 03:31
danielhanchen added a commit that referenced this pull request Oct 13, 2026
#13520 and #13516 merged files that are not a fixed point of the
ruff-format-with-kwargs hook, so tests/test_formatter_fixed_point.py
fails on main and in every PR's Repo tests (CPU, rest). Output of
scripts/run_ruff_format.py only; no code changes.
danielhanchen added a commit that referenced this pull request Oct 13, 2026
…13536 left red on main (#13543)

- Baseline the two diffusion_autoopt splice_function compile/exec sites
  with their reasons (#13520).
- Name encoding="utf-8" on four file reads/writes in tests (#13520,
  #13534, #13536).
- Format six #13536 files with scripts/run_ruff_format.py.
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