Skip to content

Studio: apply ComfyUI LoRA and LoKR files to Anima, Krea 2 and MOSS-Image - #16711

Merged
danielhanchen merged 46 commits into
unslothai:mainfrom
oobabooga:comfy-lora-files
Nov 5, 2026
Merged

danielhanchen merged 46 commits into
unslothai:mainfrom
oobabooga:comfy-lora-files

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Stacked on #16710, which adds the Anima family and MOSS-Image single files; merge that first.

Most community LoRAs for Anima, Krea 2 and MOSS-Image are written for ComfyUI's loader and failed in Studio:

  • Krea 2's ComfyUI int8 / fp8 files compile at load, so every LoRA was refused ("Speed compiled this model, so LoRAs are off"), and reloading compiled again.
  • Anima files with kohya .alpha keys failed in diffusers' converter, and an llm_adapter.embed LoRA was left on the meta device, crashing the first render.
  • LyCORIS LoKR (lokr_w1 / lokr_w2), the format of several of the most downloaded Krea 2 and MOSS-Image LoRAs, had no loader.
  • MOSS-Image had no LoRA loader.

Changes

  • diffusion_lora_files.py (new) normalizes ComfyUI / kohya files for these three families before they reach diffusers. It folds .alpha into lora_B (alpha / rank, as ComfyUI does), renames lora_down / lora_up, maps Anima's embed pair to PEFT's embedding LoRA, and splits MOSS-Image's fused qkv. Other families keep diffusers' own reading.
  • LoKR modules run through a KronLinear wrapper that adds scale * x @ kron(w1, w2).T with two small matmuls, never building the dense delta. Factor scaling follows ComfyUI's LokrAdapter.
    • It is a wrapper rather than a forward hook because MOSS-Image's compiled forward dropped hooks.
    • The scale is a device tensor written in place, so a LoKR strength change keeps the compiled code and CUDA graphs.
    • Attaching or removing one rebuilds the group offload hooks, as diffusers' PEFT loader does, so the factors stream with their block.
  • load_adapter / set_adapter_weights / unload_adapters replace the diffusers calls in diffusion.py, so LoRA and LoKR adapters share one set of names and can sit on the same layer.
  • On ComfyUI-quantized files, LoRAs named at load attach before the compile, as Studio's own int8 / fp8 builds already bake them. Strength changes need no reload; a different adapter set does.
  • MOSS-Image's transformer gains PeftAdapterMixin, and its pipeline gains the LoRA methods.

Limitations

  • LoKR covers Linear layers of these three families. Other families, and LoKR convolutions (lokr_t2), are refused with a message.

  • Adapters cost more per image than in ComfyUI, which patches them into the weights. Per 1024² image on an RTX 6000 Ada:

    Case Studio ComfyUI
    Krea 2 LoRA / LoKR on a ComfyUI fp8 file 18 to 27 s about 9 s
    Anima turbo LoRAs 2.3 and 4.5 s 2 and 4 s
    Anima style LoRA 17 to 20 s 13.5 s
    MOSS-Image 4-step LoRA 1.7 s 1.5 s
    MOSS-Image LoKR 15 to 17 s 11 s
  • When the transformer streams through group offload, renders after an adapter is added or removed are about 2x slower and differ slightly (6.8 / 255 per pixel) from the first bare render. A plain LoRA through diffusers' own loader gives the same numbers, so this predates the PR and is not addressed here.

Verification

  • Against ComfyUI v0.44.0, 3 prompts × 3 seeds with the creators' settings, on Comfy-Org/Krea-2, Comfy-Org/MOSS-Image, circlestone-labs/Anima and community fine-tunes. Adapters: the official Anima turbo LoRA (circlestone-labs/Anima-Official-LoRAs), plus community LoRAs and LoKRs from the monthly most-downloaded lists (a .alpha file, an embedding pair, lora_down / lora_up, a fused qkv LoKR).
    • All generate; none did before.
    • Each adapter changes the image by a similar amount in both tools (mean |diff| per pixel against no adapter, ComfyUI / Studio): Krea 2 LoKR 43.3 / 44.3, Krea 2 LoRA 41.7 / 35.5, Anima style 48.5 / 43.8, MOSS-Image LoKR 33.4 / 23.7.
    • The turbo LoRAs give sharp images at CFG 1 in 4 (MOSS-Image), 8 (Anima) and 12 (Anima 2.9B) steps.
  • The first PR's 22 checkpoints plus these adapter and encoder cases: 32 of 32 load, 96 images. This run and the ComfyUI comparison used this branch's first commit.
  • With the follow-up commits, a strength change through /images/generate without a reload changes the image (19.6 to 42.3 per pixel between weights 1 and 0) and repeats exactly (0.0). The same holds for Krea 2 streamed through group offload on an RTX 3090, with a LoKR and a LoRA together.
  • Full diffusion test suite: 18849 passed. Of the 6 failures, 4 fail the same way on main. The other 2, in test_diffusion_native_quant.py, pass alone; they fail after any real PEFT injection in the same worker, because peft caches is_torchao_available(). test_diffusion_peft_torchao_guard.py triggers the same failures without this PR.

Screenshots

Left three columns are ComfyUI, right three are this branch: same files, adapters, prompts and seeds.

Krea 2 Turbo + LoKR, Krea 2 fine-tune + LoRA, MOSS-Image + 4-step LoRA, MOSS-Image + LoKR

Anima base + official turbo LoRA, Anima 2.9B fine-tune + turbo LoRA, Anima base + style LoRA

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 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-05T11:00:56.777866Z a2d8a82 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[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 348782350b

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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: acb7eee3a3

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

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: 1c8127f6d0

ℹ️ 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 +699 to +701
if not isinstance(state_dict, dict):
from safetensors.torch import load_file
state_dict = load_file(str(state_dict))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve safetensors adapter metadata in the MOSS loader

For a MOSS-Image adapter saved in diffusers format with lora_adapter_metadata specifying a non-default alpha, this discards the metadata before calling load_lora_adapter. diffusion_lora_files.load_adapter deliberately passes unchanged files by path so diffusers can recover that configuration, but load_file returns only the tensors. For example, an adapter with r=2, lora_alpha=8 consequently receives scale 1 instead of 4, silently changing generation results. Preserve and apply the adapter metadata when converting the file to a state dict.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 627db72: the MOSS-Image loader reads the file's adapter metadata and passes it to load_lora_adapter (a tiny check with r=2, lora_alpha=8 now gets scale 4.0, was 1.0).

Comment on lines +214 to +216
parent, attr = _parent_of(root, module)
wrapper = cls(module)
setattr(parent, attr, wrapper)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore the original layer when LoKR allocation fails

When attaching a LoKR at generation time, an OOM copying w2 or creating the scale occurs after the original layer has already been replaced. _attach_lokr adds the adapter to its rollback list only after this constructor returns, so the failing wrapper is neither restored nor registered. On a MOSS LoKR-only load, unload_lora_weights is also a no-op without PEFT configuration, leaving the wrapper and any allocated GPU buffers stranded even after unload_adapters. Allocate the factors before replacing the layer, or restore the original layer if construction fails.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in f11f0ba: the factors and the scale are allocated before the layer is swapped, so a failed allocation leaves the original layer in place.

"scheduler": ("scheduler", "diffusers", "FlowMatchEulerDiscreteScheduler"),
}

_CONTAINER_PREFIXES = ("model.diffusion_model.", "net.")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Strip the diffusion_model prefix from Anima checkpoints

An Anima checkpoint with diffusion_model.* keys is recognized as Anima by diffusion_content.classify_tensors, but this prefix list does not include that container. Consequently, diffusion_model.llm_adapter.* never enters the conditioner branch in split_anima_checkpoint, and loading fails with the misleading error that the checkpoint has no text-conditioner weights. Include diffusion_model. among the stripped prefixes so checkpoints accepted by detection can reach the converter.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 555fabd on the parent branch (merged here in a2d8a82): a bare diffusion_model. prefix is now stripped like the other container prefixes.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: a2d8a82cfd

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

Copy link
Copy Markdown
Member

The staging run's seam-guard job fails on this PR (danielhanchen#3911):

tests/test_diffusion_autoopt_parity.py:560: in test_autoopt_resolves_the_same_optimizations_as_before
E   AssertionError: {'image|chroma|default|bfloat16|offload=0|gguf=0': {'before': {'applied': [['compiled', 'cuda_graph', 'cudnn_benchmark...
FAILED test_legacy_sequence_still_matches_fixture

Both parity tests compare the optimizations each family resolves against the recorded fixture, and the image|chroma row now resolves a different set (the diff includes compiled_vae_decode). If the new Chroma optimizations are intended, the fixture needs regenerating for that row in this PR; if not, the Chroma family is picking up levers it should not.

@danielhanchen

Copy link
Copy Markdown
Member

Correction to my note above: the seam-guard failure is not from this PR. It fails on main too, since #16762 regenerated the parity fixture on a branch that predated the Anima and Chroma families. #16838 updates those rows; once it lands, a rerun here should go green on that job.

danielhanchen added a commit that referenced this pull request Nov 5, 2026
…er rows (#16838)

## Summary

`seam-guard` (`studio/backend/tests/test_diffusion_autoopt_parity.py`)
fails on main and on every PR that runs it, for example the staging runs
for #16711 and #16799:

```
FAILED tests/test_diffusion_autoopt_parity.py::test_autoopt_resolves_the_same_optimizations_as_before
FAILED tests/test_diffusion_autoopt_parity.py::test_legacy_sequence_still_matches_fixture
E   AssertionError: {'image|chroma|default|bfloat16|offload=0|gguf=0': {'before': {'applied': [['compiled', 'cuda_graph', 'cudnn_benchmark', 'fp16_accum']], ...
```

Bisected on main: `7d0c0952a0` (#16762, "TF32 matmuls on the default
speed tier, not only max") is the first failing commit; its parent
passes. #16762 added `tf32` to the default tier and regenerated
`fixtures/diffusion_autoopt_parity.json`, but its branch predates
#16710, which added the Anima and Chroma families. Those 16 rows (2
families x 2 dtypes x offload x GGUF on the default tier) kept their
pre-#16762 values, so both parity tests now see them change. The code is
right; the fixture is stale for the two families that landed in between.

## Change

`studio/backend/tests/fixtures/diffusion_autoopt_parity.json` only. The
16 `image|anima|default|...` and `image|chroma|default|...` rows are
rewritten from the current resolver, in the file's existing
one-row-per-line format. In every one of them the only change is `tf32`
appended to `applied`, the same change #16762 made to the other
families' default-tier rows. No other row moves, and both
`autoopt_entry` and `legacy_entry` produce the new rows.

## Testing

- `tests/test_diffusion_autoopt_parity.py` and
`tests/test_diffusion_speed.py`: main 2 failed; this branch 236 passed.
- `7d0c0952a0~1`: the two parity tests pass; `7d0c0952a0`: they fail,
which is the bisect above.
- A script check over the diff: 16 rows changed, and in each the only
difference is `tf32` added to `applied`.
@danielhanchen
danielhanchen merged commit 083ba2f into unslothai:main Nov 5, 2026
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Nov 6, 2026
…nslothai#16874)

A ComfyUI-quantized single file (fp8 or int8 ConvRot) loaded with
adapters bakes them before the compile, and they then run as layers on
every step. A LoRA adds two small GEMMs per adapted Linear. A full-rank
LoKR adds about a quarter of the Linear's own GEMM in bf16, which costs
more than the fp8 GEMM it sits next to. ComfyUI patches the adapters
into the weights instead (dequantize, add the delta, requantize), so
they cost nothing per step there.

Seconds per step, RTX 6000 Ada, 1024², community adapters from unslothai#16711's
set, lower is better:

| | Before (main) | After (this PR) | ComfyUI v0.44.0 |
|---|---|---|---|
| Krea 2 Turbo fp8 + LoKR | 1.27 | 0.74 | 1.07 |
| Krea 2 fine-tune fp8 + LoRA | 0.83 | 0.76 | 0.81 |
| MOSS-Image SFT int8 ConvRot + LoKR (fused `qkv`) | 1.19 | 0.54 | 0.44
|

The remaining MOSS-Image gap is the base model's own int8 step (0.54
against 0.44 without adapters too).

## Change

New `diffusion_lora_quant_merge.py`, called where a resident quantized
load bakes its adapters:

- Every adapted Linear is dequantized in float32 (ConvRot rotation
undone), the deltas are added (`scale * B @ A` for a LoRA, `kron(w1,
w2)` with its row slice for a LoKR), and the result is quantized back
into the layer's own `Float8Tensor` / `Int8Tensor` (or plain float)
tensors: a per-row scale recomputed for the merged weight, and seeded
stochastic rounding, as ComfyUI rounds a patched weight.
Round-to-nearest dropped every delta below half a step: the MOSS-Image
LoKR's effect fell from 19.6 to 16.5 per pixel.
- The PEFT and LoKR layers are then removed, so the compile sees the
base model alone (MOSS-Image's fused int8 path included).
- The original quantized data of every touched layer is kept in host
memory. A weight change copies it back into the same tensors and merges
again; weight 0 is the original weights. Compiled code and captured
graphs read those tensors, so they stay valid.

Kept on the current adapter-layer path: offloaded loads (the host copy,
not the card's, is the source there), adapters that also touch a text
encoder, DoRA / LoRA-bias layers, anything but a plain or ConvRot Linear
with a registered weight, other weight formats, and a host without room
for the backups in its usable RAM (cgroup limits included).
`UNSLOTH_DIFFUSION_LORA_QUANT_MERGE=0` turns it off.

At `max` speed, diffusers' QKV fusion is skipped on a merged load: its
fused `to_qkv` is a copy that a weight change would not reach. Studio's
own fused paths (Z-Image, MOSS-Image, int8) are views of the projections
and follow it.

A weight change that fails (an out-of-memory during the re-merge) leaves
the base weights and records the adapters at weight 0, so the next
request merges again. A load that ended up offloaded refuses weight
changes with a reload message, as a streamed graph already does.

## Verification

- The table above, against ComfyUI on the same files.
- Weight 1, weight 0, weight 1 again through `/images/generate` with no
reload, for the Krea 2 LoKR, the Krea 2 LoRA, the MOSS-Image LoKR and
the MOSS-Image 4-step LoRA: weight 0 equals the model without the
adapter exactly (mean |diff| 0.0; with the adapter layers at weight 0 it
was 1.6 to 11 per pixel), the repeated weight reproduces the image
exactly (0.0), and the adapter effect matches the layer path (Krea 2
LoKR 37.2, Krea 2 LoRA 38.5, MOSS-Image LoKR 19.9 per pixel).
- 3 prompts x 2 seeds per case, side by side with ComfyUI: no artifacts.
- Full diffusion, MOSS-Image and LoRA test files (`pytest -n 8`, 19,100+
tests): the only failures are the same 27 that fail on main with the
same command (environment-dependent PyAV and attention-kernel tests, and
tests that only fail when xdist puts them in one worker).
- Tests:
- `test_diffusion_lora_quant_merge.py`: merged weight against `base +
delta` for int8 ConvRot, fp8 and dense; weight 0 restores the original
codes and a weight merges to the same codes twice; the qdata / scale
tensors are written in place; a fused `qkv` row slice; a PEFT LoRA at
its alpha / r; adapters outside the denoiser, an unsupported format and
the kill switch keep the adapter layers.
- Also: a wrapped Linear and a host without room keep the adapter
layers; a failed re-merge records the adapters as off and the next
request merges again; an offloaded load refuses a weight change. These
four fail before the follow-up commit. `max` speed never fuses QKV over
merged weights (fails without its guard).
-
`test_merged_quant_file_adapters_change_weight_in_place_with_no_recompile`:
a compiled model follows a weight change, switching the adapter off and
back on with one compile and no graph reset. It fails without the
routing in `_adjust_baked_loras`.

---------

Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
…ile (unslothai#17088)

## Summary

Follow-up to unslothai#16711. For Anima, Krea 2 and MOSS-Image, Studio normalises
LoRA files before loading them. A file that needs no rewrite loads by
path, and diffusers reads `lora_adapter_metadata` (`lora_alpha`, `r`,
`alpha_pattern`, `use_rslora`) from its safetensors header.

A file that does need a rewrite loads from a tensor dict instead.
Rewrites cover:
- `lora_down` / `lora_up` names
- MOSS fused `qkv`
- Kohya underscore keys
- a LoRA + LoKR mix

With a dict, diffusers never sees the header, so every module ran at
scale 1 instead of `lora_alpha / r`.

Repro with real PEFT and a tiny real MOSS transformer: both files hold
identical tensors and metadata `r = 2, lora_alpha = 8`.

| File keys | main | this PR |
|---|---|---|
| `lora_A` / `lora_B` (loads by path) | rel. error 1.6e-08 vs the alpha
8 / r 2 delta | 1.6e-08 (same path, untouched) |
| `lora_down` / `lora_up` (rewritten) | rel. error **0.75** (scale 1.0)
| 1.6e-08 |

Same results on peft 0.18.0 and 0.21.2.

## Changes

- `load_adapter` reads the file's `lora_adapter_metadata` only when the
file is rewritten. It keeps the `transformer.` keys, the same filtering
diffusers applies under that prefix.
- `normalize_lora` folds the resulting per-module scale into `lora_B`,
the same way it already folds a tensor `.alpha`. Diffusers then runs the
module at scale 1 and the delta is unchanged.
- The per-module scale is `alpha_pattern` / `lora_alpha` over the real
tensor rank, or over `sqrt(rank)` with `use_rslora`.
- A tensor `.alpha` still wins over the header.
- The scale is folded before the MOSS qkv split, so patterns naming the
fused layer still match.
- A `use_dora` header is left as before.
- A file without metadata, or one that loads by path, takes exactly the
same route as before.
- Kill switch: `UNSLOTH_DIFFUSION_LORA_REWRITE_METADATA=0`.

## Tests

`tests/test_diffusion_lora_files.py` gains tests for:
- the real-MOSS strength check, native and renamed
- the kill switch
- pattern / rslora / DoRA / `.alpha` precedence
- the fused-qkv split
- header parsing

22 passed, 3 GPU-only tests skipped, on peft 0.18.0, 0.19.1, 0.20.0 and
0.21.2.

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

Same MOSS check on CUDA, base and head one per T4, 3 reps each. Relative
error against the alpha 8 / r 2 delta:

| File keys | main | this PR |
|---|---|---|
| native | 0.0 | 0.0 |
| renamed | 0.75 | 0.0 |

After review, `alpha_pattern` / `rank_pattern` lookups use PEFT's own
`get_pattern_key` expression, `(.*\.)?(key)$`. That includes
caret-prefixed keys.

A second review pass found a related gap. PEFT scales the whole `lora_B`
output, so a `lora_B.bias` kept by the rewrite now carries the folded
scale too. This covers both sources: a tensor `.alpha`, which had the
same gap on main, and the metadata. A new test checks both.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 8, 2026
…quantised single files (unslothai#17087)

## Summary

Follow-up to unslothai#16711. With peft 0.19.x, loading a plain LoRA onto a
quantised single file's int8 / fp8 transformer fails during adapter
injection:

```
TypeError: TorchaoLoraLinear.__init__() missing 1 required keyword-only argument: 'get_apply_tensor_subclass'
```

Why it fails:
- peft 0.19 dispatches every `TorchAOBaseTensor` weight to
`TorchaoLoraLinear`, and its constructor requires a requantisation
callback.
- peft reads that callback only from a transformers `hf_quantizer`.
Studio builds these `Int8Tensor` / `Float8Tensor` weights directly from
the file, so the callback is never there.
- peft 0.18 routes those weights to a plain `lora.Linear`, so it works.
- peft 0.20 made the callback optional: forward and training work, and
only merge / unmerge refuse (huggingface/peft
`src/peft/tuners/lora/torchao.py`).
- Studio pins peft 0.18.1, but the supported range is 0.18.0 to 0.20.x,
so 0.19.x users hit this.

## Changes

- When peft's LoRA module loads, `diffusion_torchao_patches` gives
`TorchaoLoraLinear.__init__` the same `get_apply_tensor_subclass=None`
default that peft 0.20 has.
- The patch only applies when the installed signature has the
keyword-only, no-default parameter, which means peft 0.19.x. On peft
0.18 and 0.20+ it changes nothing.
- A callback that transformers supplies still wins.
- The patch is idempotent and keeps `__wrapped__`.
- It hooks into the existing peft import hook, so importing peft stays
lazy.
- Studio does not call peft's merge on these layers. The quantised merge
path (`diffusion_lora_quant_merge`) does its own dequantise, add and
requantise.
- Kill switch: `UNSLOTH_STUDIO_PEFT_TORCHAO_OPTIONAL_CALLBACK=0`.

## Evidence (CPU, Studio's real `_int8_tensor` / `_fp8_tensor`
constructors, diffusers `load_lora_adapter`)

Results for `test_diffusion_lora_quant_merge.py` +
`test_diffusion_peft_torchao_guard.py`, torch 2.10 / torchao 0.18 /
diffusers 0.42.1:

| peft | main | this PR |
|---|---|---|
| 0.18.0 | 31 passed (new unit tests absent) | 35 passed |
| 0.19.1 | `test_a_peft_lora_merges_at_its_alpha_scale` and the new int8
/ fp8 injection tests fail with the TypeError above | 35 passed |
| 0.20.0 | 31 passed | 35 passed |
| 0.21.2 | 31 passed | 35 passed |

The new head tests also pass on:
- torch 2.12.1 / torchao 0.17 / peft 0.19.1 / diffusers 0.40
- torch 2.10 CPU / torchao 0.17 with peft 0.18.0 and 0.19.1

The int8 injection test also checks the LoRA output against `base + B @
A x` (relative error < 2%, the bf16 path). The fp8 forward is not run on
CPU, because torch's CPU `_scaled_mm` only takes per-tensor scales.

## GPU (Kaggle T4 sm75 and Colab L4 sm89; torch 2.10 / peft 0.19.1 /
torchao 0.16 / diffusers 0.42.1)

Base and head ran one per T4 in the same kernel, 3 reps each. Setup: an
int8 ConvRot layer of 256 x 512 on CUDA, a LoRA loaded through diffusers
`load_lora_adapter`, then a forward pass checked against `base + B @ A
x`.

| | main | this PR |
|---|---|---|
| int8 | `TypeError: ... missing 1 required keyword-only argument:
'get_apply_tensor_subclass'` | loads as `TorchaoLoraLinear`, rel. error
1.9e-3 |
| fp8 (Colab L4, sm89, 3 interleaved reps) | same `TypeError` | loads as
`TorchaoLoraLinear`, rel. error 1.9e-3 |
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.

2 participants