Skip to content

Studio: fold an unchanged LoRA set into a resident denoiser, restore it exactly before a change - #16675

Merged
danielhanchen merged 7 commits into
mainfrom
studio-lora-fuse-constant
Nov 4, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio-lora-fuse-constant

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

With a LoRA attached, PEFT runs every adapted layer as base(x) + B(A(x)) * scale: two extra small GEMMs per layer on every step. For SDXL with a constant-strength LoRA that made a render about 35% slower than the same model without one.

When a render uses the same LoRA set and strengths as the previous one, this folds the adapters into the weights of a resident, unquantised denoiser, so PEFT runs only the base layer. The original weights are restored exactly before any change.

Change

  • New diffusion_lora_fuse.py:
    • fuse computes scale * (B @ A) in fp32, adds it to the weight in fp32 and rounds to the weight dtype once, then marks each layer merged.
    • A backup of the original weights is kept on the card when at least max(8 GiB, 25%) stays free after it, otherwise in pinned host memory in 64 MiB chunks. UNSLOTH_DIFFUSION_LORA_FUSE_BACKUP=host|device forces either.
    • unfuse copies the originals back before any strength, set or removal change, so the existing weights-only path (set_adapters) runs on exactly the unfused model.
    • Not folded: offloaded denoisers, quantised bakes, GGUF / torchao / other tensor-subclass weights, DoRA and LoRA-bias adapters, layers already merged or disabled.
    • Kill switch UNSLOTH_DIFFUSION_LORA_FUSE=0.
  • diffusion.py: an unchanged set folds (a no-op once folded); a change, or clearing the LoRAs, restores first. CUDA graphs are reset and a CFG replica is invalidated after a fold or a restore.
  • Compiled loads are unchanged: Studio already refuses LoRA changes on them.

Evidence

SDXL + a pixel-art LoRA at 0.8, 1024x1024, 25 steps, CFG 7, one G4, interleaved:

case main s/img this PR s/img result
same strength every render 2.207 / 2.214 1.625 / 1.626 -26%
first change after a folded run 2.213-2.244 2.233-2.240 tie
strength changes every render 2.224 / 2.232 2.233 / 2.232 tie, identical images
no LoRA 1.632 / 1.623 1.625 / 1.621 tie, identical images

Accuracy against an fp32 reference (UNet + LoRA in fp32, unfused, same seeds, 4 prompts; every arm reproduces exactly across repeats):

arm vs fp32 mean LPIPS max per prompt
main, unfused bf16 0.0735 0.1535 0.0095 / 0.1535 / 0.1126 / 0.0182
this PR, folded 0.0546 0.1210 0.0118 / 0.1210 / 0.0697 / 0.0161

The folded path is closer to fp32 on the mean, the max and 3 of 4 prompts; on the fourth both are within about 0.01.

  • Restores are exact: 0 of 1680 UNet parameters differ from a snapshot taken before the first render, across every check.
  • 0 Dynamo graphs and 0 graph breaks on every measured render, both arms.

Backup on the host (L4, where the card would keep under 8 GiB free):

  • Every folded render: 10.26-10.40 s against main's 12.2-12.5 s (-16%).
  • The first change after a folded run: 12.69-12.81 s against 12.17-12.48 s (+0.3-0.5 s, one render), the upload of the originals.
  • Host RAM +4.4 GiB for this LoRA (722 layers). On the card instead (G4): +4.8 GiB of VRAM while folded and no host RAM.

Tests

  • test_diffusion_lora_fuse.py: 12 tests, including a GPU test that pins the fold bit for bit to (W.float() + scale * (B.float() @ A.float())).to(bf16) and a bit-exact restore with the backup on the card and on the host. 10 CPU tests pass here; 6 fail on main.
  • test_diffusion_lora.py: 677 passed; the one failure (test_moss_image_has_no_lora_loader_so_lora_is_gated_off) fails identically on main in a venv without the pinned huggingface_hub.
  • AMD gfx1151 (Linux, ROCm), base and head in the same job: 678 -> 690 passed, the GPU tests ran and passed.

Not covered

  • One LoRA was timed; stacked adapters, SD1.5 and FLUX LoRAs were not.
  • No Mac or Windows GPU runs.

@danielhanchen danielhanchen self-assigned this Nov 4, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 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-04T15:23:11.471335Z daae09b 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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: daae09b05f

ℹ️ 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 f5935a7 into main Nov 4, 2026
@danielhanchen
danielhanchen deleted the studio-lora-fuse-constant branch November 4, 2026 18:26
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
…side the host RAM reserve (unslothai#17086)

## Summary

Follow-up to unslothai#16675. When a resident dense denoiser renders the same
LoRA set twice, Studio folds the adapters into the weights and keeps a
backup of the original weights so it can restore them bit-exactly. If
the card has no room for the backup, it goes to host memory. That host
allocation had two gaps:

1. It was always pinned on a CUDA / ROCm device, including integrated
GPUs, where Studio's own policy (`host_pinning_allowed`) skips pinning
because the card's memory is the same RAM.
2. Nothing checked host RAM. The backup is the full set of adapted
weights (several GiB for an SDXL or larger DiT), so the second identical
render could add a multi-GiB allocation the first render did not need.
The `except` fallback only covers an outright allocation failure, not
memory pressure after a successful allocation.

## Changes

- `diffusion_lora_fuse.fuse` now pins the host backup only when
`host_pinning_allowed(device)` says so, asking about the weights' own
device.
- Before allocating a host backup, it checks the small-host reserve
(`max(3 GiB, 10% of RAM)`, the same reserve and cgroup-aware reading the
low-memory load route uses). If the backup would cut into that reserve,
the set stays unfused. Unfused output is exactly what PEFT computes
without the fold, so the only cost is the two extra low-rank GEMMs per
adapted layer.
- An unreadable host reading still allows the allocation, so behaviour
there is unchanged.
- Kill switch: `UNSLOTH_DIFFUSION_LORA_FUSE_HOST_GUARD=0` restores the
previous allocation, pinned on every CUDA / ROCm device with no RAM
check.
- The device-backup path and the restore path are unchanged.

## Evidence (CPU, tiny UNet + real PEFT, base = merge base)

| Check | main | this PR |
|---|---|---|
| Fold with `UNSLOTH_DIFFUSION_HOST_RAM_LIMIT_MIB=2048`, host backup |
folded (backup allocated below the reserve) | stays unfused, weights
untouched |
| `pin_memory` requested for the backup on an integrated GPU | `True` |
`False` |
|
`test_every_pinning_site_asks_the_integrated_gpu_predicate_or_is_reached_through_one`
| lists `diffusion_lora_fuse.py:136 fuse` | the fuse site no longer
appears |

The structural test still fails on both sides because of an unrelated
site, `diffusion_transformer_quant.py _upload_staged`.
`test_the_h3_block_pin_helper_is_reached_only_through_the_gated_deferral`
also fails on both sides. Neither is touched here.

New tests in `tests/test_diffusion_lora_fuse.py` cover:
- the reserve arithmetic
- the unfused fallback through `_apply_loras` together with the kill
switch
- the pin decision on integrated, discrete and CPU devices

All 17 tests in the file pass; the 2 GPU-only tests are skipped on CPU.

## GPU (Kaggle T4, sm75, torch 2.10 / peft 0.19.1 / diffusers 0.42.1)

Base (merge base) and head ran one per T4 in the same kernel, 3 reps
each. Tiny UNet in fp16, host backup forced:

| Check | main | this PR |
|---|---|---|
| fold with a normal host | folded, pinned backup, restore bit-exact |
same |
| fold with `UNSLOTH_DIFFUSION_HOST_RAM_LIMIT_MIB=2048` | folded, pinned
backup | stays unfused, output bit-equal to unfused |

The fused output differs from the unfused one by max abs 1.6e-3 in fp16.
That difference is identical on both arms, because the fold itself is
unchanged. In every rep, the restore was bit-exact and the output after
the restore was bit-equal to the unfused output.
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