Merge pull request #7 from kijai/main

Some tweaks
This commit is contained in:
log(td)
2024-05-04 11:06:37 -06:00
committed by GitHub
9 changed files with 149 additions and 244 deletions
+4 -1
View File
@@ -3,6 +3,7 @@ from .nodes.load_instance_scaleu_node import LoadInstanceScaleUNode
from .nodes.load_instance_fusers_node import LoadInstanceFusersNode
from .nodes.load_instance_positionnet_node import LoadInstancePositionNetNode
from .nodes.instance_diffusion_tracking_prompt_node import InstanceDiffusionTrackingPromptNode
from .nodes.download_and_load_models import DownloadInstanceDiffusionModels
NODE_CLASS_MAPPINGS = {
@@ -11,6 +12,7 @@ NODE_CLASS_MAPPINGS = {
"LoadInstancePositionNetModel": LoadInstancePositionNetNode,
"LoadInstanceFusersNode": LoadInstanceFusersNode,
"InstanceDiffusionTrackingPrompt": InstanceDiffusionTrackingPromptNode,
"DownloadInstanceDiffusionModels": DownloadInstanceDiffusionModels
}
NODE_DISPLAY_NAME_MAPPINGS = {
@@ -18,5 +20,6 @@ NODE_DISPLAY_NAME_MAPPINGS = {
"LoadInstancePositionNetModel": "Load Instance PositionNet Model",
"LoadInstanceScaleUModel": "Load Instance ScaleU Model",
"LoadInstanceFusersNode": "Load Instance Fusers Model",
"InstanceDiffusionTrackingPrompt": "Instance Diffusion Tracking Prompt"
"InstanceDiffusionTrackingPrompt": "Instance Diffusion Tracking Prompt",
"DownloadInstanceDiffusionModels": "(Down)Load Instance Diffusion Models"
}
+7 -1
View File
@@ -1,7 +1,13 @@
import torch
from ..modules.attention import GatedSelfAttentionDense
#from ..modules.attention import GatedSelfAttentionDense
from comfy.gligen import GatedSelfAttentionDense as GSAD
class GatedSelfAttentionDense(GSAD):
def forward(self, x, instance_options={}):
objs = instance_options['objs']
x = super().forward(x, objs)
return x.to(torch.float16)
def prepare_fusers(fusers_ckpt) -> list[torch.nn.Module]:
fusers_list = []
+1 -1
View File
@@ -22,5 +22,5 @@ def get_positionnet_default_params():
def prepare_positionnet(checkpoint, params) -> torch.nn.Module:
model = UniFusion(**params)
model.load_state_dict(checkpoint)
model.load_state_dict(checkpoint, strict=False)
return model
-184
View File
@@ -1,184 +0,0 @@
import torch
import numpy as np
from torch import nn
from inspect import isfunction
import torch.nn.functional as F
from comfy.gligen import GatedSelfAttentionDense as GSAD
def exists(val):
return val is not None
def default(val, d):
if exists(val):
return val
return d() if isfunction(d) else d
# feedforward
class GEGLU(nn.Module):
def __init__(self, dim_in, dim_out):
super().__init__()
self.proj = nn.Linear(dim_in, dim_out * 2)
def forward(self, x):
x, gate = self.proj(x).chunk(2, dim=-1)
return x * F.gelu(gate)
class FeedForward(nn.Module):
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
super().__init__()
inner_dim = int(dim * mult)
dim_out = default(dim_out, dim)
project_in = nn.Sequential(
nn.Linear(dim, inner_dim),
nn.GELU()
) if not glu else GEGLU(dim, inner_dim)
self.net = nn.Sequential(
project_in,
nn.Dropout(dropout),
nn.Linear(inner_dim, dim_out)
)
def forward(self, x):
return self.net(x)
class SelfAttentionFusers(nn.Module):
def __init__(self, query_dim, heads=8, dim_head=64, dropout=0.):
super().__init__()
inner_dim = dim_head * heads
self.scale = dim_head ** -0.5
self.heads = heads
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
self.to_k = nn.Linear(query_dim, inner_dim, bias=False)
self.to_v = nn.Linear(query_dim, inner_dim, bias=False)
self.to_out = nn.Sequential(
nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
def forward(self, x, instance_options={}):
# TODO: use attention masking
grounding_input = instance_options.get('grounding_input', None)
drop_box_mask = instance_options.get('drop_box_mask', None)
q = self.to_q(x) # B*N*(H*C)
k = self.to_k(x) # B*N*(H*C)
v = self.to_v(x) # B*N*(H*C)
B, N, HC = q.shape
H = self.heads
C = HC // H
q = q.view(B, N, H, C).permute(
0, 2, 1, 3).reshape(B * H, N, C) # (B*H)*N*C
k = k.view(B, N, H, C).permute(
0, 2, 1, 3).reshape(B * H, N, C) # (B*H)*N*C
v = v.view(B, N, H, C).permute(
0, 2, 1, 3).reshape(B * H, N, C) # (B*H)*N*C
sim = torch.einsum('b i c, b j c -> b i j', q, k) * \
self.scale # (B*H)*N*N
if grounding_input is not None:
# att_masks: B*(n_objs*4)*sqrt(w_h)*sqrt(w_h)
n_objs = grounding_input["att_masks"].shape[1]
att_masks_reshape = None
# if N - n_objs * 4 == 64 * 64:
# att_masks_reshape = grounding_input["att_masks"]
# att_key = "att_masks_selfAtt64"
# if the mask is all zeros or box&mask are dropped, we do not need to mask the self-attention
if att_masks_reshape is not None and torch.sum(att_masks_reshape) > 0.0 and not drop_box_mask:
# the attention mask is shared across all blocks for more efficient forwarding
# we only need to get the mask for the first block.
if att_key in grounding_input:
att_masks_ = grounding_input[att_key]
else:
w_h = att_masks_reshape.shape[2] * \
att_masks_reshape.shape[3]
att_masks_ = torch.ones(B, 1, N, N).type(
att_masks_reshape.dtype).to(att_masks_reshape.device)
# mask the self-attention between visual tokens
# all object patches do not exchange information with each other
# but object patches share information with all background regions
att_masks_reshape_v = att_masks_reshape.view(
B * n_objs, w_h, 1)
# get the self-attention between att_masks_reshape with batch matrix multiplication
# 1. att_masks_reshape_v: (B*n_objs)*w_h*1
# 2. att_masks_reshape_v.permute(0,1,3,2): (B*n_objs)*1*w_h
# 3. torch.bmm(att_masks_reshape_v, att_masks_reshape_v.permute(0,2,1)): (B*n_objs)*w_h*w_h
self_att_all = torch.bmm(
att_masks_reshape_v, att_masks_reshape_v.permute(0, 2, 1))
# sum the values alone the n_objs dimension
# 1. self_att_all: B*n_objs*w_h*w_h
# 2. self_att_all.sum(dim=1): B*w_h*w_h
self_att_ind_objs = self_att_all.view(
B, n_objs, w_h, w_h).sum(dim=1)
# sum att_masks_reshape alone the n_objs dimension and measure the self-attention with batch matrix multiplication
# 1. att_masks_reshape_all: B*n_objs*w_h*1
# 2. att_masks_reshape_all.sum(dim=1): B*w_h*1
# 3. set non-zero values to 1: B*w_h*1
# 4. use batch matrix multiplication to measure the self-attention: B*w_h*w_h
att_masks_reshape_all = att_masks_reshape_v.view(
B, n_objs, w_h, 1).sum(dim=1)
att_masks_reshape_all[att_masks_reshape_all >= 1.0] = 1.0
self_att_all_objs = torch.bmm(
att_masks_reshape_all, att_masks_reshape_all.permute(0, 2, 1))
# get the masks for avoiding information leakage between object patches
visual_token_masks = self_att_all_objs + self_att_ind_objs
# avoid the communications between objects and background
# objects-background can not communicate
visual_token_masks[self_att_ind_objs < 1.0] = 0.0
visual_token_masks[self_att_ind_objs >=
1.0] = 1.0 # binay mask
att_masks_[:, :, :w_h, :w_h] = visual_token_masks.view(
B, 1, w_h, w_h)
# mask the self-attention between grounded tokens and the visual tokens
att_masks_reshape = att_masks_reshape.view(
B, 1, n_objs, w_h)
# the order of inputs are [box, point, scribble, mask]. only box and mask need to have masked self-attention
att_masks_[:, :, w_h:, :w_h] = att_masks_reshape.repeat(
1, 1, 4, 1)
att_masks_[:, :, w_h + n_objs:w_h + n_objs * 3, :w_h] = 1
att_masks_[:, :, :w_h, w_h:] = att_masks_reshape.permute(
0, 1, 3, 2).repeat(1, 1, 1, 4)
att_masks_[:, :, :w_h, w_h + n_objs:w_h + n_objs * 3] = 1
# add 1e-9 along the diagonal to avoid nan
diagonal_epsilon = torch.eye(N).view(1, 1, N, N).type(
att_masks_.dtype).to(att_masks_.device) * 1e-9
att_masks_ = att_masks_ + diagonal_epsilon
# save the masks for later blocks
grounding_input['next_att_mask'] = att_masks_
# the larger the threshold is, the smaller area the grounded info can influence
# if threshold = 1.01, all grounded info has no influence on the rest of the patches.
sim = sim.view(B, H, N, N).masked_fill(
att_masks_ <= 0.0, -np.inf).view(B * H, N, N) # -np.inf
attn = sim.softmax(dim=-1) # (B*H)*N*N
out = torch.einsum('b i j, b j c -> b i c', attn, v) # (B*H)*N*C
out = out.view(B, H, N, C).permute(
0, 2, 1, 3).reshape(B, N, (H * C)) # B*N*(H*C)
return self.to_out(out)
class GatedSelfAttentionDense(GSAD):
def forward(self, x, instance_options={}):
objs = instance_options['objs']
x = super().forward(x, objs)
return x.to(torch.float16)
+48 -46
View File
@@ -12,6 +12,8 @@ import torch.nn.functional as F
from timm.models.layers import trunc_normal_, DropPath
from timm.models.registry import register_model
import comfy.ops
ops = comfy.ops.manual_cast
class Block(nn.Module):
r""" ConvNeXt Block. There are two equivalent implementations:
@@ -27,13 +29,13 @@ class Block(nn.Module):
def __init__(self, dim, drop_path=0., layer_scale_init_value=1e-6):
super().__init__()
self.dwconv = nn.Conv2d(dim, dim, kernel_size=7,
self.dwconv = ops.Conv2d(dim, dim, kernel_size=7,
padding=3, groups=dim) # depthwise conv
self.norm = LayerNorm(dim, eps=1e-6)
# pointwise/1x1 convs, implemented with linear layers
self.pwconv1 = nn.Linear(dim, 4 * dim)
self.pwconv1 = ops.Linear(dim, 4 * dim)
self.act = nn.GELU()
self.pwconv2 = nn.Linear(4 * dim, dim)
self.pwconv2 = ops.Linear(4 * dim, dim)
self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)),
requires_grad=True) if layer_scale_init_value > 0 else None
self.drop_path = DropPath(
@@ -79,14 +81,14 @@ class ConvNeXt(nn.Module):
# stem and 3 intermediate downsampling conv layers
self.downsample_layers = nn.ModuleList()
stem = nn.Sequential(
nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
ops.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
LayerNorm(dims[0], eps=1e-6, data_format="channels_first")
)
self.downsample_layers.append(stem)
for i in range(3):
downsample_layer = nn.Sequential(
LayerNorm(dims[i], eps=1e-6, data_format="channels_first"),
nn.Conv2d(dims[i], dims[i + 1], kernel_size=2, stride=2),
ops.Conv2d(dims[i], dims[i + 1], kernel_size=2, stride=2),
)
self.downsample_layers.append(downsample_layer)
@@ -104,7 +106,7 @@ class ConvNeXt(nn.Module):
cur += depths[i]
def _init_weights(self, m):
if isinstance(m, (nn.Conv2d, nn.Linear)):
if isinstance(m, (ops.Conv2d, ops.Linear)):
trunc_normal_(m.weight, std=.02)
nn.init.constant_(m.bias, 0)
@@ -173,49 +175,49 @@ def convnext_tiny(pretrained=False, in_22k=False, **kwargs):
return model
@register_model
def convnext_small(pretrained=False, in_22k=False, **kwargs):
model = ConvNeXt(depths=[3, 3, 27, 3], dims=[96, 192, 384, 768], **kwargs)
if pretrained:
url = model_urls['convnext_small_22k'] if in_22k else model_urls['convnext_small_1k']
checkpoint = torch.hub.load_state_dict_from_url(
url=url, map_location="cpu")
model.load_state_dict(checkpoint["model"])
return model
# @register_model
# def convnext_small(pretrained=False, in_22k=False, **kwargs):
# model = ConvNeXt(depths=[3, 3, 27, 3], dims=[96, 192, 384, 768], **kwargs)
# if pretrained:
# url = model_urls['convnext_small_22k'] if in_22k else model_urls['convnext_small_1k']
# checkpoint = torch.hub.load_state_dict_from_url(
# url=url, map_location="cpu")
# model.load_state_dict(checkpoint["model"])
# return model
@register_model
def convnext_base(pretrained=False, in_22k=False, **kwargs):
model = ConvNeXt(depths=[3, 3, 27, 3], dims=[
128, 256, 512, 1024], **kwargs)
if pretrained:
url = model_urls['convnext_base_22k'] if in_22k else model_urls['convnext_base_1k']
checkpoint = torch.hub.load_state_dict_from_url(
url=url, map_location="cpu")
model.load_state_dict(checkpoint["model"])
return model
# @register_model
# def convnext_base(pretrained=False, in_22k=False, **kwargs):
# model = ConvNeXt(depths=[3, 3, 27, 3], dims=[
# 128, 256, 512, 1024], **kwargs)
# if pretrained:
# url = model_urls['convnext_base_22k'] if in_22k else model_urls['convnext_base_1k']
# checkpoint = torch.hub.load_state_dict_from_url(
# url=url, map_location="cpu")
# model.load_state_dict(checkpoint["model"])
# return model
@register_model
def convnext_large(pretrained=False, in_22k=False, **kwargs):
model = ConvNeXt(depths=[3, 3, 27, 3], dims=[
192, 384, 768, 1536], **kwargs)
if pretrained:
url = model_urls['convnext_large_22k'] if in_22k else model_urls['convnext_large_1k']
checkpoint = torch.hub.load_state_dict_from_url(
url=url, map_location="cpu")
model.load_state_dict(checkpoint["model"])
return model
# @register_model
# def convnext_large(pretrained=False, in_22k=False, **kwargs):
# model = ConvNeXt(depths=[3, 3, 27, 3], dims=[
# 192, 384, 768, 1536], **kwargs)
# if pretrained:
# url = model_urls['convnext_large_22k'] if in_22k else model_urls['convnext_large_1k']
# checkpoint = torch.hub.load_state_dict_from_url(
# url=url, map_location="cpu")
# model.load_state_dict(checkpoint["model"])
# return model
@register_model
def convnext_xlarge(pretrained=False, in_22k=False, **kwargs):
model = ConvNeXt(depths=[3, 3, 27, 3], dims=[
256, 512, 1024, 2048], **kwargs)
if pretrained:
assert in_22k, "only ImageNet-22K pre-trained ConvNeXt-XL is available; please set in_22k=True"
url = model_urls['convnext_xlarge_22k']
checkpoint = torch.hub.load_state_dict_from_url(
url=url, map_location="cpu")
model.load_state_dict(checkpoint["model"])
return model
# @register_model
# def convnext_xlarge(pretrained=False, in_22k=False, **kwargs):
# model = ConvNeXt(depths=[3, 3, 27, 3], dims=[
# 256, 512, 1024, 2048], **kwargs)
# if pretrained:
# assert in_22k, "only ImageNet-22K pre-trained ConvNeXt-XL is available; please set in_22k=True"
# url = model_urls['convnext_xlarge_22k']
# checkpoint = torch.hub.load_state_dict_from_url(
# url=url, map_location="cpu")
# model.load_state_dict(checkpoint["model"])
# return model
+12 -9
View File
@@ -3,12 +3,14 @@ import torch.nn as nn
from .util import FourierEmbedder
from .convnext import convnext_tiny
import comfy.ops
ops = comfy.ops.manual_cast
class UniFusion(nn.Module):
def __init__(self, in_dim, out_dim, mid_dim=3072, fourier_freqs=8,
train_add_boxes=True, train_add_points=True, train_add_scribbles=True, train_add_masks=True,
test_drop_boxes=False, test_drop_points=False, test_drop_scribbles=True, test_drop_masks=False,
use_seperate_tokenizer=True):
use_seperate_tokenizer=True, use_segs=True):
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
@@ -26,14 +28,15 @@ class UniFusion(nn.Module):
self.use_seperate_tokenizer = use_seperate_tokenizer
# Use instance masks as additional model inputs for mask conditioned image generation
self.use_segs = True if self.add_masks else False
#self.use_segs = True if self.add_masks else False
self.use_segs = use_segs
if self.use_segs:
in_dim = 30
self.resize_input = 512
self.down_factor = 64 # determined by the convnext backbone
# from num_sem to 3 channels
self.in_conv = nn.Conv2d(in_dim, 3, 3, 1, 1)
self.in_conv = ops.Conv2d(in_dim, 3, 3, 1, 1)
self.convnext_tiny_backbone = convnext_tiny(pretrained=True)
self.num_tokens = (self.resize_input // self.down_factor) ** 2
self.convnext_feature_dim = 3072
@@ -79,19 +82,19 @@ class UniFusion(nn.Module):
for idx, input_dim_ in enumerate(input_dim_list):
mid_dim = self.mid_dim
self.linears_list.append(nn.Sequential(
nn.Linear(input_dim_, mid_dim),
ops.Linear(input_dim_, mid_dim),
nn.SiLU(),
nn.Linear(mid_dim, mid_dim),
ops.Linear(mid_dim, mid_dim),
nn.SiLU(),
nn.Linear(mid_dim, out_dim),
ops.Linear(mid_dim, out_dim),
))
else:
self.linears = nn.Sequential(
nn.Linear(input_dim, self.mid_dim),
ops.Linear(input_dim, self.mid_dim),
nn.SiLU(),
nn.Linear(self.mid_dim, self.mid_dim),
ops.Linear(self.mid_dim, self.mid_dim),
nn.SiLU(),
nn.Linear(self.mid_dim, out_dim),
ops.Linear(self.mid_dim, out_dim),
)
self.null_positive_feature = torch.nn.Parameter(
+72
View File
@@ -0,0 +1,72 @@
import os
import folder_paths
import comfy.utils
from .. import constants as constants
from ..model_helpers.prepare_positionnet import prepare_positionnet, get_positionnet_default_params
from ..model_helpers.prepare_scaleu import prepare_scaleu_nets
from ..model_helpers.prepare_fusers import prepare_fusers
from huggingface_hub import snapshot_download
INSTANCE_FUSERS_DIR = "fuser_models"
INSTANCE_SCALEU_DIR = "scaleu_models"
class DownloadInstanceDiffusionModels:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"use_segs": ("BOOLEAN", {"default": True}),
}}
RETURN_TYPES = ("POSITIONNET", "FUSERS", "SCALEU", )
FUNCTION = "load_model"
CATEGORY = "instance/loaders"
def load_model(self, use_segs: bool):
repo_id = "logtd/instance_diffusion"
instance_models_folder = os.path.join(folder_paths.models_dir, constants.INSTANCE_MODELS_DIR)
models_to_download = [
("position_net", constants.INSTANCE_POSITIONNET_DIR, "position_net.ckpt"),
("fusers", constants.INSTANCE_FUSERS_DIR, "fusers.ckpt"),
("scaleu", constants.INSTANCE_SCALEU_DIR, "scaleu.ckpt")
]
for model_name, model_folder, model_file in models_to_download:
model_folder_path = os.path.join(instance_models_folder, model_folder)
model_file_path = os.path.join(model_folder_path, model_file)
if not os.path.exists(model_file_path):
print(f"Selected model: {model_file_path} not found, downloading...")
allow_patterns = [f"*{model_name}*"]
snapshot_download(repo_id=repo_id,
allow_patterns=allow_patterns,
local_dir=model_folder_path,
local_dir_use_symlinks=False
)
positionnet_file = os.path.join(instance_models_folder, constants.INSTANCE_POSITIONNET_DIR, "position_net.ckpt")
fusers_file = os.path.join(instance_models_folder, constants.INSTANCE_FUSERS_DIR, "fusers.ckpt")
scaleu_file = os.path.join(instance_models_folder, constants.INSTANCE_SCALEU_DIR, "scaleu.ckpt")
pos_checkpoint = comfy.utils.load_torch_file(positionnet_file, safe_load=True)
params = get_positionnet_default_params()
params["use_segs"] = use_segs
model = prepare_positionnet(pos_checkpoint, params)
positionnet = {
'model': model,
}
fusers_checkpoint = comfy.utils.load_torch_file(fusers_file, safe_load=True)
fusers_list = prepare_fusers(fusers_checkpoint)
fusers = {
'model_list': fusers_list
}
scaleu_checkpoint = comfy.utils.load_torch_file(scaleu_file, safe_load=True)
scaleu_list = prepare_scaleu_nets(scaleu_checkpoint)
scaleu = {
'model_list': scaleu_list
}
return (positionnet, fusers, scaleu)
+4 -2
View File
@@ -8,17 +8,19 @@ class LoadInstancePositionNetNode:
def INPUT_TYPES(s):
return {"required": {
"model_filename": (get_model_list(constants.INSTANCE_POSITIONNET_DIR),),
"use_segs": ("BOOLEAN", {"default": True}),
}}
RETURN_TYPES = ("POSITIONNET",)
RETURN_TYPES = ("POSITIONNET", "FUSERS", "SCALEU",)
FUNCTION = "load_model"
CATEGORY = "instance/loaders"
def load_model(self, model_filename: str):
def load_model(self, model_filename: str, use_segs: bool):
checkpoint = load_checkpoint(
constants.INSTANCE_POSITIONNET_DIR, model_filename)
params = get_positionnet_default_params()
params["use_segs"] = use_segs
model = prepare_positionnet(checkpoint, params)
positionnet = {
'model': model,
+1
View File
@@ -0,0 +1 @@
huggingface_hub