Skip to content

Studio diffusion: fold a constant LoRA set only when opted in - #18983

Merged
danielhanchen merged 2 commits into
mainfrom
studio-lora-fold-followup
Nov 23, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-lora-fold-followup

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

#18872 lets _fuse_constant_loras fold an unchanged LoRA set under offload_policy=group when the denoiser is resident (FLUX.2 klein 4B bf16 on a 24 GB card). The PR body said the fold, W + scale * (B @ A) in fp32 rounded once to bf16, is closer to the true result than PEFT's unfolded branch. Checked against an exact fp32 computation of the adapted layers, it is not. The fold rounds the whole merged weight to bf16, which adds an error of about 2^-9 of each weight whatever the adapter's size. PEFT keeps the base weight exact and only rounds the small adapter branch.

This change keeps group offload loads on the unfolded path by default. UNSLOTH_DIFFUSION_LORA_FUSE=1 turns the #18872 fold back on for users who want the speed. Loads with no offload fold as before, and UNSLOTH_DIFFUSION_LORA_FUSE=0 still turns every fold off.

Results

Colab L4, FLUX.2 klein 4B bf16, 1024 px, 4 steps, seed 1234, guidance 1.0, Studio defaults (text encoder grouped, DiT resident, INT8 attention), rank-32 adapter on 100 layers, the same 4 prompts as #18872. Each arm ran in a fresh process. The reference computes every adapted layer as x W^T + b + scale * (x A^T) B^T in fp32 and rounds the output to bf16 once. The rest of the DiT is unchanged.

Prompt Unfolded PEFT vs reference, LPIPS / PSNR Folded vs reference, LPIPS / PSNR Unfolded vs folded, one-step rel. error vs reference
0 0.0107 / 35.5 dB 0.0196 / 31.6 dB 0.037 vs 0.042
1 0.0100 / 35.8 dB 0.0071 / 38.0 dB 0.038 vs 0.038
2 0.0170 / 29.4 dB 0.0273 / 27.9 dB 0.021 vs 0.025
3 0.0058 / 35.9 dB 0.0055 / 36.6 dB 0.021 vs 0.023
mean 0.0109 0.0149 0.029 vs 0.032

The one-step error is measured on the first transformer forward of each render, where the inputs are identical across arms. The fold is further from the reference on 3 of 4 prompts by one-step error and on 2 of 4 by LPIPS, with mean LPIPS 37% higher. A CPU check on a 3072x3072 bf16 layer shows the cause. Before the shared output rounding, the folded weight is off by 1.5e-3 to 1.7e-3 (relative) for every adapter size. PEFT's branch is off by 9e-6 to 6e-4, and that error grows with the adapter.

Against a whole-transformer fp32 reference (fp32 weights and adapters), the result is the same:

Attention Prompts where PEFT is closer (LPIPS) Prompts where PEFT is closer (one-step error) Mean LPIPS to fp32, PEFT / folded
INT8 (default) 4 of 4 4 of 4 0.0135 / 0.0204
native SDPA 3 of 4 (the fourth within 0.0007) 4 of 4 0.0094 / 0.0193

Repeat runs on the same VM and on a second VM gave byte-identical images. No-LoRA renders and the first LoRA render after a change are byte-identical across all arms.

Cost: on this workload the repeat LoRA render goes back to the unfolded speed measured in #18872 (about 0.87 s/step against 0.71 s/step folded). The 7 GiB pinned host backup the fold keeps on L4 also goes away (process RSS 16.2 GiB folded against 9.1 GiB unfolded).

Tests

  • test_group_fold_is_opt_in: unset, empty, auto and 0 keep group offload unfused; 1, on and true fold; no offload always passes the gate.
  • test_group_policy_stays_unfused_unless_opted_in: a group policy load with a resident denoiser leaves the weights untouched by default.
  • The existing gate and fold tests now set UNSLOTH_DIFFUSION_LORA_FUSE=1. Without that, they would test the default.
python -m pytest tests/test_diffusion_lora_fuse.py tests/test_diffusion_lora_fold_gate.py tests/test_diffusion_manual_cast_lora.py
49 passed, 2 skipped

On the unpatched gate the five new default-off cases fail.

Update: opt-in on resident cards too

A follow-up measurement on a Colab A100-40 with the denoiser resident (offload policy none, same model, LoRA, prompts and seed) shows the same trade-off, so the fold is now opt-in on every path (UNSLOTH_DIFFUSION_LORA_FUSE=1):

arm s/step s/image (4 steps) peak alloc / reserved restore copy
fold (main default) 0.1742 1.109 21.42 / 23.39 GiB 7.19 GiB on the card
fold, A/A repeat 0.1748 1.119 21.42 / 23.39 GiB same
unfolded (PEFT) 0.2092 1.254 14.23 / 15.79 GiB none
  • The fold is 16.7% faster per step (A/A 0.3%), but holds a 7.19 GiB restore copy on the card (it moves to pinned host RAM when the card has less than about 17 GiB to spare).
  • Against a whole-transformer fp32 reference, PEFT is closer on 4/4 prompts by one-step error and 3/4 by LPIPS (mean LPIPS 0.0274 folded vs 0.0223 unfolded).
  • Default renders therefore take PEFT's path everywhere; users who prefer the speed set UNSLOTH_DIFFUSION_LORA_FUSE=1. UNSLOTH_DIFFUSION_LORA_FUSE=0 stays a no-op off switch.
  • Tests: the fuse suites set the opt-in where they exercise folding; a new test checks a resident denoiser stays unfolded by default. 44 passed, 2 skipped. test_integrated_gpu_no_host_pin.py has 3 failures that are identical on the parent commit.

…hen opted in

Against an exact fp32 computation of the adapted layers, rounding the merged
weight to bf16 lands further from the reference than PEFT's unfolded branch on
most prompts (FLUX.2 klein 4B, L4). Group offload loads now keep the unfolded
path unless UNSLOTH_DIFFUSION_LORA_FUSE=1; loads with no offload fold as before.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T03:19:42.325092Z 5affbd1 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. You're on a roll.

Reviewed commit: 58720c5fa7

ℹ️ 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 changed the title Studio diffusion: fold a constant LoRA set under group offload only when opted in Studio diffusion: fold a constant LoRA set only when opted in Nov 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 5affbd1db7

ℹ️ 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 2f9b73d into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the studio-lora-fold-followup branch November 23, 2026 05:09
danielhanchen added a commit that referenced this pull request Nov 23, 2026
… graph release and quantize OOM (#19011)

## Summary

Follow-up fixes from a recheck of the merged Studio training and memory
PRs #18967, #18978 and #18980. Each commit fixes one root cause and adds
a test that fails on the merge base (`02bed8883e`) and passes here.
#18964 and #18983 were rechecked as well and need no change.

## Changes

1. **DDP compares the converted layer set, not only the precision
label** (#18967). `check_effective_precision` gathered one precision
code per rank. The fp8 and W8A8 converters keep a layer that fails to
convert in bf16 and still report success, so two ranks could both report
`fp8` while training different frozen bases. In a real two-process Gloo
run with one rank-local constructor failure, rank 0 converted 2 of 2
layers, rank 1 converted 1 of 2, and both passed. Each rank now also
sends a digest and count of its sorted `(name, format)` set from
`lowp_layers_digest`, and every rank refuses when they differ. A count
alone would miss equal counts at different layers. Callers that pass no
`layers` keep the old one-int64 exchange.
2. **An unreadable Windows ROCm card keeps the default memory budgets**
(#18967). `rocm_windows_discrete()` negated `device_is_integrated()`,
which answers False when the device property cannot be read. An APU
whose classification failed therefore lost budgeted checkpointing and
the dequant cache, like a known discrete Radeon. The new
`device_integrated_status()` returns True, False or None (unknown), and
only a positive discrete reading turns the budgets off.
`device_is_integrated()` behaves as before.
3. **The env oversized override releases idle CUDA graphs like the
request flag** (#18978). `graph_release_fits` cleared `allow_oversized`
for its un-overridden check, but `image_activation_verdict` still read
`UNSLOTH_DIFFUSION_ALLOW_OVERSIZED_GENERATE`. With the env override set,
the release returned 0 without reading the pool, and the request took
the oversized path even when dropping the graphs would have let it run
normally. On the recorded L4 6-image case, `allow_oversized=True`
released 3.3 GiB while the env override released 0. The check now
ignores both overrides (`env_override=False`).
4. **Graph release credits only the pools this pipeline frees, on the
card being checked** (#18978). The guard credited every live graph pool
on the card and then reset only the image pipeline's handles. The
whole-step pool is shared across the process. While a co-resident video
pipeline still recorded into it, the reset freed nothing, and the image
graphs were dropped for no gain. `releasable_pool_bytes(handles,
device)` counts only whole-step pools that no other live wrapper records
into, plus the block-graph pools these handles own, on the named card. A
layer split's block card could also be refused because of its own idle
block-graph pool, with no release, because only the primary card ran
one. That card now drops the graphs and re-reads when their pool there
closes the gap. `UNSLOTH_DIFFUSION_GUARD_RELEASE_GRAPHS=0` still turns
both off.
5. **An OOM while quantizing a frozen layer is no longer counted as a
kept layer** (#18980). `convert_frozen_int8` and `convert_frozen_fp8`
caught `torch.cuda.OutOfMemoryError` (a `RuntimeError`) in their
per-layer `except (RuntimeError, ValueError)`. An allocation failure
inside the second layer's quantization therefore produced
`[FrozenInt8Linear, Linear]` and `True`. That run recorded the same
`base_int8_kernel='w8a8'` resume identity as a full conversion. The OOM
now propagates. W8A8 refuses a partly converted base through the check
#18980 added. fp8 had the same hole, and an exception escaping after
some layers converted left them inside a base the caller recorded as
bf16. The fp8 path now refuses a partial base the same way. The
host-first nf4 reload (`Fp8FallbackDoesNotFit`) still runs first.
Deliberate per-layer skips (alignment, a non-OOM error) are unchanged.

## Not changed

- #18980: a T4 without torchao passes the W8A8 preflight, but
`_resolve_base_precision` would refuse it. That function only runs on
the bf16 route. The fp16 route (`fp16_amp`) sets `base_precision`
directly and never calls it, so the preflight and the trainer agree.
- #18980: torch 2.1 `is_autocast_enabled(device)` and torch 2.4
compiled-backward cache misses are both below the supported torch floor.
The 2.4 case only affects performance, and its gradients are
bit-identical. Torch 2.10 through 2.15 engage the cache.

## Testing

- Flip tests: every new test fails on the merge base and passes here,
and each arm imports its own tree. Behavioural probes that use no new
symbols, base then head:
- Two-rank Gloo, rank-local fp8 layer failure: both ranks accepted, then
both ranks refused.
- Unreadable Windows ROCm card: `rocm_windows_discrete()` was True
(budgets off), now False.
- Image reset with a video wrapper sharing the pool: 3 GiB credited, now
0.
  - Env oversized override, L4 6-image case: release was 0, now 3.3 GiB.
- OOM inside the second W8A8 layer: returned True with a mixed base, now
refused.
- Changed test files on head (`test_diffusion_ddp_effective_precision`,
`test_diffusion_gc_budget_rocm_windows`,
`test_diffusion_guard_graph_release`, `test_diffusion_frozen_int8`,
`test_diffusion_layer_split_lifecycle`): 85 passed.
- 19 related training, graph and memory suites: base and head both 853
passed, 95 skipped, with the same 4 pre-existing failures (three
`test_integrated_gpu_no_host_pin` source scans and
`test_capture_then_replay_uses_one_graph_and_copies_statics`, which
cannot import `torch_config_guard` in its subprocess).
- `test_diffusion_dit_trainer`, `test_diffusion_training`,
`test_rocm_windows_vram_7072` on head: 340 passed.

## Not covered

- No GPU run. A real multi-GPU check (two cards, W8A8 or fp8 with one
injected rank-local failure) should confirm that both ranks refuse
before the first optimizer step and that a clean run trains.
- A real CUDA OOM during conversion, co-resident image and video graphs
on one card, and a layer split with block graphs on the second card were
tested with mocks only.
- The unreadable Windows ROCm property case was tested by mocking the
property read. No Windows ROCm hardware was used.
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