OneTrainer icon indicating copy to clipboard operation
OneTrainer copied to clipboard

Anima

Open dxqb opened this issue 6 months ago • 1 comments

Includes:

  • #1392 — Upgrade torch - needed because of Anima uses the Qwen VAE: https://github.com/Nerogar/OneTrainer/issues/1371
  • #1285 — Upgrade transformers to 5.x: needed by diffusers now

dxqb avatar May 30 '26 08:05 dxqb

Unsure if this is in scope for this PR, but I think it would be useful to expose an optional toggle to train Anima's llm_adapter. From my testing with multi-concept training, training the llm adapter seems to improve concept adherence, converge faster, and reach lower loss/val. I know tdrussel recommends to avoid training it, but in my experiments I have not seen obvious degradation of general knowledge, while the trained concepts became more reliable.

NerissG avatar Jun 01 '26 12:06 NerissG

Using compiled optimizer (AdamW_adv) will cause an error. With other DiTs using compiled optimizer usually gives some training speed benefit. So it would be probably useful for Anima, too. Error log:

0530 20:41:45.112000 49275 venv/lib/python3.12/site-packages/torch/_inductor/utils.py:1717] [0/0] Not enough SMs to use max_autotune_gemm mode
                                                                               W0530 20:42:04.793000 49275 venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py:1853] [1/8] torch._dynamo hit config.recompile_limit (8)
W0530 20:42:04.793000 49275 venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py:1853] [1/8]    function: '_step_parameter' (/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/adv_optm/optim/AdamW_adv.py:264)
W0530 20:42:04.793000 49275 venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py:1853] [1/8]    last reason: 1/5: tensor 'p' size mismatch at index 0. expected 4, actual 8192. Guard failed on a parameter, consider using torch._dynamo.config.force_parameter_static_shapes = False to allow dynamism on parameters.
W0530 20:42:04.793000 49275 venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py:1853] [1/8] To log all recompilation reasons, use TORCH_LOGS="recompiles".
W0530 20:42:04.793000 49275 venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py:1853] [1/8] To diagnose recompilation issues, see https://docs.pytorch.org/docs/main/user_guide/torch_compiler/compile/programming_model.recompilation.html
step:  11%|▋     | 1/9 [00:25<03:21, 25.23s/it, loss=0.0921, smooth loss=0.0921]
epoch:   0%|                                             | 0/10 [00:35<?, ?it/s]
Traceback (most recent call last):
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py", line 1883, in _compile
    raise_unimplemented_cache_limit_exceeded()
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py", line 1867, in raise_unimplemented_cache_limit_exceeded
    unimplemented(
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/_dynamo/exc.py", line 657, in unimplemented
    raise Unsupported(msg, gb_type, skip_frame)
torch._dynamo.exc.Unsupported: Dynamo recompile limit exceeded
  Explanation: Dynamo attempted to recompile the code object too many times, exceeding the recompile_limit cache size limit (currently set to 8). Excessive recompilations can degrade performance due to the compilation overhead of each recompilation.
  Hint: To monitor recompilations, enable TORCH_LOGS=recompiles. If recompilations are expected, consider increasing torch._dynamo.config.recompile_limit to an appropriate value.
  Hint: See https://docs.pytorch.org/docs/main/user_guide/torch_compiler/compile/programming_model.recompilation.html for tips on dealing with recompilations.

  Developer debug context: Limit type: recompile_limit

 For more details about this graph break, please visit: https://meta-pytorch.github.io/compile-graph-break-site/gb/gb0039.html

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/modules/ui/TrainUI.py", line 735, in __training_thread_function
    trainer.train()
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/modules/trainer/GenericTrainer.py", line 783, in train
    self.model.optimizer.step()
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/optim/lr_scheduler.py", line 166, in wrapper
    return func.__get__(opt, opt.__class__)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/optim/optimizer.py", line 535, in wrapper
    out = func(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/utils/_contextlib.py", line 124, in decorate_context
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/adv_optm/optim/AdamW_adv.py", line 390, in step
    self.step_parameter(p, group, i)
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/utils/_contextlib.py", line 124, in decorate_context
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/adv_optm/optim/AdamW_adv.py", line 260, in step_parameter
    step_param_fn(p, grad, state, group, step_size, beta1, beta2, sqrt_bias_correction2, random_int_tensor)
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 1047, in compile_wrapper
    result = fn(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py", line 2474, in __call__
    result = self._torchdynamo_orig_backend(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py", line 736, in __call__
    result = _compile(
             ^^^^^^^^^
  File "/home/user/AI/Anima_OT-TEST/OneTrainer/venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py", line 1890, in _compile
    raise FailOnRecompileLimitHit(
torch._dynamo.exc.FailOnRecompileLimitHit: Hard failure due to fullgraph=True

Silvicultor avatar Jun 02 '26 19:06 Silvicultor

Unsure if this is in scope for this PR, but I think it would be useful to expose an optional toggle to train Anima's llm_adapter. From my testing with multi-concept training, training the llm adapter seems to improve concept adherence, converge faster, and reach lower loss/val. I know tdrussel recommends to avoid training it, but in my experiments I have not seen obvious degradation of general knowledge, while the trained concepts became more reliable.

training text components should be a thing of the past. it's always been a crutch for diffusion models that weren't very capable yet. So I'm hesitant to reintroduce this, with all the problems that come with it (such as having multiple learning rates and many more failure modes). If there is strong community support that this is needed, maybe, but if even the model's creator advises against it...

dxqb avatar Jun 02 '26 19:06 dxqb

torch._dynamo.exc.FailOnRecompileLimitHit: Hard failure due to fullgraph=True

fixed by https://github.com/Nerogar/OneTrainer/pull/1495, merged into this PR

dxqb avatar Jun 04 '26 18:06 dxqb

Thank you for your great work!

I've been training Anima LoRAs in OneTrainer and using the same dataset/settings in Kohya sd-scripts. Training itself works fine, but LoRAs saved from OneTrainer (preview branch) don't load correctly in ComfyUI when paired with the standard single-checkpoint Anima model (anima-base-v1.0.safetensors). I believe this is due to the LoRA key naming on export.

Example key:

  • sd-scripts: lora_unet_blocks_0_self_attn_q_proj.lora_down.weight
  • OneTrainer: transformer.transformer_blocks.0.attn1.to_q.lora_down.weight

Other model types in OneTrainer already handle this via convert_*_lora.py key sets (e.g. Flux, HiDream, SD3). Anima's AnimaLoRASaver and AnimaLoRALoader both return None from _get_convert_key_sets(), so no conversion runs on save or load.

Diffusers has the inverse mapping in _convert_non_diffusers_anima_lora_to_diffusers() (lora_conversion_utils.py), which lines up with the rename table already documented in AnimaModel.py (diffusers_to_original()).

I prototyped the conversion script as below. It might be missing things as I haven't tested exhaustively yet:

# convert_anima_lora.py
from modules.util.convert.lora.convert_lora_util import LoraConversionKeySet


def __map_anima_blocks(parent: LoraConversionKeySet) -> list[LoraConversionKeySet]:
    return [LoraConversionKeySet(
        omi_prefix=f"blocks.{i}",
        diffusers_prefix=f"transformer_blocks.{i}",
        legacy_diffusers_prefix=f"blocks_{i}",
        parent=parent,
        next_omi_prefix=f"blocks.{i + 1}",
        next_diffusers_prefix=f"transformer_blocks.{i + 1}",
    ) for i in range(100)]


def __map_transformer_block(key_prefix: LoraConversionKeySet) -> list[LoraConversionKeySet]:
    mappings = [
        ("self_attn.q_proj", "attn1.to_q", "self_attn_q_proj"),
        ("self_attn.k_proj", "attn1.to_k", "self_attn_k_proj"),
        ("self_attn.v_proj", "attn1.to_v", "self_attn_v_proj"),
        ("self_attn.output_proj", "attn1.to_out.0", "self_attn_output_proj"),
        ("cross_attn.q_proj", "attn2.to_q", "cross_attn_q_proj"),
        ("cross_attn.k_proj", "attn2.to_k", "cross_attn_k_proj"),
        ("cross_attn.v_proj", "attn2.to_v", "cross_attn_v_proj"),
        ("cross_attn.output_proj", "attn2.to_out.0", "cross_attn_output_proj"),
        ("mlp.layer1", "ff.net.0.proj", "mlp_layer1"),
        ("mlp.layer2", "ff.net.2", "mlp_layer2"),
    ]

    return [
        LoraConversionKeySet(omi, diffusers, legacy_diffusers_prefix=legacy, parent=key_prefix)
        for omi, diffusers, legacy in mappings
    ]


def convert_anima_lora_key_sets() -> list[LoraConversionKeySet]:
    keys = []

    transformer = LoraConversionKeySet(
        "lora_unet",
        "transformer",
        legacy_diffusers_prefix="lora_unet",
    )

    for block_prefix in __map_anima_blocks(transformer):
        keys += __map_transformer_block(block_prefix)

    return keys

After converting, the output in ComfyUI seems to be affected by the LoRA as expected.

FuouM avatar Jun 05 '26 08:06 FuouM

I've been training Anima LoRAs in OneTrainer and using the same dataset/settings in Kohya sd-scripts. Training itself works fine, but LoRAs saved from OneTrainer (preview branch) don't load correctly in ComfyUI when paired with the standard single-checkpoint Anima model (anima-base-v1.0.safetensors). I believe this is due to the LoRA key naming on export.

https://github.com/Comfy-Org/ComfyUI/pull/14182

dxqb avatar Jun 05 '26 17:06 dxqb

I've been training Anima LoRAs in OneTrainer and using the same dataset/settings in Kohya sd-scripts. Training itself works fine, but LoRAs saved from OneTrainer (preview branch) don't load correctly in ComfyUI when paired with the standard single-checkpoint Anima model (anima-base-v1.0.safetensors). I believe this is due to the LoRA key naming on export.

Comfy-Org/ComfyUI#14182

Doesn't look like Comfyanon wants to merge this one and also keep in mind that other inference tools (at least the ones that aren't built upon Diffusers) would also have to make the same change to their code. So I say OneTrainer should include the above proposed conversion logic into it's code and settle for the de-facto standard already established. I know OT wants to use Diffusers keys whenever possible for consistency, and that's perfectly fine for all the models like Flux or Qwen, their original repos being Diffusers format, but this is a special case. Initial Anima release wasn't in Diffusers format, so it's hard to argue for the Diffusers keys.

Silvicultor avatar Jun 05 '26 19:06 Silvicultor

I've been training Anima LoRAs in OneTrainer and using the same dataset/settings in Kohya sd-scripts. Training itself works fine, but LoRAs saved from OneTrainer (preview branch) don't load correctly in ComfyUI when paired with the standard single-checkpoint Anima model (anima-base-v1.0.safetensors). I believe this is due to the LoRA key naming on export.

Comfy-Org/ComfyUI#14182

Doesn't look like Comfyanon wants to merge this one

if that is the case, they should close the PR. As for the other points, we already had this discussion on Discord.

dxqb avatar Jun 05 '26 19:06 dxqb

By the way, this PR already includes conversion code: https://github.com/dxqb/OneTrainer/blob/03b7156c49bac5c8f5a8f13de259357f94047d75/modules/model/AnimaModel.py#L31

It's just not used for LoRAs currently (only for full finetunes), because this was the consistent and accepted way to do things for all other models. If inference tools want to change that now, they should make that clear (by closing the PR, for example)

dxqb avatar Jun 05 '26 19:06 dxqb