Skip to content

Make torch.compile LoRA/key-compatible#8213

Merged
comfyanonymous merged 7 commits intomasterfrom
torch-compile-fix
May 21, 2025
Merged

Make torch.compile LoRA/key-compatible#8213
comfyanonymous merged 7 commits intomasterfrom
torch-compile-fix

Conversation

@Kosinkadink
Copy link
Member

Originally, torch.compile was implemented as an object_patch because there was no other built-in way to deal with changing an internal object to another without monkey patching.

However, this means the entirety of diffusion_model is changed to the OptimizedModel class as soon as the model begins to load, even before any weight patches are applied. The actual 'diffusion_model' is stored on the OptimizedModel's ._orig_mod parameter. So, anything relating to keys no longer applies, whether it be loras, hooks, or a simple get attr call.

This PR replaces the object_patch usage with a built-in wrapper that got added late last year as part of the hooks PR. It replaces diffusion_model with the torch.compile'd OptimizedModel object only when it gets to BaseModel.apply_model function, and replaces it with the original diffusion_model as soon as it leaves, for every step of sampling. This is only a reference swap so has basically no cost, and this is about as deep in the sampling code the existing wrappers allow for (meaning very little should be broken now by torch.compile).

The OptimizedModel object gets reused from the torch.compile call same as before.

…ntire diffusion_models object, allowing key assotiations on diffusion_models to not break (loras, getting attributes, etc.)
@Kosinkadink
Copy link
Member Author

This will take care of the lora problem that #6638 has a partial solution to.

@comfyanonymous comfyanonymous merged commit 65da29a into master May 21, 2025
6 checks passed
@comfyanonymous comfyanonymous deleted the torch-compile-fix branch May 21, 2025 08:57
orig_modules[key] = comfy.utils.get_attr(executor.class_obj, key)
comfy.utils.set_attr(executor.class_obj, key, value)
return executor(*args, **kwargs)
finally:

Choose a reason for hiding this comment

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

Hi @Kosinkadink I found if the image shape is changed, the patch of torch.compile will not work. Do you have any clue ? I‘d like to know how to trigger the patching when image shape is changed. thank you

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.

3 participants