Finetuned models aren't saved or loaded properly in train_custom_diffusion.py
Describe the bug
Thank you for your amazing work. It seems like models are not saved or loaded properly after finetuning train_custom_diffusion.py in a new dataset. Generated validation images are expected but final test (inference) results are not expected as finetuned models are not used properly. The bug most probably in the following lines.
Reproduction
Please finetune using a custom dataset and see the final test/inference results.
Logs
No response
System Info
- 珞 Diffusers version: 0.31.0.dev0
- Platform: Linux-6.5.0-45-generic-x86_64-with-glibc2.17
- Running on Google Colab?: No
- Python version: 3.8.19
- PyTorch version (GPU?): 2.4.0+cu121 (True)
- Flax version (CPU?/GPU?/TPU?): not installed (NA)
- Jax version: not installed
- JaxLib version: not installed
- Huggingface_hub version: 0.24.6
- Transformers version: 4.44.0
- Accelerate version: 0.33.0
- PEFT version: not installed
- Bitsandbytes version: not installed
- Safetensors version: 0.4.4
- xFormers version: not installed
- Accelerator: NVIDIA RTX A6000, 49140 MiB NVIDIA RTX A6000, 49140 MiB NVIDIA RTX A6000, 49140 MiB NVIDIA RTX A6000, 49140 MiB
- Using GPU in script?: 4 NVIDIA RTX A6000 GPUs
- Using distributed or parallel set-up in script?: distributed
Who can help?
No response
This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.
Please note that issues that do not follow the contributing guidelines are likely to be ignored.
Hi, have you solved this issue?
Hi, thank you for your issue. I also met this problem.
Does anyone solve this problem or is it fixed?
After checking for some times, I found the following codes from diffusers may contain bugs:
unet.save_attn_procs(args.output_dir, safe_serialization=not args.no_safe_serialization)
pipeline.unet.load_attn_procs(args.output_dir, weight_name=weight_name)
After saving and loading from the files, the processors for CustomDiffusion are all lost.
Now, I avoided it by downgrading the versions:
pip install diffusers==0.26
pip install huggingface-hub==0.20.2
pip install transformers==4.28
If I have time in the future, I want to look into the unet.save_attn_procs and unet.load_attn_procs to see what is wrong.
This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.
Please note that issues that do not follow the contributing guidelines are likely to be ignored.
I think I figured out the bug.
In later versions of diffusers (I'm using 0.32.2) the pipeline.unet.load_attn_procs( ) script adds an if loop to the CustomDiffusion process (see attached image). Now you must additionally pass the _pipeline argument. Without passing _pipeline argument, load_attn_procs( ) will load the finetuned CustomDiffusion weights, but it will never set them. Since the attn_processors are neither set nor returned, they are lost when when load_attn_procs( ) returns. Adding the _pipeline argument will trigger the loop that calls set_attn_processor( ).
However, I think there's an additional bug here. At least in my case, CustomDiffusion saves with 16 procs (corresponding to each of 16 cross-attention layers). However, models.unets.unet_2d_condition.set_attn_processor( ) has a check to ensure that the number of procs matches the number of attention layers in pipeline.unet.attn_processors, which contains 32 procs (corresponding to 16 cross-attention procs and 16 self-attention procs). This causes the set_attn_processor( ) call to fail in my case.
I created a workaround as follows:
- Load CustomDiffusion attention processors (16 procs)
- Add in self-attention processors from original model (to get to 32 procs)
- Call set_attn_processor on the mixed processor dictionary
This code allows me to successfully generate images with my finetuned CustomDiffusion model.
Final comment: I think HuggingFace is not really paying attention to CustomDiffusion anymore. This CustomDiffusion code has not been updated across many versions, yet this thread is the only one I see about the saving/loading bug. I feel like if someone were actively monitoring this, the bug would have been noticed/fixed sooner. Perhaps it is time to start refocusing on more popular finetuning methods like LoRAs.
I tried the solution from @JStyborski but didn't work from my side (error at line pipeline.unet._process_custom_diffusion(state_dict=custom_unet_state_dict), 'to_k_custom_diffusion.weight' is not in the state_dict)
I think there is a bug in the function _process_custom_diffusion where only one type of processor CustomDiffusionAttnProcessor was checked while in the _get_custom_diffusion_state_dict function, there are three types of processors to be checked.
This still reproduces on current main (d6726f3), and @JStyborski's diagnosis above is exactly right. It's a two-line indentation defect in UNet2DConditionLoadersMixin.load_attn_procs.
src/diffusers/loaders/unet.py, lines 195–201:
is_model_cpu_offload = False
is_sequential_cpu_offload = False
is_group_offload = False
if _pipeline is not None:
is_model_cpu_offload, is_sequential_cpu_offload, is_group_offload = self._optionally_disable_offloading(
_pipeline=_pipeline
)
self.set_attn_processor(attn_processors) # <-- inside the guard
self.to(dtype=self.dtype, device=self.device) # <-- inside the guard
_pipeline is a private kwarg only passed by the pipeline-level loaders, so for every public caller — the docstring example at line 116, examples/custom_diffusion/train_custom_diffusion.py, examples/community/sde_drag.py, and the repo's own tests/models/unets/test_models_unet_2d_condition.py — the guard is False, the processors built on line 187 are never installed, and load_attn_procs silently returns a UNet with default AttnProcessor2_0. No error, no warning.
The comment immediately above the guard describes those two lines as unconditional work ("it just sets attention processors and puts all in the same dtype"), and the parallel structure in load_lora_adapter (loaders/peft.py) keeps them at function scope — so the over-indentation looks accidental.
Reproduced on CPU with a small hand-built UNet2DConditionModel, reusing create_custom_diffusion_layers from the existing test with mock_weights=True, then save_attn_procs → fresh model → load_attn_procs:
processor after load : AttnProcessor2_0
load_attn_procs took effect : False
max|loaded - trained| : 1.5328717231750488
With lines 200–201 dedented to function scope:
processor after load : CustomDiffusionAttnProcessor
load_attn_procs took effect : True
max|loaded - trained| : 0.0
Why the existing test doesn't catch it: test_custom_diffusion_save_load uses create_custom_diffusion_layers(model, mock_weights=False), which initialises the Custom Diffusion projections from the base weights, so a never-installed processor is numerically indistinguishable from the default one.
I have the two-line fix plus a regression test in TestUNet2DConditionCustomDiffusion (same style as the existing save/load test, but with mock_weights=True so the weights actually change the output). It fails on main and passes with the fix; the full test_models_unet_2d_condition.py is 51 passed / 95 skipped with it applied.
Per the AI-assisted contribution guidelines I'm checking here first rather than opening a PR — happy to send it if a maintainer is OK with the approach. @sayakpaul @DN6
Scope note: the separate proc-count mismatch for train_q_out=False configs mentioned earlier in this thread is not addressed by this change; that seems worth keeping separate.
Disclosure: I used AI assistance while investigating this. I've reproduced the behaviour and verified the fix and tests myself.
Hi! Is anyone still working on this? @Kaif10, you mentioned a fix in August. If you're still on it, I'll stay out of the way.
If not, I'd like to take it. I confirmed the bug is still on main: in src/diffusers/loaders/unet.py, self.set_attn_processor(attn_processors) and the following self.to(...) are indented under if _pipeline is not None:, so Custom Diffusion processors are only installed when a pipeline is passed. The fix is to dedent those two lines, plus a test in test_models_unet_2d_condition.py that loads Custom Diffusion weights without a pipeline and checks the processors are set.
I'd use AI assistance (Claude Code) and run the self-review skill. I'll wait for a maintainer's go-ahead before opening a PR.