Skip to content

Studio diffusion: change baked LoRA subsets and weights without recompiling or recapturing - #14692

Merged
danielhanchen merged 4 commits into
mainfrom
studio-baked-lora-graph-stable
Oct 22, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-baked-lora-graph-stable

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

A torchao int8/fp8 load in Studio bakes its LoRA adapters before quantize and compile. Since #14312, a later prompt can drop one of the baked adapters (it runs at weight 0) or change a weight without a reload. That change only moves the PEFT scale, but the scale is a Python float read inside the LoRA forward:

  • torch.compile guards on it (self.scaling['lora_b'] == 1.0), so each new weight vector compiles the denoiser again.
  • A CUDA graph records it as a kernel argument, so _adjust_baked_loras calls cuda_graph.reset_all and the next prompt captures every graph again. This also happens when you go back to a selection that was already compiled.

The adapters and their shapes never change on a baked load, so neither cost is needed.

Change

  • _pin_baked_lora_scales: once the denoiser is placed, and before anything compiles or captures, each baked scaling[adapter] is stored as a 0-d float32 tensor on the device of its LoRA weights. Compiled code takes that tensor as a graph input, not as a guarded constant, and a captured graph reads it from memory when it replays.
  • _adjust_baked_loras writes the new weights into those tensors in place (fill_) for a subset change, a weight change or turning everything off. It skips set_adapters and the graph reset.
  • In these cases the old set_adapters + reset_all path is still used:
    • an offloaded denoiser (hooks move the LoRA weights off the scale's device)
    • LoRA weights that are not on the target device type
    • a scale that something has written back as a float
  • CFG-parallel replica: build_replica copies the pinned tensors to the replica's card. weights_fingerprint now reads their identity and version counter rather than repr, so a write still rebuilds the replica, and there is no device read on each call.

Evidence

Tiny FLUX.2 klein (Flux2Transformer2DModel, random weights) loaded through DiffusionBackend.begin_load with transformer_quant="int8", speed_mode="max" (compiled + CUDA graph), and two random rank-4 LoRAs baked on every attention / FF Linear. 256x256, 4 steps, same seed. Counts are per prompt.

Prompt main: new Dynamo graphs main: graph captures this PR: new Dynamo graphs this PR: graph captures
P1 A+B (first) 2 1 2 1
P2 A+B (repeat) 0 0 0 0
P3 A only (subset) 2 (recompile) 1 0 0
P4 A+B (back) 0 1 0 0
P5 A only (again) 0 1 0 0
P6 A=0.5, B=1 2 (recompile) 1 0 0
P7 A+B (back) 0 1 0 0
P8 all off 0 1 0 0
P9 A+B (back) 0 1 0 0

On main, the recompile reason is the guard on result = result + lora_B(lora_A(dropout(x))) * scaling. Every changed prompt captures the graph again, even for a selection that was already compiled. With this change, nothing recompiles or recaptures after the first prompt. On both arms the images match: P2, P4 and P9 equal P1, P5 equals P3, and P3 and P6 differ from P1.

Unit test test_baked_lora_subset_and_weight_changes_keep_compiled_graphs uses a real PEFT lora.Linear with two adapters under torch.compile and goes through the real _apply_loras. It fails on main (frame_count 3, expected 1) and passes with this change. On CPU with the change, tests/test_diffusion_lora.py plus the multi-GPU wiring suites give 147 passed, 4 skipped.

Not covered

  • Offloaded (model / group / sequential) loads keep the previous behaviour by design.
  • CFG-parallel on two cards and layer-split were not run on GPUs, only the replica fingerprint unit test.
  • If diffusers' scale_lora_layers is called with a non-1 attention_kwargs["scale"], it would scale the pinned tensor in place and then unscale it. Studio does not pass that kwarg.

A torchao int8/fp8 load bakes its LoRA adapters before quantize and compile,
so a later prompt that drops one adapter or changes a weight only moves the
PEFT scale. PEFT holds that scale as a Python float read inside the LoRA
forward: torch.compile guards on it (self.scaling['b'] == 1.0) and a CUDA
graph records it as a kernel argument, so every new weight vector recompiled
the denoiser and _adjust_baked_loras dropped every captured graph.

Once the denoiser is placed, and before anything compiles or captures, hold
each baked scale as a 0-d float32 tensor on its LoRA weights' device. A
weight or subset change then writes those tensors in place: the guards and
the captured graphs read them at run time, so no recompile and no recapture.
Offloaded denoisers, weights off the target device, or a scale something
rewrote as a float keep the previous set_adapters + reset path.

The CFG-parallel replica copies the pinned tensors to its own card, and its
staleness fingerprint reads their version counter instead of repr, so an
in-place write still rebuilds the replica without a device read per call.
@danielhanchen danielhanchen self-assigned this Oct 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T18:34:52.967591Z 5175579 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: 615bbf8dba

ℹ️ 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 +12100 to +12102
if _set_pinned_lora_scales(pipe, {n: w for (n, _p, w) in updated}):
pipe._unsloth_loras = updated
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Update non-denoiser adapter scales before returning

When a baked adapter contains both denoiser and text-encoder LoRA weights—as supported by the Stable Diffusion, SDXL, SD3, and Flux diffusers loaders—_pin_baked_lora_scales records only modules returned by denoiser_modules. A later subset or weight change therefore makes this call return true after updating only the denoiser tensors, and the early return bypasses pipe.set_adapters; the text encoder keeps its bake-time scale while _unsloth_loras claims the new value, so prompt encoding silently uses mixed old/new adapter weights. Pin and update every LoRA-bearing loadable component, or fall back whenever any adapter scale remains unpinned.

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.

Good catch, this was real. _pin_baked_lora_scales only looked at the denoisers, and the pinned path skips set_adapters. So when a baked file also carried text-encoder LoRA weights, a subset or weight change only updated the denoiser. The text encoder kept its bake-time scale while _unsloth_loras named the new weights.

Fixed. Pinning now also records the LoRA layers on the other pipeline components. On the pinned path their scales are set with set_scale, the same call set_adapters makes. Those scales stay plain floats, and the denoiser graphs are not affected.

New test test_pinned_lora_change_also_sets_the_text_encoder_scales uses a real PEFT text-encoder layer carrying both adapters and switches to [("a", 0.5)]. It expects the text encoder scales to be {"a": 1.0, "b": 0.0}. With the new set_scale loop removed, it fails with {'a': 2.0, 'b': 2.0}, which are the bake-time values. With the loop in place, all 33 tests in tests/test_diffusion_lora.py pass.

A LoRA file can carry text-encoder weights as well as denoiser weights. The
pinned path updates the denoiser's scale tensors and skips set_adapters, so
the text encoder kept its bake-time scale while _unsloth_loras named the new
weights. Record the non-denoiser LoRA layers when pinning and set their
scales the same way set_adapters does.

[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. 🚀

Reviewed commit: dd6d3fab31

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

…d a stub torch

Read the target device type off its string form and skip denoiser roots
without a modules() walker, so a load under a minimal torch takes the same
path it did before the pin. The test helper adds its second adapter through
the keyword arguments the installed LoraLayer.update_layer names, since PEFT
0.18 requires use_rslora and friends where 0.19+ takes config.

[skip ci]
@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: b0d17fbaed

ℹ️ 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 +854 to +855
if adapter not in lora_b or isinstance(value, torch.Tensor):
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fall back when any LoRA layer cannot be pinned

When a baked adapter targets a PEFT Embedding alongside an ordinary Linear layer, the embedding adapter has its factors in lora_embedding_A/B rather than an entry in lora_B, so this branch silently skips it while the Linear layer makes pinning report success. _adjust_baked_loras then returns without calling pipe.set_adapters, and _side_lora_layers uses the same lora_B filter, leaving the embedding at its bake-time scale and producing mixed adapter weights after a subset or weight change. Fresh evidence beyond the earlier text-encoder report is that PEFT embedding adapters are still excluded by this newly added filter; encountering any unpinnable scale-bearing LoRA layer should disable the pinned path or explicitly update that layer.

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.

Confirmed and fixed. A PEFT Embedding keeps its factors in lora_embedding_A/B, so its scale had no lora_B entry and the pin walk skipped it while still pinning the Linear layers. The pin now declines outright when any denoiser LoRA scale has no lora_B entry, so those loads keep the set_adapters path. The text encoder side walk now covers every scaled adapter, embeddings included, so their scales follow a weight or subset change. Two new tests cover both cases: they fail on the previous code and pass now, on PEFT 0.18.1 and the latest PEFT.

… entry

A PEFT Embedding keeps its factors in lora_embedding_A/B, so the pin walk
skipped its scale while still pinning the Linear layers, and a later weight
change skipped set_adapters and left the embedding at its bake-time weight.
Decline the pin on any such scale so the set_adapters path stays, and let the
text-encoder side walk set every scaled adapter, embeddings included.

[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. Swish!

Reviewed commit: 5175579891

ℹ️ 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 38a3a34 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the studio-baked-lora-graph-stable branch October 22, 2026 19:27
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