Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework ModelPatcher for upcoming ComfyUI update #498

Open
wants to merge 48 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
32c352e
Initial scaffolding for supporting FancyVideo, refactored load_motion…
Kosinkadink Aug 22, 2024
7c2c863
Improved description for Value Scheduling node
Kosinkadink Aug 22, 2024
df8eb6f
Merge branch 'main' into develop
Kosinkadink Aug 23, 2024
ae7ae37
In Create Raw Sigma Schedule, renamed lcm_zsnr to zsnr and changed lo…
Kosinkadink Aug 23, 2024
0475e70
Merge branch 'main' into develop
Kosinkadink Aug 28, 2024
00b63e6
Merge branch 'main' into develop
Kosinkadink Aug 30, 2024
0837d2b
Adjust ADEAUTOSIZE since after description feature was added, it work…
Kosinkadink Sep 1, 2024
6a1d498
Started work on NoiseCalibration implementation (pain)
Kosinkadink Sep 1, 2024
1a9d70e
Progress on FancyVideo support
Kosinkadink Sep 3, 2024
a77460c
Updated emb_patch, some upgrades for ModelSamplingConfig
Kosinkadink Sep 7, 2024
9a45452
Merge branch 'main' into develop
Kosinkadink Sep 18, 2024
e6a9638
Started porting over code to use upcoming ModelPatcher features in Co…
Kosinkadink Sep 21, 2024
3e3d297
Fixed FreeInit for new implementation
Kosinkadink Sep 21, 2024
a1b03d6
Ported Gen1 nodes to use upcoming ComfyUI features, refactored some c…
Kosinkadink Sep 22, 2024
f003299
Adapted sliding_calc_cond_batch and forward_timestep_embed to use new…
Kosinkadink Sep 24, 2024
8c3c948
Updated gen1 nodes and deprecated nodes to use new ModelPatcher syste…
Kosinkadink Sep 24, 2024
10e6b0b
Made Visualize Context Options nodes work after the refactor
Kosinkadink Sep 24, 2024
b960317
Refactored outer_sample_wrapper to work with my changes in in-progres…
Kosinkadink Sep 27, 2024
1698f9f
Fixed device mismatch issue in perform_image_injection (Image Injecti…
Kosinkadink Oct 7, 2024
3e93f15
Removed no longer needed code from sampling.py, removed ContextRefInj…
Kosinkadink Oct 8, 2024
82c8801
Merge branch 'main' into rework-modelpatcher
Kosinkadink Oct 25, 2024
0b01ea1
Refactored ADGS to be a variable stored within transformer_options in…
Kosinkadink Oct 25, 2024
2161721
Merge branch 'main' into rework-modelpatcher
Kosinkadink Oct 25, 2024
959fd3f
Match changes in patch_hooks_improved_memory ComfyUI branch
Kosinkadink Nov 3, 2024
0fb102e
Modified FunctionInjectionHolder to work more smoothily with new Comf…
Kosinkadink Nov 11, 2024
f32a382
Refactored nodes_conditioning.py to use new built-in ComfyUI hook fea…
Kosinkadink Nov 12, 2024
bac7a81
Deprecated most of nodes_conditioning nodes since they exist in vanil…
Kosinkadink Nov 12, 2024
3195564
Moved autosize param from optional to hidden for all nodes
Kosinkadink Nov 12, 2024
006ac04
Commented out NoiseCalibration and FancyVideo from user's view so can…
Kosinkadink Nov 12, 2024
c088d80
Made Prompt Scheduling work with schedule_clip, fixed progress bar ad…
Kosinkadink Nov 12, 2024
f2f9c90
Added support for HelloMeme AnimateDiff model loading via simple key …
Kosinkadink Nov 12, 2024
7ded0a7
version bump
Kosinkadink Nov 12, 2024
48db232
Added DinkLink scaffolding
Kosinkadink Nov 13, 2024
815eede
Make context_extras an optional param on Set Context Extras node
Kosinkadink Nov 14, 2024
4807978
Use DinkLink to get ACN wrapper for ContextRef and ControlNet convers…
Kosinkadink Nov 14, 2024
f64d674
Add proper parent reference to MotionModelPatcher.clone() to work pro…
Kosinkadink Nov 15, 2024
d70fd11
Modified comfy.hooks calls to match ComfyUI changes
Kosinkadink Nov 16, 2024
68ccced
Added support for hooks from CLIP to be applied to resulting conds to…
Kosinkadink Nov 16, 2024
844b4e4
Make diffusion_model_groupnormed hack use built-in diffusion_model wr…
Kosinkadink Nov 17, 2024
054418d
Replace apply_model_factory with special_model_apply_model_wrapper th…
Kosinkadink Nov 17, 2024
066bb23
Clean up perform_image_injection, as backwards compatible code no lon…
Kosinkadink Nov 17, 2024
d06a408
Adjusted spacing
Kosinkadink Nov 17, 2024
32a06f1
Match changes in ComfyUI PR that remove opt_ prefix on optional comfy…
Kosinkadink Nov 21, 2024
0a2d129
Refactored MotionModelPatcher into MotionModelAttachment so that no c…
Kosinkadink Nov 28, 2024
5ee8cf6
Pass transformer_options into VanillaTemporalModule and all subsequen…
Kosinkadink Nov 28, 2024
95cfd12
Generalized AnimateDiffModel initialization so mm_state_dict can be u…
Kosinkadink Nov 29, 2024
28b841f
Fixed special model features not being changed to use attachment from…
Kosinkadink Nov 29, 2024
a6c9400
Register AnimateDiffModel and AnimateDiffInfo on DinkLink
Kosinkadink Nov 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
from .animatediff.utils_model import get_available_motion_models, Folders
from .animatediff.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
from .animatediff import documentation
from .animatediff.dinklink import init_dinklink

if len(get_available_motion_models()) == 0:
logger.error(f"No motion models found. Please download one and place in: {folder_paths.get_folder_paths(Folders.ANIMATEDIFF_MODELS)}")

WEB_DIRECTORY = "./web"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
documentation.format_descriptions(NODE_CLASS_MAPPINGS)

init_dinklink()
40 changes: 40 additions & 0 deletions animatediff/adapter_fancyvideo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from torch import nn

import comfy.ops


FancyVideoKeys = [
'fps_embedding.linear.bias',
'fps_embedding.linear.weight',
'motion_embedding.linear.bias',
'motion_embedding.linear.weight',
'conv_in.bias',
'conv_in.weight',
]


def initialize_weights_to_zero(m):
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
nn.init.constant_(m.weight, 0)
if m.bias is not None:
nn.init.constant_(m.bias, 0)


class FancyVideoCondEmbedding(nn.Module):
def __init__(self, in_channels: int, cond_embed_dim: int, act_fn: str = "silu", ops=comfy.ops.disable_weight_init):
super().__init__()

self.linear = ops.Linear(in_channels, cond_embed_dim)
self.act = None
if act_fn == "silu":
self.act = nn.SiLU()
elif act_fn == "mish":
self.act = nn.Mish()

def forward(self, sample):
sample = self.linear(sample)

if self.act is not None:
sample = self.act(sample)

return sample
11 changes: 9 additions & 2 deletions animatediff/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,9 +604,14 @@ def draw_view(window: list[int], gd: GridDisplay):
draw_subidxs(window=window, gd=gd, y_grid_offset=2, color=gd.vs.view_color)


def generate_context_visualization(context_opts: ContextOptionsGroup, model: ModelPatcher, sampler_name: str=None, scheduler: str=None,
def generate_context_visualization(model: ModelPatcher, context_opts: ContextOptionsGroup=None, sampler_name: str=None, scheduler: str=None,
width=1440, height=200, video_length=32,
steps=None, start_step=None, end_step=None, sigmas=None, force_full_denoise=False, denoise=None):
if context_opts is None:
context_opts = ContextOptionsGroup.default()
params = model.get_attachment("ADE_params")
if params is not None:
context_opts = params.context_options
context_opts = context_opts.clone()
vs = VisualizeSettings(width, video_length)
all_imgs = []
Expand Down Expand Up @@ -642,7 +647,9 @@ def generate_context_visualization(context_opts: ContextOptionsGroup, model: Mod

# check if context should even be active in this case
context_active = True
if video_length < context_opts.context_length:
if context_opts.context_length is None:
context_active = False
elif video_length < context_opts.context_length:
context_active = False
elif video_length == context_opts.context_length and not context_opts.use_on_equal_length:
context_active = False
Expand Down
61 changes: 61 additions & 0 deletions animatediff/dinklink.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
####################################################################################################
# DinkLink is my method of sharing classes/functions between my nodes.
#
# My DinkLink-compatible nodes will inject comfy.hooks with a __DINKLINK attr
# that stores a dictionary, where any of my node packs can store their stuff.
#
# It is not intended to be accessed by node packs that I don't develop, so things may change
# at any time.
#
# DinkLink also serves as a proof-of-concept for a future ComfyUI implementation of
# purposely exposing node pack classes/functions with other node packs.
####################################################################################################
from __future__ import annotations
import comfy.hooks

from .motion_module_ad import AnimateDiffModel, AnimateDiffInfo

DINKLINK = "__DINKLINK"


def init_dinklink():
create_dinklink()
prepare_dinklink()

def create_dinklink():
if not hasattr(comfy.hooks, DINKLINK):
setattr(comfy.hooks, DINKLINK, {})

def get_dinklink() -> dict[str, dict[str]]:
create_dinklink()
return getattr(comfy.hooks, DINKLINK)


class DinkLinkConst:
VERSION = "version"
# ACN
ACN = "ACN"
ACN_CREATE_OUTER_SAMPLE_WRAPPER = "create_outer_sample_wrapper"
# ADE
ADE = "ADE"
ADE_ANIMATEDIFFMODEL = "AnimateDiffModel"
ADE_ANIMATEDIFFINFO = "AnimateDiffInfo"

def prepare_dinklink():
# expose classes
d = get_dinklink()
link_ade = d.setdefault(DinkLinkConst.ADE, {})
link_ade[DinkLinkConst.VERSION] = 10000
link_ade[DinkLinkConst.ADE_ANIMATEDIFFMODEL] = AnimateDiffModel
link_ade[DinkLinkConst.ADE_ANIMATEDIFFINFO] = AnimateDiffInfo

def get_acn_outer_sample_wrapper(throw_exception=True):
d = get_dinklink()
try:
link_acn = d[DinkLinkConst.ACN]
return link_acn[DinkLinkConst.ACN_CREATE_OUTER_SAMPLE_WRAPPER]
except KeyError:
if throw_exception:
raise Exception("Advanced-ControlNet nodes need to be installed to make use of ContextRef; " + \
"they are either not installed or are of an insufficient version.")
return None
4 changes: 3 additions & 1 deletion animatediff/freeinit.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class FreeInitFilter:
LIST = [GAUSSIAN, BUTTERWORTH, IDEAL, BOX]


def freq_mix_3d(x, noise, LPF):
def freq_mix_3d(x: torch.Tensor, noise: torch.Tensor, LPF: torch.Tensor):
"""
Noise reinitialization.

Expand All @@ -33,6 +33,8 @@ def freq_mix_3d(x, noise, LPF):
noise: randomly sampled noise
LPF: low pass filter
"""
noise = noise.to(dtype=x.dtype, device=x.device)
LPF = LPF.to(dtype=x.dtype, device=x.device)
# FFT
x_freq = fft.fftn(x, dim=(-4, -2, -1))
x_freq = fft.fftshift(x_freq, dim=(-4, -2, -1))
Expand Down
Loading