Repository navigation
Studio: apply ComfyUI LoRA and LoKR files to Anima, Krea 2 and MOSS-Image - #16711
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if not isinstance(state_dict, dict): | ||
| from safetensors.torch import load_file | ||
| state_dict = load_file(str(state_dict)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
| parent, attr = _parent_of(root, module) | ||
| wrapper = cls(module) | ||
| setattr(parent, attr, wrapper) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.") |
There was a problem hiding this comment.
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 👍 / 👎.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
The staging run's Both parity tests compare the optimizations each family resolves against the recorded fixture, and the |
…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`.
…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]>
…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.
…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 |
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:
.alphakeys failed in diffusers' converter, and anllm_adapter.embedLoRA was left on the meta device, crashing the first render.lokr_w1/lokr_w2), the format of several of the most downloaded Krea 2 and MOSS-Image LoRAs, had no loader.Changes
diffusion_lora_files.py(new) normalizes ComfyUI / kohya files for these three families before they reach diffusers. It folds.alphaintolora_B(alpha / rank, as ComfyUI does), renameslora_down/lora_up, maps Anima's embed pair to PEFT's embedding LoRA, and splits MOSS-Image's fusedqkv. Other families keep diffusers' own reading.KronLinearwrapper that addsscale * x @ kron(w1, w2).Twith two small matmuls, never building the dense delta. Factor scaling follows ComfyUI'sLokrAdapter.load_adapter/set_adapter_weights/unload_adaptersreplace the diffusers calls indiffusion.py, so LoRA and LoKR adapters share one set of names and can sit on the same layer.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:
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
Comfy-Org/Krea-2,Comfy-Org/MOSS-Image,circlestone-labs/Animaand 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.alphafile, an embedding pair,lora_down/lora_up, a fusedqkvLoKR)./images/generatewithout 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.test_diffusion_native_quant.py, pass alone; they fail after any real PEFT injection in the same worker, because peft cachesis_torchao_available().test_diffusion_peft_torchao_guard.pytriggers the same failures without this PR.Screenshots
Left three columns are ComfyUI, right three are this branch: same files, adapters, prompts and seeds.