Delete comfy
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- comfy/checkpoint_pickle.py +0 -13
- comfy/cldm/cldm.py +0 -433
- comfy/cldm/control_types.py +0 -10
- comfy/cldm/dit_embedder.py +0 -120
- comfy/cldm/mmdit.py +0 -81
- comfy/cli_args.py +0 -236
- comfy/clip_config_bigg.json +0 -23
- comfy/clip_model.py +0 -244
- comfy/clip_vision.py +0 -148
- comfy/clip_vision_config_g.json +0 -18
- comfy/clip_vision_config_h.json +0 -18
- comfy/clip_vision_config_vitl.json +0 -18
- comfy/clip_vision_config_vitl_336.json +0 -18
- comfy/clip_vision_config_vitl_336_llava.json +0 -19
- comfy/clip_vision_siglip_384.json +0 -13
- comfy/clip_vision_siglip_512.json +0 -13
- comfy/comfy_types/README.md +0 -43
- comfy/comfy_types/__init__.py +0 -46
- comfy/comfy_types/examples/example_nodes.py +0 -28
- comfy/comfy_types/examples/input_options.png +0 -3
- comfy/comfy_types/examples/input_types.png +0 -3
- comfy/comfy_types/examples/required_hint.png +0 -3
- comfy/comfy_types/node_typing.py +0 -350
- comfy/conds.py +0 -130
- comfy/controlnet.py +0 -858
- comfy/diffusers_convert.py +0 -189
- comfy/diffusers_load.py +0 -36
- comfy/extra_samplers/uni_pc.py +0 -873
- comfy/float.py +0 -67
- comfy/gligen.py +0 -299
- comfy/hooks.py +0 -785
- comfy/image_encoders/dino2.py +0 -141
- comfy/image_encoders/dino2_giant.json +0 -21
- comfy/k_diffusion/deis.py +0 -120
- comfy/k_diffusion/sa_solver.py +0 -121
- comfy/k_diffusion/sampling.py +0 -1761
- comfy/k_diffusion/utils.py +0 -313
- comfy/latent_formats.py +0 -472
- comfy/ldm/ace/attention.py +0 -761
- comfy/ldm/ace/lyric_encoder.py +0 -1067
- comfy/ldm/ace/model.py +0 -385
- comfy/ldm/ace/vae/autoencoder_dc.py +0 -644
- comfy/ldm/ace/vae/music_dcae_pipeline.py +0 -109
- comfy/ldm/ace/vae/music_log_mel.py +0 -113
- comfy/ldm/ace/vae/music_vocoder.py +0 -538
- comfy/ldm/audio/autoencoder.py +0 -276
- comfy/ldm/audio/dit.py +0 -896
- comfy/ldm/audio/embedders.py +0 -108
- comfy/ldm/aura/mmdit.py +0 -498
- comfy/ldm/cascade/common.py +0 -154
comfy/checkpoint_pickle.py
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
import pickle
|
| 2 |
-
|
| 3 |
-
load = pickle.load
|
| 4 |
-
|
| 5 |
-
class Empty:
|
| 6 |
-
pass
|
| 7 |
-
|
| 8 |
-
class Unpickler(pickle.Unpickler):
|
| 9 |
-
def find_class(self, module, name):
|
| 10 |
-
#TODO: safe unpickle
|
| 11 |
-
if module.startswith("pytorch_lightning"):
|
| 12 |
-
return Empty
|
| 13 |
-
return super().find_class(module, name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/cldm/cldm.py
DELETED
|
@@ -1,433 +0,0 @@
|
|
| 1 |
-
#taken from: https://github.com/lllyasviel/ControlNet
|
| 2 |
-
#and modified
|
| 3 |
-
|
| 4 |
-
import torch
|
| 5 |
-
import torch.nn as nn
|
| 6 |
-
|
| 7 |
-
from ..ldm.modules.diffusionmodules.util import (
|
| 8 |
-
timestep_embedding,
|
| 9 |
-
)
|
| 10 |
-
|
| 11 |
-
from ..ldm.modules.attention import SpatialTransformer
|
| 12 |
-
from ..ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample
|
| 13 |
-
from ..ldm.util import exists
|
| 14 |
-
from .control_types import UNION_CONTROLNET_TYPES
|
| 15 |
-
from collections import OrderedDict
|
| 16 |
-
import comfy.ops
|
| 17 |
-
from comfy.ldm.modules.attention import optimized_attention
|
| 18 |
-
|
| 19 |
-
class OptimizedAttention(nn.Module):
|
| 20 |
-
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
|
| 21 |
-
super().__init__()
|
| 22 |
-
self.heads = nhead
|
| 23 |
-
self.c = c
|
| 24 |
-
|
| 25 |
-
self.in_proj = operations.Linear(c, c * 3, bias=True, dtype=dtype, device=device)
|
| 26 |
-
self.out_proj = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
|
| 27 |
-
|
| 28 |
-
def forward(self, x):
|
| 29 |
-
x = self.in_proj(x)
|
| 30 |
-
q, k, v = x.split(self.c, dim=2)
|
| 31 |
-
out = optimized_attention(q, k, v, self.heads)
|
| 32 |
-
return self.out_proj(out)
|
| 33 |
-
|
| 34 |
-
class QuickGELU(nn.Module):
|
| 35 |
-
def forward(self, x: torch.Tensor):
|
| 36 |
-
return x * torch.sigmoid(1.702 * x)
|
| 37 |
-
|
| 38 |
-
class ResBlockUnionControlnet(nn.Module):
|
| 39 |
-
def __init__(self, dim, nhead, dtype=None, device=None, operations=None):
|
| 40 |
-
super().__init__()
|
| 41 |
-
self.attn = OptimizedAttention(dim, nhead, dtype=dtype, device=device, operations=operations)
|
| 42 |
-
self.ln_1 = operations.LayerNorm(dim, dtype=dtype, device=device)
|
| 43 |
-
self.mlp = nn.Sequential(
|
| 44 |
-
OrderedDict([("c_fc", operations.Linear(dim, dim * 4, dtype=dtype, device=device)), ("gelu", QuickGELU()),
|
| 45 |
-
("c_proj", operations.Linear(dim * 4, dim, dtype=dtype, device=device))]))
|
| 46 |
-
self.ln_2 = operations.LayerNorm(dim, dtype=dtype, device=device)
|
| 47 |
-
|
| 48 |
-
def attention(self, x: torch.Tensor):
|
| 49 |
-
return self.attn(x)
|
| 50 |
-
|
| 51 |
-
def forward(self, x: torch.Tensor):
|
| 52 |
-
x = x + self.attention(self.ln_1(x))
|
| 53 |
-
x = x + self.mlp(self.ln_2(x))
|
| 54 |
-
return x
|
| 55 |
-
|
| 56 |
-
class ControlledUnetModel(UNetModel):
|
| 57 |
-
#implemented in the ldm unet
|
| 58 |
-
pass
|
| 59 |
-
|
| 60 |
-
class ControlNet(nn.Module):
|
| 61 |
-
def __init__(
|
| 62 |
-
self,
|
| 63 |
-
image_size,
|
| 64 |
-
in_channels,
|
| 65 |
-
model_channels,
|
| 66 |
-
hint_channels,
|
| 67 |
-
num_res_blocks,
|
| 68 |
-
dropout=0,
|
| 69 |
-
channel_mult=(1, 2, 4, 8),
|
| 70 |
-
conv_resample=True,
|
| 71 |
-
dims=2,
|
| 72 |
-
num_classes=None,
|
| 73 |
-
use_checkpoint=False,
|
| 74 |
-
dtype=torch.float32,
|
| 75 |
-
num_heads=-1,
|
| 76 |
-
num_head_channels=-1,
|
| 77 |
-
num_heads_upsample=-1,
|
| 78 |
-
use_scale_shift_norm=False,
|
| 79 |
-
resblock_updown=False,
|
| 80 |
-
use_new_attention_order=False,
|
| 81 |
-
use_spatial_transformer=False, # custom transformer support
|
| 82 |
-
transformer_depth=1, # custom transformer support
|
| 83 |
-
context_dim=None, # custom transformer support
|
| 84 |
-
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
|
| 85 |
-
legacy=True,
|
| 86 |
-
disable_self_attentions=None,
|
| 87 |
-
num_attention_blocks=None,
|
| 88 |
-
disable_middle_self_attn=False,
|
| 89 |
-
use_linear_in_transformer=False,
|
| 90 |
-
adm_in_channels=None,
|
| 91 |
-
transformer_depth_middle=None,
|
| 92 |
-
transformer_depth_output=None,
|
| 93 |
-
attn_precision=None,
|
| 94 |
-
union_controlnet_num_control_type=None,
|
| 95 |
-
device=None,
|
| 96 |
-
operations=comfy.ops.disable_weight_init,
|
| 97 |
-
**kwargs,
|
| 98 |
-
):
|
| 99 |
-
super().__init__()
|
| 100 |
-
assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
|
| 101 |
-
if use_spatial_transformer:
|
| 102 |
-
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
| 103 |
-
|
| 104 |
-
if context_dim is not None:
|
| 105 |
-
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
| 106 |
-
# from omegaconf.listconfig import ListConfig
|
| 107 |
-
# if type(context_dim) == ListConfig:
|
| 108 |
-
# context_dim = list(context_dim)
|
| 109 |
-
|
| 110 |
-
if num_heads_upsample == -1:
|
| 111 |
-
num_heads_upsample = num_heads
|
| 112 |
-
|
| 113 |
-
if num_heads == -1:
|
| 114 |
-
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
| 115 |
-
|
| 116 |
-
if num_head_channels == -1:
|
| 117 |
-
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
| 118 |
-
|
| 119 |
-
self.dims = dims
|
| 120 |
-
self.image_size = image_size
|
| 121 |
-
self.in_channels = in_channels
|
| 122 |
-
self.model_channels = model_channels
|
| 123 |
-
|
| 124 |
-
if isinstance(num_res_blocks, int):
|
| 125 |
-
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
| 126 |
-
else:
|
| 127 |
-
if len(num_res_blocks) != len(channel_mult):
|
| 128 |
-
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
| 129 |
-
"as a list/tuple (per-level) with the same length as channel_mult")
|
| 130 |
-
self.num_res_blocks = num_res_blocks
|
| 131 |
-
|
| 132 |
-
if disable_self_attentions is not None:
|
| 133 |
-
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
| 134 |
-
assert len(disable_self_attentions) == len(channel_mult)
|
| 135 |
-
if num_attention_blocks is not None:
|
| 136 |
-
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
| 137 |
-
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
| 138 |
-
|
| 139 |
-
transformer_depth = transformer_depth[:]
|
| 140 |
-
|
| 141 |
-
self.dropout = dropout
|
| 142 |
-
self.channel_mult = channel_mult
|
| 143 |
-
self.conv_resample = conv_resample
|
| 144 |
-
self.num_classes = num_classes
|
| 145 |
-
self.use_checkpoint = use_checkpoint
|
| 146 |
-
self.dtype = dtype
|
| 147 |
-
self.num_heads = num_heads
|
| 148 |
-
self.num_head_channels = num_head_channels
|
| 149 |
-
self.num_heads_upsample = num_heads_upsample
|
| 150 |
-
self.predict_codebook_ids = n_embed is not None
|
| 151 |
-
|
| 152 |
-
time_embed_dim = model_channels * 4
|
| 153 |
-
self.time_embed = nn.Sequential(
|
| 154 |
-
operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
|
| 155 |
-
nn.SiLU(),
|
| 156 |
-
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
if self.num_classes is not None:
|
| 160 |
-
if isinstance(self.num_classes, int):
|
| 161 |
-
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
| 162 |
-
elif self.num_classes == "continuous":
|
| 163 |
-
self.label_emb = nn.Linear(1, time_embed_dim)
|
| 164 |
-
elif self.num_classes == "sequential":
|
| 165 |
-
assert adm_in_channels is not None
|
| 166 |
-
self.label_emb = nn.Sequential(
|
| 167 |
-
nn.Sequential(
|
| 168 |
-
operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
|
| 169 |
-
nn.SiLU(),
|
| 170 |
-
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
| 171 |
-
)
|
| 172 |
-
)
|
| 173 |
-
else:
|
| 174 |
-
raise ValueError()
|
| 175 |
-
|
| 176 |
-
self.input_blocks = nn.ModuleList(
|
| 177 |
-
[
|
| 178 |
-
TimestepEmbedSequential(
|
| 179 |
-
operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
|
| 180 |
-
)
|
| 181 |
-
]
|
| 182 |
-
)
|
| 183 |
-
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations, dtype=self.dtype, device=device)])
|
| 184 |
-
|
| 185 |
-
self.input_hint_block = TimestepEmbedSequential(
|
| 186 |
-
operations.conv_nd(dims, hint_channels, 16, 3, padding=1, dtype=self.dtype, device=device),
|
| 187 |
-
nn.SiLU(),
|
| 188 |
-
operations.conv_nd(dims, 16, 16, 3, padding=1, dtype=self.dtype, device=device),
|
| 189 |
-
nn.SiLU(),
|
| 190 |
-
operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
| 191 |
-
nn.SiLU(),
|
| 192 |
-
operations.conv_nd(dims, 32, 32, 3, padding=1, dtype=self.dtype, device=device),
|
| 193 |
-
nn.SiLU(),
|
| 194 |
-
operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
| 195 |
-
nn.SiLU(),
|
| 196 |
-
operations.conv_nd(dims, 96, 96, 3, padding=1, dtype=self.dtype, device=device),
|
| 197 |
-
nn.SiLU(),
|
| 198 |
-
operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
| 199 |
-
nn.SiLU(),
|
| 200 |
-
operations.conv_nd(dims, 256, model_channels, 3, padding=1, dtype=self.dtype, device=device)
|
| 201 |
-
)
|
| 202 |
-
|
| 203 |
-
self._feature_size = model_channels
|
| 204 |
-
input_block_chans = [model_channels]
|
| 205 |
-
ch = model_channels
|
| 206 |
-
ds = 1
|
| 207 |
-
for level, mult in enumerate(channel_mult):
|
| 208 |
-
for nr in range(self.num_res_blocks[level]):
|
| 209 |
-
layers = [
|
| 210 |
-
ResBlock(
|
| 211 |
-
ch,
|
| 212 |
-
time_embed_dim,
|
| 213 |
-
dropout,
|
| 214 |
-
out_channels=mult * model_channels,
|
| 215 |
-
dims=dims,
|
| 216 |
-
use_checkpoint=use_checkpoint,
|
| 217 |
-
use_scale_shift_norm=use_scale_shift_norm,
|
| 218 |
-
dtype=self.dtype,
|
| 219 |
-
device=device,
|
| 220 |
-
operations=operations,
|
| 221 |
-
)
|
| 222 |
-
]
|
| 223 |
-
ch = mult * model_channels
|
| 224 |
-
num_transformers = transformer_depth.pop(0)
|
| 225 |
-
if num_transformers > 0:
|
| 226 |
-
if num_head_channels == -1:
|
| 227 |
-
dim_head = ch // num_heads
|
| 228 |
-
else:
|
| 229 |
-
num_heads = ch // num_head_channels
|
| 230 |
-
dim_head = num_head_channels
|
| 231 |
-
if legacy:
|
| 232 |
-
#num_heads = 1
|
| 233 |
-
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
| 234 |
-
if exists(disable_self_attentions):
|
| 235 |
-
disabled_sa = disable_self_attentions[level]
|
| 236 |
-
else:
|
| 237 |
-
disabled_sa = False
|
| 238 |
-
|
| 239 |
-
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
| 240 |
-
layers.append(
|
| 241 |
-
SpatialTransformer(
|
| 242 |
-
ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
|
| 243 |
-
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
| 244 |
-
use_checkpoint=use_checkpoint, attn_precision=attn_precision, dtype=self.dtype, device=device, operations=operations
|
| 245 |
-
)
|
| 246 |
-
)
|
| 247 |
-
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
| 248 |
-
self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
|
| 249 |
-
self._feature_size += ch
|
| 250 |
-
input_block_chans.append(ch)
|
| 251 |
-
if level != len(channel_mult) - 1:
|
| 252 |
-
out_ch = ch
|
| 253 |
-
self.input_blocks.append(
|
| 254 |
-
TimestepEmbedSequential(
|
| 255 |
-
ResBlock(
|
| 256 |
-
ch,
|
| 257 |
-
time_embed_dim,
|
| 258 |
-
dropout,
|
| 259 |
-
out_channels=out_ch,
|
| 260 |
-
dims=dims,
|
| 261 |
-
use_checkpoint=use_checkpoint,
|
| 262 |
-
use_scale_shift_norm=use_scale_shift_norm,
|
| 263 |
-
down=True,
|
| 264 |
-
dtype=self.dtype,
|
| 265 |
-
device=device,
|
| 266 |
-
operations=operations
|
| 267 |
-
)
|
| 268 |
-
if resblock_updown
|
| 269 |
-
else Downsample(
|
| 270 |
-
ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
|
| 271 |
-
)
|
| 272 |
-
)
|
| 273 |
-
)
|
| 274 |
-
ch = out_ch
|
| 275 |
-
input_block_chans.append(ch)
|
| 276 |
-
self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
|
| 277 |
-
ds *= 2
|
| 278 |
-
self._feature_size += ch
|
| 279 |
-
|
| 280 |
-
if num_head_channels == -1:
|
| 281 |
-
dim_head = ch // num_heads
|
| 282 |
-
else:
|
| 283 |
-
num_heads = ch // num_head_channels
|
| 284 |
-
dim_head = num_head_channels
|
| 285 |
-
if legacy:
|
| 286 |
-
#num_heads = 1
|
| 287 |
-
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
| 288 |
-
mid_block = [
|
| 289 |
-
ResBlock(
|
| 290 |
-
ch,
|
| 291 |
-
time_embed_dim,
|
| 292 |
-
dropout,
|
| 293 |
-
dims=dims,
|
| 294 |
-
use_checkpoint=use_checkpoint,
|
| 295 |
-
use_scale_shift_norm=use_scale_shift_norm,
|
| 296 |
-
dtype=self.dtype,
|
| 297 |
-
device=device,
|
| 298 |
-
operations=operations
|
| 299 |
-
)]
|
| 300 |
-
if transformer_depth_middle >= 0:
|
| 301 |
-
mid_block += [SpatialTransformer( # always uses a self-attn
|
| 302 |
-
ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
|
| 303 |
-
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
| 304 |
-
use_checkpoint=use_checkpoint, attn_precision=attn_precision, dtype=self.dtype, device=device, operations=operations
|
| 305 |
-
),
|
| 306 |
-
ResBlock(
|
| 307 |
-
ch,
|
| 308 |
-
time_embed_dim,
|
| 309 |
-
dropout,
|
| 310 |
-
dims=dims,
|
| 311 |
-
use_checkpoint=use_checkpoint,
|
| 312 |
-
use_scale_shift_norm=use_scale_shift_norm,
|
| 313 |
-
dtype=self.dtype,
|
| 314 |
-
device=device,
|
| 315 |
-
operations=operations
|
| 316 |
-
)]
|
| 317 |
-
self.middle_block = TimestepEmbedSequential(*mid_block)
|
| 318 |
-
self.middle_block_out = self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device)
|
| 319 |
-
self._feature_size += ch
|
| 320 |
-
|
| 321 |
-
if union_controlnet_num_control_type is not None:
|
| 322 |
-
self.num_control_type = union_controlnet_num_control_type
|
| 323 |
-
num_trans_channel = 320
|
| 324 |
-
num_trans_head = 8
|
| 325 |
-
num_trans_layer = 1
|
| 326 |
-
num_proj_channel = 320
|
| 327 |
-
# task_scale_factor = num_trans_channel ** 0.5
|
| 328 |
-
self.task_embedding = nn.Parameter(torch.empty(self.num_control_type, num_trans_channel, dtype=self.dtype, device=device))
|
| 329 |
-
|
| 330 |
-
self.transformer_layes = nn.Sequential(*[ResBlockUnionControlnet(num_trans_channel, num_trans_head, dtype=self.dtype, device=device, operations=operations) for _ in range(num_trans_layer)])
|
| 331 |
-
self.spatial_ch_projs = operations.Linear(num_trans_channel, num_proj_channel, dtype=self.dtype, device=device)
|
| 332 |
-
#-----------------------------------------------------------------------------------------------------
|
| 333 |
-
|
| 334 |
-
control_add_embed_dim = 256
|
| 335 |
-
class ControlAddEmbedding(nn.Module):
|
| 336 |
-
def __init__(self, in_dim, out_dim, num_control_type, dtype=None, device=None, operations=None):
|
| 337 |
-
super().__init__()
|
| 338 |
-
self.num_control_type = num_control_type
|
| 339 |
-
self.in_dim = in_dim
|
| 340 |
-
self.linear_1 = operations.Linear(in_dim * num_control_type, out_dim, dtype=dtype, device=device)
|
| 341 |
-
self.linear_2 = operations.Linear(out_dim, out_dim, dtype=dtype, device=device)
|
| 342 |
-
def forward(self, control_type, dtype, device):
|
| 343 |
-
c_type = torch.zeros((self.num_control_type,), device=device)
|
| 344 |
-
c_type[control_type] = 1.0
|
| 345 |
-
c_type = timestep_embedding(c_type.flatten(), self.in_dim, repeat_only=False).to(dtype).reshape((-1, self.num_control_type * self.in_dim))
|
| 346 |
-
return self.linear_2(torch.nn.functional.silu(self.linear_1(c_type)))
|
| 347 |
-
|
| 348 |
-
self.control_add_embedding = ControlAddEmbedding(control_add_embed_dim, time_embed_dim, self.num_control_type, dtype=self.dtype, device=device, operations=operations)
|
| 349 |
-
else:
|
| 350 |
-
self.task_embedding = None
|
| 351 |
-
self.control_add_embedding = None
|
| 352 |
-
|
| 353 |
-
def union_controlnet_merge(self, hint, control_type, emb, context):
|
| 354 |
-
# Equivalent to: https://github.com/xinsir6/ControlNetPlus/tree/main
|
| 355 |
-
inputs = []
|
| 356 |
-
condition_list = []
|
| 357 |
-
|
| 358 |
-
for idx in range(min(1, len(control_type))):
|
| 359 |
-
controlnet_cond = self.input_hint_block(hint[idx], emb, context)
|
| 360 |
-
feat_seq = torch.mean(controlnet_cond, dim=(2, 3))
|
| 361 |
-
if idx < len(control_type):
|
| 362 |
-
feat_seq += self.task_embedding[control_type[idx]].to(dtype=feat_seq.dtype, device=feat_seq.device)
|
| 363 |
-
|
| 364 |
-
inputs.append(feat_seq.unsqueeze(1))
|
| 365 |
-
condition_list.append(controlnet_cond)
|
| 366 |
-
|
| 367 |
-
x = torch.cat(inputs, dim=1)
|
| 368 |
-
x = self.transformer_layes(x)
|
| 369 |
-
controlnet_cond_fuser = None
|
| 370 |
-
for idx in range(len(control_type)):
|
| 371 |
-
alpha = self.spatial_ch_projs(x[:, idx])
|
| 372 |
-
alpha = alpha.unsqueeze(-1).unsqueeze(-1)
|
| 373 |
-
o = condition_list[idx] + alpha
|
| 374 |
-
if controlnet_cond_fuser is None:
|
| 375 |
-
controlnet_cond_fuser = o
|
| 376 |
-
else:
|
| 377 |
-
controlnet_cond_fuser += o
|
| 378 |
-
return controlnet_cond_fuser
|
| 379 |
-
|
| 380 |
-
def make_zero_conv(self, channels, operations=None, dtype=None, device=None):
|
| 381 |
-
return TimestepEmbedSequential(operations.conv_nd(self.dims, channels, channels, 1, padding=0, dtype=dtype, device=device))
|
| 382 |
-
|
| 383 |
-
def forward(self, x, hint, timesteps, context, y=None, **kwargs):
|
| 384 |
-
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
|
| 385 |
-
emb = self.time_embed(t_emb)
|
| 386 |
-
|
| 387 |
-
guided_hint = None
|
| 388 |
-
if self.control_add_embedding is not None: #Union Controlnet
|
| 389 |
-
control_type = kwargs.get("control_type", [])
|
| 390 |
-
|
| 391 |
-
if any([c >= self.num_control_type for c in control_type]):
|
| 392 |
-
max_type = max(control_type)
|
| 393 |
-
max_type_name = {
|
| 394 |
-
v: k for k, v in UNION_CONTROLNET_TYPES.items()
|
| 395 |
-
}[max_type]
|
| 396 |
-
raise ValueError(
|
| 397 |
-
f"Control type {max_type_name}({max_type}) is out of range for the number of control types" +
|
| 398 |
-
f"({self.num_control_type}) supported.\n" +
|
| 399 |
-
"Please consider using the ProMax ControlNet Union model.\n" +
|
| 400 |
-
"https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/tree/main"
|
| 401 |
-
)
|
| 402 |
-
|
| 403 |
-
emb += self.control_add_embedding(control_type, emb.dtype, emb.device)
|
| 404 |
-
if len(control_type) > 0:
|
| 405 |
-
if len(hint.shape) < 5:
|
| 406 |
-
hint = hint.unsqueeze(dim=0)
|
| 407 |
-
guided_hint = self.union_controlnet_merge(hint, control_type, emb, context)
|
| 408 |
-
|
| 409 |
-
if guided_hint is None:
|
| 410 |
-
guided_hint = self.input_hint_block(hint, emb, context)
|
| 411 |
-
|
| 412 |
-
out_output = []
|
| 413 |
-
out_middle = []
|
| 414 |
-
|
| 415 |
-
if self.num_classes is not None:
|
| 416 |
-
assert y.shape[0] == x.shape[0]
|
| 417 |
-
emb = emb + self.label_emb(y)
|
| 418 |
-
|
| 419 |
-
h = x
|
| 420 |
-
for module, zero_conv in zip(self.input_blocks, self.zero_convs):
|
| 421 |
-
if guided_hint is not None:
|
| 422 |
-
h = module(h, emb, context)
|
| 423 |
-
h += guided_hint
|
| 424 |
-
guided_hint = None
|
| 425 |
-
else:
|
| 426 |
-
h = module(h, emb, context)
|
| 427 |
-
out_output.append(zero_conv(h, emb, context))
|
| 428 |
-
|
| 429 |
-
h = self.middle_block(h, emb, context)
|
| 430 |
-
out_middle.append(self.middle_block_out(h, emb, context))
|
| 431 |
-
|
| 432 |
-
return {"middle": out_middle, "output": out_output}
|
| 433 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
|
|
comfy/cldm/dit_embedder.py
DELETED
|
@@ -1,120 +0,0 @@
|
|
| 1 |
-
import math
|
| 2 |
-
from typing import List, Optional, Tuple
|
| 3 |
-
|
| 4 |
-
import torch
|
| 5 |
-
import torch.nn as nn
|
| 6 |
-
from torch import Tensor
|
| 7 |
-
|
| 8 |
-
from comfy.ldm.modules.diffusionmodules.mmdit import DismantledBlock, PatchEmbed, VectorEmbedder, TimestepEmbedder, get_2d_sincos_pos_embed_torch
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
class ControlNetEmbedder(nn.Module):
|
| 12 |
-
|
| 13 |
-
def __init__(
|
| 14 |
-
self,
|
| 15 |
-
img_size: int,
|
| 16 |
-
patch_size: int,
|
| 17 |
-
in_chans: int,
|
| 18 |
-
attention_head_dim: int,
|
| 19 |
-
num_attention_heads: int,
|
| 20 |
-
adm_in_channels: int,
|
| 21 |
-
num_layers: int,
|
| 22 |
-
main_model_double: int,
|
| 23 |
-
double_y_emb: bool,
|
| 24 |
-
device: torch.device,
|
| 25 |
-
dtype: torch.dtype,
|
| 26 |
-
pos_embed_max_size: Optional[int] = None,
|
| 27 |
-
operations = None,
|
| 28 |
-
):
|
| 29 |
-
super().__init__()
|
| 30 |
-
self.main_model_double = main_model_double
|
| 31 |
-
self.dtype = dtype
|
| 32 |
-
self.hidden_size = num_attention_heads * attention_head_dim
|
| 33 |
-
self.patch_size = patch_size
|
| 34 |
-
self.x_embedder = PatchEmbed(
|
| 35 |
-
img_size=img_size,
|
| 36 |
-
patch_size=patch_size,
|
| 37 |
-
in_chans=in_chans,
|
| 38 |
-
embed_dim=self.hidden_size,
|
| 39 |
-
strict_img_size=pos_embed_max_size is None,
|
| 40 |
-
device=device,
|
| 41 |
-
dtype=dtype,
|
| 42 |
-
operations=operations,
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
self.t_embedder = TimestepEmbedder(self.hidden_size, dtype=dtype, device=device, operations=operations)
|
| 46 |
-
|
| 47 |
-
self.double_y_emb = double_y_emb
|
| 48 |
-
if self.double_y_emb:
|
| 49 |
-
self.orig_y_embedder = VectorEmbedder(
|
| 50 |
-
adm_in_channels, self.hidden_size, dtype, device, operations=operations
|
| 51 |
-
)
|
| 52 |
-
self.y_embedder = VectorEmbedder(
|
| 53 |
-
self.hidden_size, self.hidden_size, dtype, device, operations=operations
|
| 54 |
-
)
|
| 55 |
-
else:
|
| 56 |
-
self.y_embedder = VectorEmbedder(
|
| 57 |
-
adm_in_channels, self.hidden_size, dtype, device, operations=operations
|
| 58 |
-
)
|
| 59 |
-
|
| 60 |
-
self.transformer_blocks = nn.ModuleList(
|
| 61 |
-
DismantledBlock(
|
| 62 |
-
hidden_size=self.hidden_size, num_heads=num_attention_heads, qkv_bias=True,
|
| 63 |
-
dtype=dtype, device=device, operations=operations
|
| 64 |
-
)
|
| 65 |
-
for _ in range(num_layers)
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
# self.use_y_embedder = pooled_projection_dim != self.time_text_embed.text_embedder.linear_1.in_features
|
| 69 |
-
# TODO double check this logic when 8b
|
| 70 |
-
self.use_y_embedder = True
|
| 71 |
-
|
| 72 |
-
self.controlnet_blocks = nn.ModuleList([])
|
| 73 |
-
for _ in range(len(self.transformer_blocks)):
|
| 74 |
-
controlnet_block = operations.Linear(self.hidden_size, self.hidden_size, dtype=dtype, device=device)
|
| 75 |
-
self.controlnet_blocks.append(controlnet_block)
|
| 76 |
-
|
| 77 |
-
self.pos_embed_input = PatchEmbed(
|
| 78 |
-
img_size=img_size,
|
| 79 |
-
patch_size=patch_size,
|
| 80 |
-
in_chans=in_chans,
|
| 81 |
-
embed_dim=self.hidden_size,
|
| 82 |
-
strict_img_size=False,
|
| 83 |
-
device=device,
|
| 84 |
-
dtype=dtype,
|
| 85 |
-
operations=operations,
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
def forward(
|
| 89 |
-
self,
|
| 90 |
-
x: torch.Tensor,
|
| 91 |
-
timesteps: torch.Tensor,
|
| 92 |
-
y: Optional[torch.Tensor] = None,
|
| 93 |
-
context: Optional[torch.Tensor] = None,
|
| 94 |
-
hint = None,
|
| 95 |
-
) -> Tuple[Tensor, List[Tensor]]:
|
| 96 |
-
x_shape = list(x.shape)
|
| 97 |
-
x = self.x_embedder(x)
|
| 98 |
-
if not self.double_y_emb:
|
| 99 |
-
h = (x_shape[-2] + 1) // self.patch_size
|
| 100 |
-
w = (x_shape[-1] + 1) // self.patch_size
|
| 101 |
-
x += get_2d_sincos_pos_embed_torch(self.hidden_size, w, h, device=x.device)
|
| 102 |
-
c = self.t_embedder(timesteps, dtype=x.dtype)
|
| 103 |
-
if y is not None and self.y_embedder is not None:
|
| 104 |
-
if self.double_y_emb:
|
| 105 |
-
y = self.orig_y_embedder(y)
|
| 106 |
-
y = self.y_embedder(y)
|
| 107 |
-
c = c + y
|
| 108 |
-
|
| 109 |
-
x = x + self.pos_embed_input(hint)
|
| 110 |
-
|
| 111 |
-
block_out = ()
|
| 112 |
-
|
| 113 |
-
repeat = math.ceil(self.main_model_double / len(self.transformer_blocks))
|
| 114 |
-
for i in range(len(self.transformer_blocks)):
|
| 115 |
-
out = self.transformer_blocks[i](x, c)
|
| 116 |
-
if not self.double_y_emb:
|
| 117 |
-
x = out
|
| 118 |
-
block_out += (self.controlnet_blocks[i](out),) * repeat
|
| 119 |
-
|
| 120 |
-
return {"output": block_out}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/cldm/mmdit.py
DELETED
|
@@ -1,81 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
from typing import Optional
|
| 3 |
-
import comfy.ldm.modules.diffusionmodules.mmdit
|
| 4 |
-
|
| 5 |
-
class ControlNet(comfy.ldm.modules.diffusionmodules.mmdit.MMDiT):
|
| 6 |
-
def __init__(
|
| 7 |
-
self,
|
| 8 |
-
num_blocks = None,
|
| 9 |
-
control_latent_channels = None,
|
| 10 |
-
dtype = None,
|
| 11 |
-
device = None,
|
| 12 |
-
operations = None,
|
| 13 |
-
**kwargs,
|
| 14 |
-
):
|
| 15 |
-
super().__init__(dtype=dtype, device=device, operations=operations, final_layer=False, num_blocks=num_blocks, **kwargs)
|
| 16 |
-
# controlnet_blocks
|
| 17 |
-
self.controlnet_blocks = torch.nn.ModuleList([])
|
| 18 |
-
for _ in range(len(self.joint_blocks)):
|
| 19 |
-
self.controlnet_blocks.append(operations.Linear(self.hidden_size, self.hidden_size, device=device, dtype=dtype))
|
| 20 |
-
|
| 21 |
-
if control_latent_channels is None:
|
| 22 |
-
control_latent_channels = self.in_channels
|
| 23 |
-
|
| 24 |
-
self.pos_embed_input = comfy.ldm.modules.diffusionmodules.mmdit.PatchEmbed(
|
| 25 |
-
None,
|
| 26 |
-
self.patch_size,
|
| 27 |
-
control_latent_channels,
|
| 28 |
-
self.hidden_size,
|
| 29 |
-
bias=True,
|
| 30 |
-
strict_img_size=False,
|
| 31 |
-
dtype=dtype,
|
| 32 |
-
device=device,
|
| 33 |
-
operations=operations
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
def forward(
|
| 37 |
-
self,
|
| 38 |
-
x: torch.Tensor,
|
| 39 |
-
timesteps: torch.Tensor,
|
| 40 |
-
y: Optional[torch.Tensor] = None,
|
| 41 |
-
context: Optional[torch.Tensor] = None,
|
| 42 |
-
hint = None,
|
| 43 |
-
) -> torch.Tensor:
|
| 44 |
-
|
| 45 |
-
#weird sd3 controlnet specific stuff
|
| 46 |
-
y = torch.zeros_like(y)
|
| 47 |
-
|
| 48 |
-
if self.context_processor is not None:
|
| 49 |
-
context = self.context_processor(context)
|
| 50 |
-
|
| 51 |
-
hw = x.shape[-2:]
|
| 52 |
-
x = self.x_embedder(x) + self.cropped_pos_embed(hw, device=x.device).to(dtype=x.dtype, device=x.device)
|
| 53 |
-
x += self.pos_embed_input(hint)
|
| 54 |
-
|
| 55 |
-
c = self.t_embedder(timesteps, dtype=x.dtype)
|
| 56 |
-
if y is not None and self.y_embedder is not None:
|
| 57 |
-
y = self.y_embedder(y)
|
| 58 |
-
c = c + y
|
| 59 |
-
|
| 60 |
-
if context is not None:
|
| 61 |
-
context = self.context_embedder(context)
|
| 62 |
-
|
| 63 |
-
output = []
|
| 64 |
-
|
| 65 |
-
blocks = len(self.joint_blocks)
|
| 66 |
-
for i in range(blocks):
|
| 67 |
-
context, x = self.joint_blocks[i](
|
| 68 |
-
context,
|
| 69 |
-
x,
|
| 70 |
-
c=c,
|
| 71 |
-
use_checkpoint=self.use_checkpoint,
|
| 72 |
-
)
|
| 73 |
-
|
| 74 |
-
out = self.controlnet_blocks[i](x)
|
| 75 |
-
count = self.depth // blocks
|
| 76 |
-
if i == blocks - 1:
|
| 77 |
-
count -= 1
|
| 78 |
-
for j in range(count):
|
| 79 |
-
output.append(out)
|
| 80 |
-
|
| 81 |
-
return {"output": output}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/cli_args.py
DELETED
|
@@ -1,236 +0,0 @@
|
|
| 1 |
-
import argparse
|
| 2 |
-
import enum
|
| 3 |
-
import os
|
| 4 |
-
import comfy.options
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
class EnumAction(argparse.Action):
|
| 8 |
-
"""
|
| 9 |
-
Argparse action for handling Enums
|
| 10 |
-
"""
|
| 11 |
-
def __init__(self, **kwargs):
|
| 12 |
-
# Pop off the type value
|
| 13 |
-
enum_type = kwargs.pop("type", None)
|
| 14 |
-
|
| 15 |
-
# Ensure an Enum subclass is provided
|
| 16 |
-
if enum_type is None:
|
| 17 |
-
raise ValueError("type must be assigned an Enum when using EnumAction")
|
| 18 |
-
if not issubclass(enum_type, enum.Enum):
|
| 19 |
-
raise TypeError("type must be an Enum when using EnumAction")
|
| 20 |
-
|
| 21 |
-
# Generate choices from the Enum
|
| 22 |
-
choices = tuple(e.value for e in enum_type)
|
| 23 |
-
kwargs.setdefault("choices", choices)
|
| 24 |
-
kwargs.setdefault("metavar", f"[{','.join(list(choices))}]")
|
| 25 |
-
|
| 26 |
-
super(EnumAction, self).__init__(**kwargs)
|
| 27 |
-
|
| 28 |
-
self._enum = enum_type
|
| 29 |
-
|
| 30 |
-
def __call__(self, parser, namespace, values, option_string=None):
|
| 31 |
-
# Convert value back into an Enum
|
| 32 |
-
value = self._enum(values)
|
| 33 |
-
setattr(namespace, self.dest, value)
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
parser = argparse.ArgumentParser()
|
| 37 |
-
|
| 38 |
-
parser.add_argument("--listen", type=str, default="127.0.0.1", metavar="IP", nargs="?", const="0.0.0.0,::", help="Specify the IP address to listen on (default: 127.0.0.1). You can give a list of ip addresses by separating them with a comma like: 127.2.2.2,127.3.3.3 If --listen is provided without an argument, it defaults to 0.0.0.0,:: (listens on all ipv4 and ipv6)")
|
| 39 |
-
parser.add_argument("--port", type=int, default=8188, help="Set the listen port.")
|
| 40 |
-
parser.add_argument("--tls-keyfile", type=str, help="Path to TLS (SSL) key file. Enables TLS, makes app accessible at https://... requires --tls-certfile to function")
|
| 41 |
-
parser.add_argument("--tls-certfile", type=str, help="Path to TLS (SSL) certificate file. Enables TLS, makes app accessible at https://... requires --tls-keyfile to function")
|
| 42 |
-
parser.add_argument("--enable-cors-header", type=str, default=None, metavar="ORIGIN", nargs="?", const="*", help="Enable CORS (Cross-Origin Resource Sharing) with optional origin or allow all with default '*'.")
|
| 43 |
-
parser.add_argument("--max-upload-size", type=float, default=100, help="Set the maximum upload size in MB.")
|
| 44 |
-
|
| 45 |
-
parser.add_argument("--base-directory", type=str, default=None, help="Set the ComfyUI base directory for models, custom_nodes, input, output, temp, and user directories.")
|
| 46 |
-
parser.add_argument("--extra-model-paths-config", type=str, default=None, metavar="PATH", nargs='+', action='append', help="Load one or more extra_model_paths.yaml files.")
|
| 47 |
-
parser.add_argument("--output-directory", type=str, default=None, help="Set the ComfyUI output directory. Overrides --base-directory.")
|
| 48 |
-
parser.add_argument("--temp-directory", type=str, default=None, help="Set the ComfyUI temp directory (default is in the ComfyUI directory). Overrides --base-directory.")
|
| 49 |
-
parser.add_argument("--input-directory", type=str, default=None, help="Set the ComfyUI input directory. Overrides --base-directory.")
|
| 50 |
-
parser.add_argument("--auto-launch", action="store_true", help="Automatically launch ComfyUI in the default browser.")
|
| 51 |
-
parser.add_argument("--disable-auto-launch", action="store_true", help="Disable auto launching the browser.")
|
| 52 |
-
parser.add_argument("--cuda-device", type=int, default=None, metavar="DEVICE_ID", help="Set the id of the cuda device this instance will use.")
|
| 53 |
-
cm_group = parser.add_mutually_exclusive_group()
|
| 54 |
-
cm_group.add_argument("--cuda-malloc", action="store_true", help="Enable cudaMallocAsync (enabled by default for torch 2.0 and up).")
|
| 55 |
-
cm_group.add_argument("--disable-cuda-malloc", action="store_true", help="Disable cudaMallocAsync.")
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
fp_group = parser.add_mutually_exclusive_group()
|
| 59 |
-
fp_group.add_argument("--force-fp32", action="store_true", help="Force fp32 (If this makes your GPU work better please report it).")
|
| 60 |
-
fp_group.add_argument("--force-fp16", action="store_true", help="Force fp16.")
|
| 61 |
-
|
| 62 |
-
fpunet_group = parser.add_mutually_exclusive_group()
|
| 63 |
-
fpunet_group.add_argument("--fp32-unet", action="store_true", help="Run the diffusion model in fp32.")
|
| 64 |
-
fpunet_group.add_argument("--fp64-unet", action="store_true", help="Run the diffusion model in fp64.")
|
| 65 |
-
fpunet_group.add_argument("--bf16-unet", action="store_true", help="Run the diffusion model in bf16.")
|
| 66 |
-
fpunet_group.add_argument("--fp16-unet", action="store_true", help="Run the diffusion model in fp16")
|
| 67 |
-
fpunet_group.add_argument("--fp8_e4m3fn-unet", action="store_true", help="Store unet weights in fp8_e4m3fn.")
|
| 68 |
-
fpunet_group.add_argument("--fp8_e5m2-unet", action="store_true", help="Store unet weights in fp8_e5m2.")
|
| 69 |
-
fpunet_group.add_argument("--fp8_e8m0fnu-unet", action="store_true", help="Store unet weights in fp8_e8m0fnu.")
|
| 70 |
-
|
| 71 |
-
fpvae_group = parser.add_mutually_exclusive_group()
|
| 72 |
-
fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")
|
| 73 |
-
fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")
|
| 74 |
-
fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")
|
| 75 |
-
|
| 76 |
-
parser.add_argument("--cpu-vae", action="store_true", help="Run the VAE on the CPU.")
|
| 77 |
-
|
| 78 |
-
fpte_group = parser.add_mutually_exclusive_group()
|
| 79 |
-
fpte_group.add_argument("--fp8_e4m3fn-text-enc", action="store_true", help="Store text encoder weights in fp8 (e4m3fn variant).")
|
| 80 |
-
fpte_group.add_argument("--fp8_e5m2-text-enc", action="store_true", help="Store text encoder weights in fp8 (e5m2 variant).")
|
| 81 |
-
fpte_group.add_argument("--fp16-text-enc", action="store_true", help="Store text encoder weights in fp16.")
|
| 82 |
-
fpte_group.add_argument("--fp32-text-enc", action="store_true", help="Store text encoder weights in fp32.")
|
| 83 |
-
fpte_group.add_argument("--bf16-text-enc", action="store_true", help="Store text encoder weights in bf16.")
|
| 84 |
-
|
| 85 |
-
parser.add_argument("--force-channels-last", action="store_true", help="Force channels last format when inferencing the models.")
|
| 86 |
-
|
| 87 |
-
parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
|
| 88 |
-
|
| 89 |
-
parser.add_argument("--oneapi-device-selector", type=str, default=None, metavar="SELECTOR_STRING", help="Sets the oneAPI device(s) this instance will use.")
|
| 90 |
-
parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize default when loading models with Intel's Extension for Pytorch.")
|
| 91 |
-
parser.add_argument("--supports-fp8-compute", action="store_true", help="ComfyUI will act like if the device supports fp8 compute.")
|
| 92 |
-
|
| 93 |
-
class LatentPreviewMethod(enum.Enum):
|
| 94 |
-
NoPreviews = "none"
|
| 95 |
-
Auto = "auto"
|
| 96 |
-
Latent2RGB = "latent2rgb"
|
| 97 |
-
TAESD = "taesd"
|
| 98 |
-
|
| 99 |
-
parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)
|
| 100 |
-
|
| 101 |
-
parser.add_argument("--preview-size", type=int, default=512, help="Sets the maximum preview size for sampler nodes.")
|
| 102 |
-
|
| 103 |
-
cache_group = parser.add_mutually_exclusive_group()
|
| 104 |
-
cache_group.add_argument("--cache-classic", action="store_true", help="Use the old style (aggressive) caching.")
|
| 105 |
-
cache_group.add_argument("--cache-lru", type=int, default=0, help="Use LRU caching with a maximum of N node results cached. May use more RAM/VRAM.")
|
| 106 |
-
cache_group.add_argument("--cache-none", action="store_true", help="Reduced RAM/VRAM usage at the expense of executing every node for each run.")
|
| 107 |
-
|
| 108 |
-
attn_group = parser.add_mutually_exclusive_group()
|
| 109 |
-
attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")
|
| 110 |
-
attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")
|
| 111 |
-
attn_group.add_argument("--use-pytorch-cross-attention", action="store_true", help="Use the new pytorch 2.0 cross attention function.")
|
| 112 |
-
attn_group.add_argument("--use-sage-attention", action="store_true", help="Use sage attention.")
|
| 113 |
-
attn_group.add_argument("--use-flash-attention", action="store_true", help="Use FlashAttention.")
|
| 114 |
-
|
| 115 |
-
parser.add_argument("--disable-xformers", action="store_true", help="Disable xformers.")
|
| 116 |
-
|
| 117 |
-
upcast = parser.add_mutually_exclusive_group()
|
| 118 |
-
upcast.add_argument("--force-upcast-attention", action="store_true", help="Force enable attention upcasting, please report if it fixes black images.")
|
| 119 |
-
upcast.add_argument("--dont-upcast-attention", action="store_true", help="Disable all upcasting of attention. Should be unnecessary except for debugging.")
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
vram_group = parser.add_mutually_exclusive_group()
|
| 123 |
-
vram_group.add_argument("--gpu-only", action="store_true", help="Store and run everything (text encoders/CLIP models, etc... on the GPU).")
|
| 124 |
-
vram_group.add_argument("--highvram", action="store_true", help="By default models will be unloaded to CPU memory after being used. This option keeps them in GPU memory.")
|
| 125 |
-
vram_group.add_argument("--normalvram", action="store_true", help="Used to force normal vram use if lowvram gets automatically enabled.")
|
| 126 |
-
vram_group.add_argument("--lowvram", action="store_true", help="Split the unet in parts to use less vram.")
|
| 127 |
-
vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")
|
| 128 |
-
vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
|
| 129 |
-
|
| 130 |
-
parser.add_argument("--reserve-vram", type=float, default=None, help="Set the amount of vram in GB you want to reserve for use by your OS/other software. By default some amount is reserved depending on your OS.")
|
| 131 |
-
|
| 132 |
-
parser.add_argument("--async-offload", action="store_true", help="Use async weight offloading.")
|
| 133 |
-
|
| 134 |
-
parser.add_argument("--default-hashing-function", type=str, choices=['md5', 'sha1', 'sha256', 'sha512'], default='sha256', help="Allows you to choose the hash function to use for duplicate filename / contents comparison. Default is sha256.")
|
| 135 |
-
|
| 136 |
-
parser.add_argument("--disable-smart-memory", action="store_true", help="Force ComfyUI to agressively offload to regular ram instead of keeping models in vram when it can.")
|
| 137 |
-
parser.add_argument("--deterministic", action="store_true", help="Make pytorch use slower deterministic algorithms when it can. Note that this might not make images deterministic in all cases.")
|
| 138 |
-
|
| 139 |
-
class PerformanceFeature(enum.Enum):
|
| 140 |
-
Fp16Accumulation = "fp16_accumulation"
|
| 141 |
-
Fp8MatrixMultiplication = "fp8_matrix_mult"
|
| 142 |
-
CublasOps = "cublas_ops"
|
| 143 |
-
|
| 144 |
-
parser.add_argument("--fast", nargs="*", type=PerformanceFeature, help="Enable some untested and potentially quality deteriorating optimizations. --fast with no arguments enables everything. You can pass a list specific optimizations if you only want to enable specific ones. Current valid optimizations: fp16_accumulation fp8_matrix_mult cublas_ops")
|
| 145 |
-
|
| 146 |
-
parser.add_argument("--mmap-torch-files", action="store_true", help="Use mmap when loading ckpt/pt files.")
|
| 147 |
-
parser.add_argument("--disable-mmap", action="store_true", help="Don't use mmap when loading safetensors.")
|
| 148 |
-
|
| 149 |
-
parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
|
| 150 |
-
parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
|
| 151 |
-
parser.add_argument("--windows-standalone-build", action="store_true", help="Windows standalone build: Enable convenient things that most people using the standalone windows build will probably enjoy (like auto opening the page on startup).")
|
| 152 |
-
|
| 153 |
-
parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")
|
| 154 |
-
parser.add_argument("--disable-all-custom-nodes", action="store_true", help="Disable loading all custom nodes.")
|
| 155 |
-
parser.add_argument("--whitelist-custom-nodes", type=str, nargs='+', default=[], help="Specify custom node folders to load even when --disable-all-custom-nodes is enabled.")
|
| 156 |
-
parser.add_argument("--disable-api-nodes", action="store_true", help="Disable loading all api nodes.")
|
| 157 |
-
|
| 158 |
-
parser.add_argument("--multi-user", action="store_true", help="Enables per-user storage.")
|
| 159 |
-
|
| 160 |
-
parser.add_argument("--verbose", default='INFO', const='DEBUG', nargs="?", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level')
|
| 161 |
-
parser.add_argument("--log-stdout", action="store_true", help="Send normal process output to stdout instead of stderr (default).")
|
| 162 |
-
|
| 163 |
-
# The default built-in provider hosted under web/
|
| 164 |
-
DEFAULT_VERSION_STRING = "comfyanonymous/ComfyUI@latest"
|
| 165 |
-
|
| 166 |
-
parser.add_argument(
|
| 167 |
-
"--front-end-version",
|
| 168 |
-
type=str,
|
| 169 |
-
default=DEFAULT_VERSION_STRING,
|
| 170 |
-
help="""
|
| 171 |
-
Specifies the version of the frontend to be used. This command needs internet connectivity to query and
|
| 172 |
-
download available frontend implementations from GitHub releases.
|
| 173 |
-
|
| 174 |
-
The version string should be in the format of:
|
| 175 |
-
[repoOwner]/[repoName]@[version]
|
| 176 |
-
where version is one of: "latest" or a valid version number (e.g. "1.0.0")
|
| 177 |
-
""",
|
| 178 |
-
)
|
| 179 |
-
|
| 180 |
-
def is_valid_directory(path: str) -> str:
|
| 181 |
-
"""Validate if the given path is a directory, and check permissions."""
|
| 182 |
-
if not os.path.exists(path):
|
| 183 |
-
raise argparse.ArgumentTypeError(f"The path '{path}' does not exist.")
|
| 184 |
-
if not os.path.isdir(path):
|
| 185 |
-
raise argparse.ArgumentTypeError(f"'{path}' is not a directory.")
|
| 186 |
-
if not os.access(path, os.R_OK):
|
| 187 |
-
raise argparse.ArgumentTypeError(f"You do not have read permissions for '{path}'.")
|
| 188 |
-
return path
|
| 189 |
-
|
| 190 |
-
parser.add_argument(
|
| 191 |
-
"--front-end-root",
|
| 192 |
-
type=is_valid_directory,
|
| 193 |
-
default=None,
|
| 194 |
-
help="The local filesystem path to the directory where the frontend is located. Overrides --front-end-version.",
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
parser.add_argument("--user-directory", type=is_valid_directory, default=None, help="Set the ComfyUI user directory with an absolute path. Overrides --base-directory.")
|
| 198 |
-
|
| 199 |
-
parser.add_argument("--enable-compress-response-body", action="store_true", help="Enable compressing response body.")
|
| 200 |
-
|
| 201 |
-
parser.add_argument(
|
| 202 |
-
"--comfy-api-base",
|
| 203 |
-
type=str,
|
| 204 |
-
default="https://api.comfy.org",
|
| 205 |
-
help="Set the base URL for the ComfyUI API. (default: https://api.comfy.org)",
|
| 206 |
-
)
|
| 207 |
-
|
| 208 |
-
database_default_path = os.path.abspath(
|
| 209 |
-
os.path.join(os.path.dirname(__file__), "..", "user", "comfyui.db")
|
| 210 |
-
)
|
| 211 |
-
parser.add_argument("--database-url", type=str, default=f"sqlite:///{database_default_path}", help="Specify the database URL, e.g. for an in-memory database you can use 'sqlite:///:memory:'.")
|
| 212 |
-
|
| 213 |
-
if comfy.options.args_parsing:
|
| 214 |
-
args = parser.parse_args()
|
| 215 |
-
else:
|
| 216 |
-
args = parser.parse_args([])
|
| 217 |
-
|
| 218 |
-
if args.windows_standalone_build:
|
| 219 |
-
args.auto_launch = True
|
| 220 |
-
|
| 221 |
-
if args.disable_auto_launch:
|
| 222 |
-
args.auto_launch = False
|
| 223 |
-
|
| 224 |
-
if args.force_fp16:
|
| 225 |
-
args.fp16_unet = True
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
# '--fast' is not provided, use an empty set
|
| 229 |
-
if args.fast is None:
|
| 230 |
-
args.fast = set()
|
| 231 |
-
# '--fast' is provided with an empty list, enable all optimizations
|
| 232 |
-
elif args.fast == []:
|
| 233 |
-
args.fast = set(PerformanceFeature)
|
| 234 |
-
# '--fast' is provided with a list of performance features, use that list
|
| 235 |
-
else:
|
| 236 |
-
args.fast = set(args.fast)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
],
|
| 5 |
-
"attention_dropout": 0.0,
|
| 6 |
-
"bos_token_id": 0,
|
| 7 |
-
"dropout": 0.0,
|
| 8 |
-
"eos_token_id": 49407,
|
| 9 |
-
"hidden_act": "gelu",
|
| 10 |
-
"hidden_size": 1280,
|
| 11 |
-
"initializer_factor": 1.0,
|
| 12 |
-
"initializer_range": 0.02,
|
| 13 |
-
"intermediate_size": 5120,
|
| 14 |
-
"layer_norm_eps": 1e-05,
|
| 15 |
-
"max_position_embeddings": 77,
|
| 16 |
-
"model_type": "clip_text_model",
|
| 17 |
-
"num_attention_heads": 20,
|
| 18 |
-
"num_hidden_layers": 32,
|
| 19 |
-
"pad_token_id": 1,
|
| 20 |
-
"projection_dim": 1280,
|
| 21 |
-
"torch_dtype": "float32",
|
| 22 |
-
"vocab_size": 49408
|
| 23 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/clip_model.py
DELETED
|
@@ -1,244 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
from comfy.ldm.modules.attention import optimized_attention_for_device
|
| 3 |
-
import comfy.ops
|
| 4 |
-
|
| 5 |
-
class CLIPAttention(torch.nn.Module):
|
| 6 |
-
def __init__(self, embed_dim, heads, dtype, device, operations):
|
| 7 |
-
super().__init__()
|
| 8 |
-
|
| 9 |
-
self.heads = heads
|
| 10 |
-
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
|
| 11 |
-
self.k_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
|
| 12 |
-
self.v_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
|
| 13 |
-
|
| 14 |
-
self.out_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
|
| 15 |
-
|
| 16 |
-
def forward(self, x, mask=None, optimized_attention=None):
|
| 17 |
-
q = self.q_proj(x)
|
| 18 |
-
k = self.k_proj(x)
|
| 19 |
-
v = self.v_proj(x)
|
| 20 |
-
|
| 21 |
-
out = optimized_attention(q, k, v, self.heads, mask)
|
| 22 |
-
return self.out_proj(out)
|
| 23 |
-
|
| 24 |
-
ACTIVATIONS = {"quick_gelu": lambda a: a * torch.sigmoid(1.702 * a),
|
| 25 |
-
"gelu": torch.nn.functional.gelu,
|
| 26 |
-
"gelu_pytorch_tanh": lambda a: torch.nn.functional.gelu(a, approximate="tanh"),
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
class CLIPMLP(torch.nn.Module):
|
| 30 |
-
def __init__(self, embed_dim, intermediate_size, activation, dtype, device, operations):
|
| 31 |
-
super().__init__()
|
| 32 |
-
self.fc1 = operations.Linear(embed_dim, intermediate_size, bias=True, dtype=dtype, device=device)
|
| 33 |
-
self.activation = ACTIVATIONS[activation]
|
| 34 |
-
self.fc2 = operations.Linear(intermediate_size, embed_dim, bias=True, dtype=dtype, device=device)
|
| 35 |
-
|
| 36 |
-
def forward(self, x):
|
| 37 |
-
x = self.fc1(x)
|
| 38 |
-
x = self.activation(x)
|
| 39 |
-
x = self.fc2(x)
|
| 40 |
-
return x
|
| 41 |
-
|
| 42 |
-
class CLIPLayer(torch.nn.Module):
|
| 43 |
-
def __init__(self, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
|
| 44 |
-
super().__init__()
|
| 45 |
-
self.layer_norm1 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
| 46 |
-
self.self_attn = CLIPAttention(embed_dim, heads, dtype, device, operations)
|
| 47 |
-
self.layer_norm2 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
| 48 |
-
self.mlp = CLIPMLP(embed_dim, intermediate_size, intermediate_activation, dtype, device, operations)
|
| 49 |
-
|
| 50 |
-
def forward(self, x, mask=None, optimized_attention=None):
|
| 51 |
-
x += self.self_attn(self.layer_norm1(x), mask, optimized_attention)
|
| 52 |
-
x += self.mlp(self.layer_norm2(x))
|
| 53 |
-
return x
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
class CLIPEncoder(torch.nn.Module):
|
| 57 |
-
def __init__(self, num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
|
| 58 |
-
super().__init__()
|
| 59 |
-
self.layers = torch.nn.ModuleList([CLIPLayer(embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations) for i in range(num_layers)])
|
| 60 |
-
|
| 61 |
-
def forward(self, x, mask=None, intermediate_output=None):
|
| 62 |
-
optimized_attention = optimized_attention_for_device(x.device, mask=mask is not None, small_input=True)
|
| 63 |
-
|
| 64 |
-
if intermediate_output is not None:
|
| 65 |
-
if intermediate_output < 0:
|
| 66 |
-
intermediate_output = len(self.layers) + intermediate_output
|
| 67 |
-
|
| 68 |
-
intermediate = None
|
| 69 |
-
for i, l in enumerate(self.layers):
|
| 70 |
-
x = l(x, mask, optimized_attention)
|
| 71 |
-
if i == intermediate_output:
|
| 72 |
-
intermediate = x.clone()
|
| 73 |
-
return x, intermediate
|
| 74 |
-
|
| 75 |
-
class CLIPEmbeddings(torch.nn.Module):
|
| 76 |
-
def __init__(self, embed_dim, vocab_size=49408, num_positions=77, dtype=None, device=None, operations=None):
|
| 77 |
-
super().__init__()
|
| 78 |
-
self.token_embedding = operations.Embedding(vocab_size, embed_dim, dtype=dtype, device=device)
|
| 79 |
-
self.position_embedding = operations.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
|
| 80 |
-
|
| 81 |
-
def forward(self, input_tokens, dtype=torch.float32):
|
| 82 |
-
return self.token_embedding(input_tokens, out_dtype=dtype) + comfy.ops.cast_to(self.position_embedding.weight, dtype=dtype, device=input_tokens.device)
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
class CLIPTextModel_(torch.nn.Module):
|
| 86 |
-
def __init__(self, config_dict, dtype, device, operations):
|
| 87 |
-
num_layers = config_dict["num_hidden_layers"]
|
| 88 |
-
embed_dim = config_dict["hidden_size"]
|
| 89 |
-
heads = config_dict["num_attention_heads"]
|
| 90 |
-
intermediate_size = config_dict["intermediate_size"]
|
| 91 |
-
intermediate_activation = config_dict["hidden_act"]
|
| 92 |
-
num_positions = config_dict["max_position_embeddings"]
|
| 93 |
-
self.eos_token_id = config_dict["eos_token_id"]
|
| 94 |
-
|
| 95 |
-
super().__init__()
|
| 96 |
-
self.embeddings = CLIPEmbeddings(embed_dim, num_positions=num_positions, dtype=dtype, device=device, operations=operations)
|
| 97 |
-
self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
|
| 98 |
-
self.final_layer_norm = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
| 99 |
-
|
| 100 |
-
def forward(self, input_tokens=None, attention_mask=None, embeds=None, num_tokens=None, intermediate_output=None, final_layer_norm_intermediate=True, dtype=torch.float32):
|
| 101 |
-
if embeds is not None:
|
| 102 |
-
x = embeds + comfy.ops.cast_to(self.embeddings.position_embedding.weight, dtype=dtype, device=embeds.device)
|
| 103 |
-
else:
|
| 104 |
-
x = self.embeddings(input_tokens, dtype=dtype)
|
| 105 |
-
|
| 106 |
-
mask = None
|
| 107 |
-
if attention_mask is not None:
|
| 108 |
-
mask = 1.0 - attention_mask.to(x.dtype).reshape((attention_mask.shape[0], 1, -1, attention_mask.shape[-1])).expand(attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1])
|
| 109 |
-
mask = mask.masked_fill(mask.to(torch.bool), -torch.finfo(x.dtype).max)
|
| 110 |
-
|
| 111 |
-
causal_mask = torch.full((x.shape[1], x.shape[1]), -torch.finfo(x.dtype).max, dtype=x.dtype, device=x.device).triu_(1)
|
| 112 |
-
|
| 113 |
-
if mask is not None:
|
| 114 |
-
mask += causal_mask
|
| 115 |
-
else:
|
| 116 |
-
mask = causal_mask
|
| 117 |
-
|
| 118 |
-
x, i = self.encoder(x, mask=mask, intermediate_output=intermediate_output)
|
| 119 |
-
x = self.final_layer_norm(x)
|
| 120 |
-
if i is not None and final_layer_norm_intermediate:
|
| 121 |
-
i = self.final_layer_norm(i)
|
| 122 |
-
|
| 123 |
-
if num_tokens is not None:
|
| 124 |
-
pooled_output = x[list(range(x.shape[0])), list(map(lambda a: a - 1, num_tokens))]
|
| 125 |
-
else:
|
| 126 |
-
pooled_output = x[torch.arange(x.shape[0], device=x.device), (torch.round(input_tokens).to(dtype=torch.int, device=x.device) == self.eos_token_id).int().argmax(dim=-1),]
|
| 127 |
-
return x, i, pooled_output
|
| 128 |
-
|
| 129 |
-
class CLIPTextModel(torch.nn.Module):
|
| 130 |
-
def __init__(self, config_dict, dtype, device, operations):
|
| 131 |
-
super().__init__()
|
| 132 |
-
self.num_layers = config_dict["num_hidden_layers"]
|
| 133 |
-
self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
|
| 134 |
-
embed_dim = config_dict["hidden_size"]
|
| 135 |
-
self.text_projection = operations.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
|
| 136 |
-
self.dtype = dtype
|
| 137 |
-
|
| 138 |
-
def get_input_embeddings(self):
|
| 139 |
-
return self.text_model.embeddings.token_embedding
|
| 140 |
-
|
| 141 |
-
def set_input_embeddings(self, embeddings):
|
| 142 |
-
self.text_model.embeddings.token_embedding = embeddings
|
| 143 |
-
|
| 144 |
-
def forward(self, *args, **kwargs):
|
| 145 |
-
x = self.text_model(*args, **kwargs)
|
| 146 |
-
out = self.text_projection(x[2])
|
| 147 |
-
return (x[0], x[1], out, x[2])
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
class CLIPVisionEmbeddings(torch.nn.Module):
|
| 151 |
-
def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, model_type="", dtype=None, device=None, operations=None):
|
| 152 |
-
super().__init__()
|
| 153 |
-
|
| 154 |
-
num_patches = (image_size // patch_size) ** 2
|
| 155 |
-
if model_type == "siglip_vision_model":
|
| 156 |
-
self.class_embedding = None
|
| 157 |
-
patch_bias = True
|
| 158 |
-
else:
|
| 159 |
-
num_patches = num_patches + 1
|
| 160 |
-
self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
|
| 161 |
-
patch_bias = False
|
| 162 |
-
|
| 163 |
-
self.patch_embedding = operations.Conv2d(
|
| 164 |
-
in_channels=num_channels,
|
| 165 |
-
out_channels=embed_dim,
|
| 166 |
-
kernel_size=patch_size,
|
| 167 |
-
stride=patch_size,
|
| 168 |
-
bias=patch_bias,
|
| 169 |
-
dtype=dtype,
|
| 170 |
-
device=device
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
self.position_embedding = operations.Embedding(num_patches, embed_dim, dtype=dtype, device=device)
|
| 174 |
-
|
| 175 |
-
def forward(self, pixel_values):
|
| 176 |
-
embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
|
| 177 |
-
if self.class_embedding is not None:
|
| 178 |
-
embeds = torch.cat([comfy.ops.cast_to_input(self.class_embedding, embeds).expand(pixel_values.shape[0], 1, -1), embeds], dim=1)
|
| 179 |
-
return embeds + comfy.ops.cast_to_input(self.position_embedding.weight, embeds)
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
class CLIPVision(torch.nn.Module):
|
| 183 |
-
def __init__(self, config_dict, dtype, device, operations):
|
| 184 |
-
super().__init__()
|
| 185 |
-
num_layers = config_dict["num_hidden_layers"]
|
| 186 |
-
embed_dim = config_dict["hidden_size"]
|
| 187 |
-
heads = config_dict["num_attention_heads"]
|
| 188 |
-
intermediate_size = config_dict["intermediate_size"]
|
| 189 |
-
intermediate_activation = config_dict["hidden_act"]
|
| 190 |
-
model_type = config_dict["model_type"]
|
| 191 |
-
|
| 192 |
-
self.embeddings = CLIPVisionEmbeddings(embed_dim, config_dict["num_channels"], config_dict["patch_size"], config_dict["image_size"], model_type=model_type, dtype=dtype, device=device, operations=operations)
|
| 193 |
-
if model_type == "siglip_vision_model":
|
| 194 |
-
self.pre_layrnorm = lambda a: a
|
| 195 |
-
self.output_layernorm = True
|
| 196 |
-
else:
|
| 197 |
-
self.pre_layrnorm = operations.LayerNorm(embed_dim)
|
| 198 |
-
self.output_layernorm = False
|
| 199 |
-
self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
|
| 200 |
-
self.post_layernorm = operations.LayerNorm(embed_dim)
|
| 201 |
-
|
| 202 |
-
def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
|
| 203 |
-
x = self.embeddings(pixel_values)
|
| 204 |
-
x = self.pre_layrnorm(x)
|
| 205 |
-
#TODO: attention_mask?
|
| 206 |
-
x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
|
| 207 |
-
if self.output_layernorm:
|
| 208 |
-
x = self.post_layernorm(x)
|
| 209 |
-
pooled_output = x
|
| 210 |
-
else:
|
| 211 |
-
pooled_output = self.post_layernorm(x[:, 0, :])
|
| 212 |
-
return x, i, pooled_output
|
| 213 |
-
|
| 214 |
-
class LlavaProjector(torch.nn.Module):
|
| 215 |
-
def __init__(self, in_dim, out_dim, dtype, device, operations):
|
| 216 |
-
super().__init__()
|
| 217 |
-
self.linear_1 = operations.Linear(in_dim, out_dim, bias=True, device=device, dtype=dtype)
|
| 218 |
-
self.linear_2 = operations.Linear(out_dim, out_dim, bias=True, device=device, dtype=dtype)
|
| 219 |
-
|
| 220 |
-
def forward(self, x):
|
| 221 |
-
return self.linear_2(torch.nn.functional.gelu(self.linear_1(x[:, 1:])))
|
| 222 |
-
|
| 223 |
-
class CLIPVisionModelProjection(torch.nn.Module):
|
| 224 |
-
def __init__(self, config_dict, dtype, device, operations):
|
| 225 |
-
super().__init__()
|
| 226 |
-
self.vision_model = CLIPVision(config_dict, dtype, device, operations)
|
| 227 |
-
if "projection_dim" in config_dict:
|
| 228 |
-
self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projection_dim"], bias=False)
|
| 229 |
-
else:
|
| 230 |
-
self.visual_projection = lambda a: a
|
| 231 |
-
|
| 232 |
-
if "llava3" == config_dict.get("projector_type", None):
|
| 233 |
-
self.multi_modal_projector = LlavaProjector(config_dict["hidden_size"], 4096, dtype, device, operations)
|
| 234 |
-
else:
|
| 235 |
-
self.multi_modal_projector = None
|
| 236 |
-
|
| 237 |
-
def forward(self, *args, **kwargs):
|
| 238 |
-
x = self.vision_model(*args, **kwargs)
|
| 239 |
-
out = self.visual_projection(x[2])
|
| 240 |
-
projected = None
|
| 241 |
-
if self.multi_modal_projector is not None:
|
| 242 |
-
projected = self.multi_modal_projector(x[1])
|
| 243 |
-
|
| 244 |
-
return (x[0], x[1], out, projected)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/clip_vision.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
from .utils import load_torch_file, transformers_convert, state_dict_prefix_replace
|
| 2 |
-
import os
|
| 3 |
-
import torch
|
| 4 |
-
import json
|
| 5 |
-
import logging
|
| 6 |
-
|
| 7 |
-
import comfy.ops
|
| 8 |
-
import comfy.model_patcher
|
| 9 |
-
import comfy.model_management
|
| 10 |
-
import comfy.utils
|
| 11 |
-
import comfy.clip_model
|
| 12 |
-
import comfy.image_encoders.dino2
|
| 13 |
-
|
| 14 |
-
class Output:
|
| 15 |
-
def __getitem__(self, key):
|
| 16 |
-
return getattr(self, key)
|
| 17 |
-
def __setitem__(self, key, item):
|
| 18 |
-
setattr(self, key, item)
|
| 19 |
-
|
| 20 |
-
def clip_preprocess(image, size=224, mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711], crop=True):
|
| 21 |
-
image = image[:, :, :, :3] if image.shape[3] > 3 else image
|
| 22 |
-
mean = torch.tensor(mean, device=image.device, dtype=image.dtype)
|
| 23 |
-
std = torch.tensor(std, device=image.device, dtype=image.dtype)
|
| 24 |
-
image = image.movedim(-1, 1)
|
| 25 |
-
if not (image.shape[2] == size and image.shape[3] == size):
|
| 26 |
-
if crop:
|
| 27 |
-
scale = (size / min(image.shape[2], image.shape[3]))
|
| 28 |
-
scale_size = (round(scale * image.shape[2]), round(scale * image.shape[3]))
|
| 29 |
-
else:
|
| 30 |
-
scale_size = (size, size)
|
| 31 |
-
|
| 32 |
-
image = torch.nn.functional.interpolate(image, size=scale_size, mode="bicubic", antialias=True)
|
| 33 |
-
h = (image.shape[2] - size)//2
|
| 34 |
-
w = (image.shape[3] - size)//2
|
| 35 |
-
image = image[:,:,h:h+size,w:w+size]
|
| 36 |
-
image = torch.clip((255. * image), 0, 255).round() / 255.0
|
| 37 |
-
return (image - mean.view([3,1,1])) / std.view([3,1,1])
|
| 38 |
-
|
| 39 |
-
IMAGE_ENCODERS = {
|
| 40 |
-
"clip_vision_model": comfy.clip_model.CLIPVisionModelProjection,
|
| 41 |
-
"siglip_vision_model": comfy.clip_model.CLIPVisionModelProjection,
|
| 42 |
-
"dinov2": comfy.image_encoders.dino2.Dinov2Model,
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
class ClipVisionModel():
|
| 46 |
-
def __init__(self, json_config):
|
| 47 |
-
with open(json_config) as f:
|
| 48 |
-
config = json.load(f)
|
| 49 |
-
|
| 50 |
-
self.image_size = config.get("image_size", 224)
|
| 51 |
-
self.image_mean = config.get("image_mean", [0.48145466, 0.4578275, 0.40821073])
|
| 52 |
-
self.image_std = config.get("image_std", [0.26862954, 0.26130258, 0.27577711])
|
| 53 |
-
model_class = IMAGE_ENCODERS.get(config.get("model_type", "clip_vision_model"))
|
| 54 |
-
self.load_device = comfy.model_management.text_encoder_device()
|
| 55 |
-
offload_device = comfy.model_management.text_encoder_offload_device()
|
| 56 |
-
self.dtype = comfy.model_management.text_encoder_dtype(self.load_device)
|
| 57 |
-
self.model = model_class(config, self.dtype, offload_device, comfy.ops.manual_cast)
|
| 58 |
-
self.model.eval()
|
| 59 |
-
|
| 60 |
-
self.patcher = comfy.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
|
| 61 |
-
|
| 62 |
-
def load_sd(self, sd):
|
| 63 |
-
return self.model.load_state_dict(sd, strict=False)
|
| 64 |
-
|
| 65 |
-
def get_sd(self):
|
| 66 |
-
return self.model.state_dict()
|
| 67 |
-
|
| 68 |
-
def encode_image(self, image, crop=True):
|
| 69 |
-
comfy.model_management.load_model_gpu(self.patcher)
|
| 70 |
-
pixel_values = clip_preprocess(image.to(self.load_device), size=self.image_size, mean=self.image_mean, std=self.image_std, crop=crop).float()
|
| 71 |
-
out = self.model(pixel_values=pixel_values, intermediate_output=-2)
|
| 72 |
-
|
| 73 |
-
outputs = Output()
|
| 74 |
-
outputs["last_hidden_state"] = out[0].to(comfy.model_management.intermediate_device())
|
| 75 |
-
outputs["image_embeds"] = out[2].to(comfy.model_management.intermediate_device())
|
| 76 |
-
outputs["penultimate_hidden_states"] = out[1].to(comfy.model_management.intermediate_device())
|
| 77 |
-
outputs["mm_projected"] = out[3]
|
| 78 |
-
return outputs
|
| 79 |
-
|
| 80 |
-
def convert_to_transformers(sd, prefix):
|
| 81 |
-
sd_k = sd.keys()
|
| 82 |
-
if "{}transformer.resblocks.0.attn.in_proj_weight".format(prefix) in sd_k:
|
| 83 |
-
keys_to_replace = {
|
| 84 |
-
"{}class_embedding".format(prefix): "vision_model.embeddings.class_embedding",
|
| 85 |
-
"{}conv1.weight".format(prefix): "vision_model.embeddings.patch_embedding.weight",
|
| 86 |
-
"{}positional_embedding".format(prefix): "vision_model.embeddings.position_embedding.weight",
|
| 87 |
-
"{}ln_post.bias".format(prefix): "vision_model.post_layernorm.bias",
|
| 88 |
-
"{}ln_post.weight".format(prefix): "vision_model.post_layernorm.weight",
|
| 89 |
-
"{}ln_pre.bias".format(prefix): "vision_model.pre_layrnorm.bias",
|
| 90 |
-
"{}ln_pre.weight".format(prefix): "vision_model.pre_layrnorm.weight",
|
| 91 |
-
}
|
| 92 |
-
|
| 93 |
-
for x in keys_to_replace:
|
| 94 |
-
if x in sd_k:
|
| 95 |
-
sd[keys_to_replace[x]] = sd.pop(x)
|
| 96 |
-
|
| 97 |
-
if "{}proj".format(prefix) in sd_k:
|
| 98 |
-
sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
|
| 99 |
-
|
| 100 |
-
sd = transformers_convert(sd, prefix, "vision_model.", 48)
|
| 101 |
-
else:
|
| 102 |
-
replace_prefix = {prefix: ""}
|
| 103 |
-
sd = state_dict_prefix_replace(sd, replace_prefix)
|
| 104 |
-
return sd
|
| 105 |
-
|
| 106 |
-
def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
|
| 107 |
-
if convert_keys:
|
| 108 |
-
sd = convert_to_transformers(sd, prefix)
|
| 109 |
-
if "vision_model.encoder.layers.47.layer_norm1.weight" in sd:
|
| 110 |
-
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_g.json")
|
| 111 |
-
elif "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
|
| 112 |
-
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
|
| 113 |
-
elif "vision_model.encoder.layers.22.layer_norm1.weight" in sd:
|
| 114 |
-
embed_shape = sd["vision_model.embeddings.position_embedding.weight"].shape[0]
|
| 115 |
-
if sd["vision_model.encoder.layers.0.layer_norm1.weight"].shape[0] == 1152:
|
| 116 |
-
if embed_shape == 729:
|
| 117 |
-
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_siglip_384.json")
|
| 118 |
-
elif embed_shape == 1024:
|
| 119 |
-
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_siglip_512.json")
|
| 120 |
-
elif embed_shape == 577:
|
| 121 |
-
if "multi_modal_projector.linear_1.bias" in sd:
|
| 122 |
-
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336_llava.json")
|
| 123 |
-
else:
|
| 124 |
-
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336.json")
|
| 125 |
-
else:
|
| 126 |
-
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
|
| 127 |
-
elif "embeddings.patch_embeddings.projection.weight" in sd:
|
| 128 |
-
json_config = os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "image_encoders"), "dino2_giant.json")
|
| 129 |
-
else:
|
| 130 |
-
return None
|
| 131 |
-
|
| 132 |
-
clip = ClipVisionModel(json_config)
|
| 133 |
-
m, u = clip.load_sd(sd)
|
| 134 |
-
if len(m) > 0:
|
| 135 |
-
logging.warning("missing clip vision: {}".format(m))
|
| 136 |
-
u = set(u)
|
| 137 |
-
keys = list(sd.keys())
|
| 138 |
-
for k in keys:
|
| 139 |
-
if k not in u:
|
| 140 |
-
sd.pop(k)
|
| 141 |
-
return clip
|
| 142 |
-
|
| 143 |
-
def load(ckpt_path):
|
| 144 |
-
sd = load_torch_file(ckpt_path)
|
| 145 |
-
if "visual.transformer.resblocks.0.attn.in_proj_weight" in sd:
|
| 146 |
-
return load_clipvision_from_sd(sd, prefix="visual.", convert_keys=True)
|
| 147 |
-
else:
|
| 148 |
-
return load_clipvision_from_sd(sd)
|
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hidden_size": 1664,
|
| 6 |
-
"image_size": 224,
|
| 7 |
-
"initializer_factor": 1.0,
|
| 8 |
-
"initializer_range": 0.02,
|
| 9 |
-
"intermediate_size": 8192,
|
| 10 |
-
"layer_norm_eps": 1e-05,
|
| 11 |
-
"model_type": "clip_vision_model",
|
| 12 |
-
"num_attention_heads": 16,
|
| 13 |
-
"num_channels": 3,
|
| 14 |
-
"num_hidden_layers": 48,
|
| 15 |
-
"patch_size": 14,
|
| 16 |
-
"projection_dim": 1280,
|
| 17 |
-
"torch_dtype": "float32"
|
| 18 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/clip_vision_config_h.json
DELETED
|
@@ -1,18 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"attention_dropout": 0.0,
|
| 3 |
-
"dropout": 0.0,
|
| 4 |
-
"hidden_act": "gelu",
|
| 5 |
-
"hidden_size": 1280,
|
| 6 |
-
"image_size": 224,
|
| 7 |
-
"initializer_factor": 1.0,
|
| 8 |
-
"initializer_range": 0.02,
|
| 9 |
-
"intermediate_size": 5120,
|
| 10 |
-
"layer_norm_eps": 1e-05,
|
| 11 |
-
"model_type": "clip_vision_model",
|
| 12 |
-
"num_attention_heads": 16,
|
| 13 |
-
"num_channels": 3,
|
| 14 |
-
"num_hidden_layers": 32,
|
| 15 |
-
"patch_size": 14,
|
| 16 |
-
"projection_dim": 1024,
|
| 17 |
-
"torch_dtype": "float32"
|
| 18 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/clip_vision_config_vitl.json
DELETED
|
@@ -1,18 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"attention_dropout": 0.0,
|
| 3 |
-
"dropout": 0.0,
|
| 4 |
-
"hidden_act": "quick_gelu",
|
| 5 |
-
"hidden_size": 1024,
|
| 6 |
-
"image_size": 224,
|
| 7 |
-
"initializer_factor": 1.0,
|
| 8 |
-
"initializer_range": 0.02,
|
| 9 |
-
"intermediate_size": 4096,
|
| 10 |
-
"layer_norm_eps": 1e-05,
|
| 11 |
-
"model_type": "clip_vision_model",
|
| 12 |
-
"num_attention_heads": 16,
|
| 13 |
-
"num_channels": 3,
|
| 14 |
-
"num_hidden_layers": 24,
|
| 15 |
-
"patch_size": 14,
|
| 16 |
-
"projection_dim": 768,
|
| 17 |
-
"torch_dtype": "float32"
|
| 18 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/clip_vision_config_vitl_336.json
DELETED
|
@@ -1,18 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"attention_dropout": 0.0,
|
| 3 |
-
"dropout": 0.0,
|
| 4 |
-
"hidden_act": "quick_gelu",
|
| 5 |
-
"hidden_size": 1024,
|
| 6 |
-
"image_size": 336,
|
| 7 |
-
"initializer_factor": 1.0,
|
| 8 |
-
"initializer_range": 0.02,
|
| 9 |
-
"intermediate_size": 4096,
|
| 10 |
-
"layer_norm_eps": 1e-5,
|
| 11 |
-
"model_type": "clip_vision_model",
|
| 12 |
-
"num_attention_heads": 16,
|
| 13 |
-
"num_channels": 3,
|
| 14 |
-
"num_hidden_layers": 24,
|
| 15 |
-
"patch_size": 14,
|
| 16 |
-
"projection_dim": 768,
|
| 17 |
-
"torch_dtype": "float32"
|
| 18 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/clip_vision_config_vitl_336_llava.json
DELETED
|
@@ -1,19 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"attention_dropout": 0.0,
|
| 3 |
-
"dropout": 0.0,
|
| 4 |
-
"hidden_act": "quick_gelu",
|
| 5 |
-
"hidden_size": 1024,
|
| 6 |
-
"image_size": 336,
|
| 7 |
-
"initializer_factor": 1.0,
|
| 8 |
-
"initializer_range": 0.02,
|
| 9 |
-
"intermediate_size": 4096,
|
| 10 |
-
"layer_norm_eps": 1e-5,
|
| 11 |
-
"model_type": "clip_vision_model",
|
| 12 |
-
"num_attention_heads": 16,
|
| 13 |
-
"num_channels": 3,
|
| 14 |
-
"num_hidden_layers": 24,
|
| 15 |
-
"patch_size": 14,
|
| 16 |
-
"projection_dim": 768,
|
| 17 |
-
"projector_type": "llava3",
|
| 18 |
-
"torch_dtype": "float32"
|
| 19 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/clip_vision_siglip_384.json
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"num_channels": 3,
|
| 3 |
-
"hidden_act": "gelu_pytorch_tanh",
|
| 4 |
-
"hidden_size": 1152,
|
| 5 |
-
"image_size": 384,
|
| 6 |
-
"intermediate_size": 4304,
|
| 7 |
-
"model_type": "siglip_vision_model",
|
| 8 |
-
"num_attention_heads": 16,
|
| 9 |
-
"num_hidden_layers": 27,
|
| 10 |
-
"patch_size": 14,
|
| 11 |
-
"image_mean": [0.5, 0.5, 0.5],
|
| 12 |
-
"image_std": [0.5, 0.5, 0.5]
|
| 13 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/clip_vision_siglip_512.json
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"num_channels": 3,
|
| 3 |
-
"hidden_act": "gelu_pytorch_tanh",
|
| 4 |
-
"hidden_size": 1152,
|
| 5 |
-
"image_size": 512,
|
| 6 |
-
"intermediate_size": 4304,
|
| 7 |
-
"model_type": "siglip_vision_model",
|
| 8 |
-
"num_attention_heads": 16,
|
| 9 |
-
"num_hidden_layers": 27,
|
| 10 |
-
"patch_size": 16,
|
| 11 |
-
"image_mean": [0.5, 0.5, 0.5],
|
| 12 |
-
"image_std": [0.5, 0.5, 0.5]
|
| 13 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/comfy_types/README.md
DELETED
|
@@ -1,43 +0,0 @@
|
|
| 1 |
-
# Comfy Typing
|
| 2 |
-
## Type hinting for ComfyUI Node development
|
| 3 |
-
|
| 4 |
-
This module provides type hinting and concrete convenience types for node developers.
|
| 5 |
-
If cloned to the custom_nodes directory of ComfyUI, types can be imported using:
|
| 6 |
-
|
| 7 |
-
```python
|
| 8 |
-
from comfy.comfy_types import IO, ComfyNodeABC, CheckLazyMixin
|
| 9 |
-
|
| 10 |
-
class ExampleNode(ComfyNodeABC):
|
| 11 |
-
@classmethod
|
| 12 |
-
def INPUT_TYPES(s) -> InputTypeDict:
|
| 13 |
-
return {"required": {}}
|
| 14 |
-
```
|
| 15 |
-
|
| 16 |
-
Full example is in [examples/example_nodes.py](examples/example_nodes.py).
|
| 17 |
-
|
| 18 |
-
# Types
|
| 19 |
-
A few primary types are documented below. More complete information is available via the docstrings on each type.
|
| 20 |
-
|
| 21 |
-
## `IO`
|
| 22 |
-
|
| 23 |
-
A string enum of built-in and a few custom data types. Includes the following special types and their requisite plumbing:
|
| 24 |
-
|
| 25 |
-
- `ANY`: `"*"`
|
| 26 |
-
- `NUMBER`: `"FLOAT,INT"`
|
| 27 |
-
- `PRIMITIVE`: `"STRING,FLOAT,INT,BOOLEAN"`
|
| 28 |
-
|
| 29 |
-
## `ComfyNodeABC`
|
| 30 |
-
|
| 31 |
-
An abstract base class for nodes, offering type-hinting / autocomplete, and somewhat-alright docstrings.
|
| 32 |
-
|
| 33 |
-
### Type hinting for `INPUT_TYPES`
|
| 34 |
-
|
| 35 |
-

|
| 36 |
-
|
| 37 |
-
### `INPUT_TYPES` return dict
|
| 38 |
-
|
| 39 |
-

|
| 40 |
-
|
| 41 |
-
### Options for individual inputs
|
| 42 |
-
|
| 43 |
-

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/comfy_types/__init__.py
DELETED
|
@@ -1,46 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
from typing import Callable, Protocol, TypedDict, Optional, List
|
| 3 |
-
from .node_typing import IO, InputTypeDict, ComfyNodeABC, CheckLazyMixin, FileLocator
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
class UnetApplyFunction(Protocol):
|
| 7 |
-
"""Function signature protocol on comfy.model_base.BaseModel.apply_model"""
|
| 8 |
-
|
| 9 |
-
def __call__(self, x: torch.Tensor, t: torch.Tensor, **kwargs) -> torch.Tensor:
|
| 10 |
-
pass
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class UnetApplyConds(TypedDict):
|
| 14 |
-
"""Optional conditions for unet apply function."""
|
| 15 |
-
|
| 16 |
-
c_concat: Optional[torch.Tensor]
|
| 17 |
-
c_crossattn: Optional[torch.Tensor]
|
| 18 |
-
control: Optional[torch.Tensor]
|
| 19 |
-
transformer_options: Optional[dict]
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
class UnetParams(TypedDict):
|
| 23 |
-
# Tensor of shape [B, C, H, W]
|
| 24 |
-
input: torch.Tensor
|
| 25 |
-
# Tensor of shape [B]
|
| 26 |
-
timestep: torch.Tensor
|
| 27 |
-
c: UnetApplyConds
|
| 28 |
-
# List of [0, 1], [0], [1], ...
|
| 29 |
-
# 0 means conditional, 1 means conditional unconditional
|
| 30 |
-
cond_or_uncond: List[int]
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
UnetWrapperFunction = Callable[[UnetApplyFunction, UnetParams], torch.Tensor]
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
__all__ = [
|
| 37 |
-
"UnetWrapperFunction",
|
| 38 |
-
UnetApplyConds.__name__,
|
| 39 |
-
UnetParams.__name__,
|
| 40 |
-
UnetApplyFunction.__name__,
|
| 41 |
-
IO.__name__,
|
| 42 |
-
InputTypeDict.__name__,
|
| 43 |
-
ComfyNodeABC.__name__,
|
| 44 |
-
CheckLazyMixin.__name__,
|
| 45 |
-
FileLocator.__name__,
|
| 46 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/comfy_types/examples/example_nodes.py
DELETED
|
@@ -1,28 +0,0 @@
|
|
| 1 |
-
from comfy.comfy_types import IO, ComfyNodeABC, InputTypeDict
|
| 2 |
-
from inspect import cleandoc
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
class ExampleNode(ComfyNodeABC):
|
| 6 |
-
"""An example node that just adds 1 to an input integer.
|
| 7 |
-
|
| 8 |
-
* Requires a modern IDE to provide any benefit (detail: an IDE configured with analysis paths etc).
|
| 9 |
-
* This node is intended as an example for developers only.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
DESCRIPTION = cleandoc(__doc__)
|
| 13 |
-
CATEGORY = "examples"
|
| 14 |
-
|
| 15 |
-
@classmethod
|
| 16 |
-
def INPUT_TYPES(s) -> InputTypeDict:
|
| 17 |
-
return {
|
| 18 |
-
"required": {
|
| 19 |
-
"input_int": (IO.INT, {"defaultInput": True}),
|
| 20 |
-
}
|
| 21 |
-
}
|
| 22 |
-
|
| 23 |
-
RETURN_TYPES = (IO.INT,)
|
| 24 |
-
RETURN_NAMES = ("input_plus_one",)
|
| 25 |
-
FUNCTION = "execute"
|
| 26 |
-
|
| 27 |
-
def execute(self, input_int: int):
|
| 28 |
-
return (input_int + 1,)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/comfy_types/examples/input_options.png
DELETED
Git LFS Details
|
comfy/comfy_types/examples/input_types.png
DELETED
Git LFS Details
|
comfy/comfy_types/examples/required_hint.png
DELETED
Git LFS Details
|
comfy/comfy_types/node_typing.py
DELETED
|
@@ -1,350 +0,0 @@
|
|
| 1 |
-
"""Comfy-specific type hinting"""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
from typing import Literal, TypedDict, Optional
|
| 5 |
-
from typing_extensions import NotRequired
|
| 6 |
-
from abc import ABC, abstractmethod
|
| 7 |
-
from enum import Enum
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
class StrEnum(str, Enum):
|
| 11 |
-
"""Base class for string enums. Python's StrEnum is not available until 3.11."""
|
| 12 |
-
|
| 13 |
-
def __str__(self) -> str:
|
| 14 |
-
return self.value
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
class IO(StrEnum):
|
| 18 |
-
"""Node input/output data types.
|
| 19 |
-
|
| 20 |
-
Includes functionality for ``"*"`` (`ANY`) and ``"MULTI,TYPES"``.
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
-
STRING = "STRING"
|
| 24 |
-
IMAGE = "IMAGE"
|
| 25 |
-
MASK = "MASK"
|
| 26 |
-
LATENT = "LATENT"
|
| 27 |
-
BOOLEAN = "BOOLEAN"
|
| 28 |
-
INT = "INT"
|
| 29 |
-
FLOAT = "FLOAT"
|
| 30 |
-
COMBO = "COMBO"
|
| 31 |
-
CONDITIONING = "CONDITIONING"
|
| 32 |
-
SAMPLER = "SAMPLER"
|
| 33 |
-
SIGMAS = "SIGMAS"
|
| 34 |
-
GUIDER = "GUIDER"
|
| 35 |
-
NOISE = "NOISE"
|
| 36 |
-
CLIP = "CLIP"
|
| 37 |
-
CONTROL_NET = "CONTROL_NET"
|
| 38 |
-
VAE = "VAE"
|
| 39 |
-
MODEL = "MODEL"
|
| 40 |
-
LORA_MODEL = "LORA_MODEL"
|
| 41 |
-
LOSS_MAP = "LOSS_MAP"
|
| 42 |
-
CLIP_VISION = "CLIP_VISION"
|
| 43 |
-
CLIP_VISION_OUTPUT = "CLIP_VISION_OUTPUT"
|
| 44 |
-
STYLE_MODEL = "STYLE_MODEL"
|
| 45 |
-
GLIGEN = "GLIGEN"
|
| 46 |
-
UPSCALE_MODEL = "UPSCALE_MODEL"
|
| 47 |
-
AUDIO = "AUDIO"
|
| 48 |
-
WEBCAM = "WEBCAM"
|
| 49 |
-
POINT = "POINT"
|
| 50 |
-
FACE_ANALYSIS = "FACE_ANALYSIS"
|
| 51 |
-
BBOX = "BBOX"
|
| 52 |
-
SEGS = "SEGS"
|
| 53 |
-
VIDEO = "VIDEO"
|
| 54 |
-
|
| 55 |
-
ANY = "*"
|
| 56 |
-
"""Always matches any type, but at a price.
|
| 57 |
-
|
| 58 |
-
Causes some functionality issues (e.g. reroutes, link types), and should be avoided whenever possible.
|
| 59 |
-
"""
|
| 60 |
-
NUMBER = "FLOAT,INT"
|
| 61 |
-
"""A float or an int - could be either"""
|
| 62 |
-
PRIMITIVE = "STRING,FLOAT,INT,BOOLEAN"
|
| 63 |
-
"""Could be any of: string, float, int, or bool"""
|
| 64 |
-
|
| 65 |
-
def __ne__(self, value: object) -> bool:
|
| 66 |
-
if self == "*" or value == "*":
|
| 67 |
-
return False
|
| 68 |
-
if not isinstance(value, str):
|
| 69 |
-
return True
|
| 70 |
-
a = frozenset(self.split(","))
|
| 71 |
-
b = frozenset(value.split(","))
|
| 72 |
-
return not (b.issubset(a) or a.issubset(b))
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
class RemoteInputOptions(TypedDict):
|
| 76 |
-
route: str
|
| 77 |
-
"""The route to the remote source."""
|
| 78 |
-
refresh_button: bool
|
| 79 |
-
"""Specifies whether to show a refresh button in the UI below the widget."""
|
| 80 |
-
control_after_refresh: Literal["first", "last"]
|
| 81 |
-
"""Specifies the control after the refresh button is clicked. If "first", the first item will be automatically selected, and so on."""
|
| 82 |
-
timeout: int
|
| 83 |
-
"""The maximum amount of time to wait for a response from the remote source in milliseconds."""
|
| 84 |
-
max_retries: int
|
| 85 |
-
"""The maximum number of retries before aborting the request."""
|
| 86 |
-
refresh: int
|
| 87 |
-
"""The TTL of the remote input's value in milliseconds. Specifies the interval at which the remote input's value is refreshed."""
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
class MultiSelectOptions(TypedDict):
|
| 91 |
-
placeholder: NotRequired[str]
|
| 92 |
-
"""The placeholder text to display in the multi-select widget when no items are selected."""
|
| 93 |
-
chip: NotRequired[bool]
|
| 94 |
-
"""Specifies whether to use chips instead of comma separated values for the multi-select widget."""
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
class InputTypeOptions(TypedDict):
|
| 98 |
-
"""Provides type hinting for the return type of the INPUT_TYPES node function.
|
| 99 |
-
|
| 100 |
-
Due to IDE limitations with unions, for now all options are available for all types (e.g. `label_on` is hinted even when the type is not `IO.BOOLEAN`).
|
| 101 |
-
|
| 102 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/datatypes
|
| 103 |
-
"""
|
| 104 |
-
|
| 105 |
-
default: NotRequired[bool | str | float | int | list | tuple]
|
| 106 |
-
"""The default value of the widget"""
|
| 107 |
-
defaultInput: NotRequired[bool]
|
| 108 |
-
"""@deprecated in v1.16 frontend. v1.16 frontend allows input socket and widget to co-exist.
|
| 109 |
-
- defaultInput on required inputs should be dropped.
|
| 110 |
-
- defaultInput on optional inputs should be replaced with forceInput.
|
| 111 |
-
Ref: https://github.com/Comfy-Org/ComfyUI_frontend/pull/3364
|
| 112 |
-
"""
|
| 113 |
-
forceInput: NotRequired[bool]
|
| 114 |
-
"""Forces the input to be an input slot rather than a widget even a widget is available for the input type."""
|
| 115 |
-
lazy: NotRequired[bool]
|
| 116 |
-
"""Declares that this input uses lazy evaluation"""
|
| 117 |
-
rawLink: NotRequired[bool]
|
| 118 |
-
"""When a link exists, rather than receiving the evaluated value, you will receive the link (i.e. `["nodeId", <outputIndex>]`). Designed for node expansion."""
|
| 119 |
-
tooltip: NotRequired[str]
|
| 120 |
-
"""Tooltip for the input (or widget), shown on pointer hover"""
|
| 121 |
-
socketless: NotRequired[bool]
|
| 122 |
-
"""All inputs (including widgets) have an input socket to connect links. When ``true``, if there is a widget for this input, no socket will be created.
|
| 123 |
-
Available from frontend v1.17.5
|
| 124 |
-
Ref: https://github.com/Comfy-Org/ComfyUI_frontend/pull/3548
|
| 125 |
-
"""
|
| 126 |
-
widgetType: NotRequired[str]
|
| 127 |
-
"""Specifies a type to be used for widget initialization if different from the input type.
|
| 128 |
-
Available from frontend v1.18.0
|
| 129 |
-
https://github.com/Comfy-Org/ComfyUI_frontend/pull/3550"""
|
| 130 |
-
# class InputTypeNumber(InputTypeOptions):
|
| 131 |
-
# default: float | int
|
| 132 |
-
min: NotRequired[float]
|
| 133 |
-
"""The minimum value of a number (``FLOAT`` | ``INT``)"""
|
| 134 |
-
max: NotRequired[float]
|
| 135 |
-
"""The maximum value of a number (``FLOAT`` | ``INT``)"""
|
| 136 |
-
step: NotRequired[float]
|
| 137 |
-
"""The amount to increment or decrement a widget by when stepping up/down (``FLOAT`` | ``INT``)"""
|
| 138 |
-
round: NotRequired[float]
|
| 139 |
-
"""Floats are rounded by this value (``FLOAT``)"""
|
| 140 |
-
# class InputTypeBoolean(InputTypeOptions):
|
| 141 |
-
# default: bool
|
| 142 |
-
label_on: NotRequired[str]
|
| 143 |
-
"""The label to use in the UI when the bool is True (``BOOLEAN``)"""
|
| 144 |
-
label_off: NotRequired[str]
|
| 145 |
-
"""The label to use in the UI when the bool is False (``BOOLEAN``)"""
|
| 146 |
-
# class InputTypeString(InputTypeOptions):
|
| 147 |
-
# default: str
|
| 148 |
-
multiline: NotRequired[bool]
|
| 149 |
-
"""Use a multiline text box (``STRING``)"""
|
| 150 |
-
placeholder: NotRequired[str]
|
| 151 |
-
"""Placeholder text to display in the UI when empty (``STRING``)"""
|
| 152 |
-
# Deprecated:
|
| 153 |
-
# defaultVal: str
|
| 154 |
-
dynamicPrompts: NotRequired[bool]
|
| 155 |
-
"""Causes the front-end to evaluate dynamic prompts (``STRING``)"""
|
| 156 |
-
# class InputTypeCombo(InputTypeOptions):
|
| 157 |
-
image_upload: NotRequired[bool]
|
| 158 |
-
"""Specifies whether the input should have an image upload button and image preview attached to it. Requires that the input's name is `image`."""
|
| 159 |
-
image_folder: NotRequired[Literal["input", "output", "temp"]]
|
| 160 |
-
"""Specifies which folder to get preview images from if the input has the ``image_upload`` flag.
|
| 161 |
-
"""
|
| 162 |
-
remote: NotRequired[RemoteInputOptions]
|
| 163 |
-
"""Specifies the configuration for a remote input.
|
| 164 |
-
Available after ComfyUI frontend v1.9.7
|
| 165 |
-
https://github.com/Comfy-Org/ComfyUI_frontend/pull/2422"""
|
| 166 |
-
control_after_generate: NotRequired[bool]
|
| 167 |
-
"""Specifies whether a control widget should be added to the input, adding options to automatically change the value after each prompt is queued. Currently only used for INT and COMBO types."""
|
| 168 |
-
options: NotRequired[list[str | int | float]]
|
| 169 |
-
"""COMBO type only. Specifies the selectable options for the combo widget.
|
| 170 |
-
Prefer:
|
| 171 |
-
["COMBO", {"options": ["Option 1", "Option 2", "Option 3"]}]
|
| 172 |
-
Over:
|
| 173 |
-
[["Option 1", "Option 2", "Option 3"]]
|
| 174 |
-
"""
|
| 175 |
-
multi_select: NotRequired[MultiSelectOptions]
|
| 176 |
-
"""COMBO type only. Specifies the configuration for a multi-select widget.
|
| 177 |
-
Available after ComfyUI frontend v1.13.4
|
| 178 |
-
https://github.com/Comfy-Org/ComfyUI_frontend/pull/2987"""
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
class HiddenInputTypeDict(TypedDict):
|
| 182 |
-
"""Provides type hinting for the hidden entry of node INPUT_TYPES."""
|
| 183 |
-
|
| 184 |
-
node_id: NotRequired[Literal["UNIQUE_ID"]]
|
| 185 |
-
"""UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages)."""
|
| 186 |
-
unique_id: NotRequired[Literal["UNIQUE_ID"]]
|
| 187 |
-
"""UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages)."""
|
| 188 |
-
prompt: NotRequired[Literal["PROMPT"]]
|
| 189 |
-
"""PROMPT is the complete prompt sent by the client to the server. See the prompt object for a full description."""
|
| 190 |
-
extra_pnginfo: NotRequired[Literal["EXTRA_PNGINFO"]]
|
| 191 |
-
"""EXTRA_PNGINFO is a dictionary that will be copied into the metadata of any .png files saved. Custom nodes can store additional information in this dictionary for saving (or as a way to communicate with a downstream node)."""
|
| 192 |
-
dynprompt: NotRequired[Literal["DYNPROMPT"]]
|
| 193 |
-
"""DYNPROMPT is an instance of comfy_execution.graph.DynamicPrompt. It differs from PROMPT in that it may mutate during the course of execution in response to Node Expansion."""
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
class InputTypeDict(TypedDict):
|
| 197 |
-
"""Provides type hinting for node INPUT_TYPES.
|
| 198 |
-
|
| 199 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/more_on_inputs
|
| 200 |
-
"""
|
| 201 |
-
|
| 202 |
-
required: NotRequired[dict[str, tuple[IO, InputTypeOptions]]]
|
| 203 |
-
"""Describes all inputs that must be connected for the node to execute."""
|
| 204 |
-
optional: NotRequired[dict[str, tuple[IO, InputTypeOptions]]]
|
| 205 |
-
"""Describes inputs which do not need to be connected."""
|
| 206 |
-
hidden: NotRequired[HiddenInputTypeDict]
|
| 207 |
-
"""Offers advanced functionality and server-client communication.
|
| 208 |
-
|
| 209 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/more_on_inputs#hidden-inputs
|
| 210 |
-
"""
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
class ComfyNodeABC(ABC):
|
| 214 |
-
"""Abstract base class for Comfy nodes. Includes the names and expected types of attributes.
|
| 215 |
-
|
| 216 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview
|
| 217 |
-
"""
|
| 218 |
-
|
| 219 |
-
DESCRIPTION: str
|
| 220 |
-
"""Node description, shown as a tooltip when hovering over the node.
|
| 221 |
-
|
| 222 |
-
Usage::
|
| 223 |
-
|
| 224 |
-
# Explicitly define the description
|
| 225 |
-
DESCRIPTION = "Example description here."
|
| 226 |
-
|
| 227 |
-
# Use the docstring of the node class.
|
| 228 |
-
DESCRIPTION = cleandoc(__doc__)
|
| 229 |
-
"""
|
| 230 |
-
CATEGORY: str
|
| 231 |
-
"""The category of the node, as per the "Add Node" menu.
|
| 232 |
-
|
| 233 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#category
|
| 234 |
-
"""
|
| 235 |
-
EXPERIMENTAL: bool
|
| 236 |
-
"""Flags a node as experimental, informing users that it may change or not work as expected."""
|
| 237 |
-
DEPRECATED: bool
|
| 238 |
-
"""Flags a node as deprecated, indicating to users that they should find alternatives to this node."""
|
| 239 |
-
API_NODE: Optional[bool]
|
| 240 |
-
"""Flags a node as an API node. See: https://docs.comfy.org/tutorials/api-nodes/overview."""
|
| 241 |
-
|
| 242 |
-
@classmethod
|
| 243 |
-
@abstractmethod
|
| 244 |
-
def INPUT_TYPES(s) -> InputTypeDict:
|
| 245 |
-
"""Defines node inputs.
|
| 246 |
-
|
| 247 |
-
* Must include the ``required`` key, which describes all inputs that must be connected for the node to execute.
|
| 248 |
-
* The ``optional`` key can be added to describe inputs which do not need to be connected.
|
| 249 |
-
* The ``hidden`` key offers some advanced functionality. More info at: https://docs.comfy.org/custom-nodes/backend/more_on_inputs#hidden-inputs
|
| 250 |
-
|
| 251 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#input-types
|
| 252 |
-
"""
|
| 253 |
-
return {"required": {}}
|
| 254 |
-
|
| 255 |
-
OUTPUT_NODE: bool
|
| 256 |
-
"""Flags this node as an output node, causing any inputs it requires to be executed.
|
| 257 |
-
|
| 258 |
-
If a node is not connected to any output nodes, that node will not be executed. Usage::
|
| 259 |
-
|
| 260 |
-
OUTPUT_NODE = True
|
| 261 |
-
|
| 262 |
-
From the docs:
|
| 263 |
-
|
| 264 |
-
By default, a node is not considered an output. Set ``OUTPUT_NODE = True`` to specify that it is.
|
| 265 |
-
|
| 266 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#output-node
|
| 267 |
-
"""
|
| 268 |
-
INPUT_IS_LIST: bool
|
| 269 |
-
"""A flag indicating if this node implements the additional code necessary to deal with OUTPUT_IS_LIST nodes.
|
| 270 |
-
|
| 271 |
-
All inputs of ``type`` will become ``list[type]``, regardless of how many items are passed in. This also affects ``check_lazy_status``.
|
| 272 |
-
|
| 273 |
-
From the docs:
|
| 274 |
-
|
| 275 |
-
A node can also override the default input behaviour and receive the whole list in a single call. This is done by setting a class attribute `INPUT_IS_LIST` to ``True``.
|
| 276 |
-
|
| 277 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lists#list-processing
|
| 278 |
-
"""
|
| 279 |
-
OUTPUT_IS_LIST: tuple[bool, ...]
|
| 280 |
-
"""A tuple indicating which node outputs are lists, but will be connected to nodes that expect individual items.
|
| 281 |
-
|
| 282 |
-
Connected nodes that do not implement `INPUT_IS_LIST` will be executed once for every item in the list.
|
| 283 |
-
|
| 284 |
-
A ``tuple[bool]``, where the items match those in `RETURN_TYPES`::
|
| 285 |
-
|
| 286 |
-
RETURN_TYPES = (IO.INT, IO.INT, IO.STRING)
|
| 287 |
-
OUTPUT_IS_LIST = (True, True, False) # The string output will be handled normally
|
| 288 |
-
|
| 289 |
-
From the docs:
|
| 290 |
-
|
| 291 |
-
In order to tell Comfy that the list being returned should not be wrapped, but treated as a series of data for sequential processing,
|
| 292 |
-
the node should provide a class attribute `OUTPUT_IS_LIST`, which is a ``tuple[bool]``, of the same length as `RETURN_TYPES`,
|
| 293 |
-
specifying which outputs which should be so treated.
|
| 294 |
-
|
| 295 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lists#list-processing
|
| 296 |
-
"""
|
| 297 |
-
|
| 298 |
-
RETURN_TYPES: tuple[IO, ...]
|
| 299 |
-
"""A tuple representing the outputs of this node.
|
| 300 |
-
|
| 301 |
-
Usage::
|
| 302 |
-
|
| 303 |
-
RETURN_TYPES = (IO.INT, "INT", "CUSTOM_TYPE")
|
| 304 |
-
|
| 305 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#return-types
|
| 306 |
-
"""
|
| 307 |
-
RETURN_NAMES: tuple[str, ...]
|
| 308 |
-
"""The output slot names for each item in `RETURN_TYPES`, e.g. ``RETURN_NAMES = ("count", "filter_string")``
|
| 309 |
-
|
| 310 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#return-names
|
| 311 |
-
"""
|
| 312 |
-
OUTPUT_TOOLTIPS: tuple[str, ...]
|
| 313 |
-
"""A tuple of strings to use as tooltips for node outputs, one for each item in `RETURN_TYPES`."""
|
| 314 |
-
FUNCTION: str
|
| 315 |
-
"""The name of the function to execute as a literal string, e.g. `FUNCTION = "execute"`
|
| 316 |
-
|
| 317 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#function
|
| 318 |
-
"""
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
class CheckLazyMixin:
|
| 322 |
-
"""Provides a basic check_lazy_status implementation and type hinting for nodes that use lazy inputs."""
|
| 323 |
-
|
| 324 |
-
def check_lazy_status(self, **kwargs) -> list[str]:
|
| 325 |
-
"""Returns a list of input names that should be evaluated.
|
| 326 |
-
|
| 327 |
-
This basic mixin impl. requires all inputs.
|
| 328 |
-
|
| 329 |
-
:kwargs: All node inputs will be included here. If the input is ``None``, it should be assumed that it has not yet been evaluated. \
|
| 330 |
-
When using ``INPUT_IS_LIST = True``, unevaluated will instead be ``(None,)``.
|
| 331 |
-
|
| 332 |
-
Params should match the nodes execution ``FUNCTION`` (self, and all inputs by name).
|
| 333 |
-
Will be executed repeatedly until it returns an empty list, or all requested items were already evaluated (and sent as params).
|
| 334 |
-
|
| 335 |
-
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lazy_evaluation#defining-check-lazy-status
|
| 336 |
-
"""
|
| 337 |
-
|
| 338 |
-
need = [name for name in kwargs if kwargs[name] is None]
|
| 339 |
-
return need
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
class FileLocator(TypedDict):
|
| 343 |
-
"""Provides type hinting for the file location"""
|
| 344 |
-
|
| 345 |
-
filename: str
|
| 346 |
-
"""The filename of the file."""
|
| 347 |
-
subfolder: str
|
| 348 |
-
"""The subfolder of the file."""
|
| 349 |
-
type: Literal["input", "output", "temp"]
|
| 350 |
-
"""The root folder of the file."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
comfy/conds.py
DELETED
|
@@ -1,130 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import math
|
| 3 |
-
import comfy.utils
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
class CONDRegular:
|
| 7 |
-
def __init__(self, cond):
|
| 8 |
-
self.cond = cond
|
| 9 |
-
|
| 10 |
-
def _copy_with(self, cond):
|
| 11 |
-
return self.__class__(cond)
|
| 12 |
-
|
| 13 |
-
def process_cond(self, batch_size, device, **kwargs):
|
| 14 |
-
return self._copy_with(comfy.utils.repeat_to_batch_size(self.cond, batch_size).to(device))
|
| 15 |
-
|
| 16 |
-
def can_concat(self, other):
|
| 17 |
-
if self.cond.shape != other.cond.shape:
|
| 18 |
-
return False
|
| 19 |
-
return True
|
| 20 |
-
|
| 21 |
-
def concat(self, others):
|
| 22 |
-
conds = [self.cond]
|
| 23 |
-
for x in others:
|
| 24 |
-
conds.append(x.cond)
|
| 25 |
-
return torch.cat(conds)
|
| 26 |
-
|
| 27 |
-
def size(self):
|
| 28 |
-
return list(self.cond.size())
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class CONDNoiseShape(CONDRegular):
|
| 32 |
-
def process_cond(self, batch_size, device, area, **kwargs):
|
| 33 |
-
data = self.cond
|
| 34 |
-
if area is not None:
|
| 35 |
-
dims = len(area) // 2
|
| 36 |
-
for i in range(dims):
|
| 37 |
-
data = data.narrow(i + 2, area[i + dims], area[i])
|
| 38 |
-
|
| 39 |
-
return self._copy_with(comfy.utils.repeat_to_batch_size(data, batch_size).to(device))
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
class CONDCrossAttn(CONDRegular):
|
| 43 |
-
def can_concat(self, other):
|
| 44 |
-
s1 = self.cond.shape
|
| 45 |
-
s2 = other.cond.shape
|
| 46 |
-
if s1 != s2:
|
| 47 |
-
if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
|
| 48 |
-
return False
|
| 49 |
-
|
| 50 |
-
mult_min = math.lcm(s1[1], s2[1])
|
| 51 |
-
diff = mult_min // min(s1[1], s2[1])
|
| 52 |
-
if diff > 4: #arbitrary limit on the padding because it's probably going to impact performance negatively if it's too much
|
| 53 |
-
return False
|
| 54 |
-
return True
|
| 55 |
-
|
| 56 |
-
def concat(self, others):
|
| 57 |
-
conds = [self.cond]
|
| 58 |
-
crossattn_max_len = self.cond.shape[1]
|
| 59 |
-
for x in others:
|
| 60 |
-
c = x.cond
|
| 61 |
-
crossattn_max_len = math.lcm(crossattn_max_len, c.shape[1])
|
| 62 |
-
conds.append(c)
|
| 63 |
-
|
| 64 |
-
out = []
|
| 65 |
-
for c in conds:
|
| 66 |
-
if c.shape[1] < crossattn_max_len:
|
| 67 |
-
c = c.repeat(1, crossattn_max_len // c.shape[1], 1) #padding with repeat doesn't change result
|
| 68 |
-
out.append(c)
|
| 69 |
-
return torch.cat(out)
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
class CONDConstant(CONDRegular):
|
| 73 |
-
def __init__(self, cond):
|
| 74 |
-
self.cond = cond
|
| 75 |
-
|
| 76 |
-
def process_cond(self, batch_size, device, **kwargs):
|
| 77 |
-
return self._copy_with(self.cond)
|
| 78 |
-
|
| 79 |
-
def can_concat(self, other):
|
| 80 |
-
if self.cond != other.cond:
|
| 81 |
-
return False
|
| 82 |
-
return True
|
| 83 |
-
|
| 84 |
-
def concat(self, others):
|
| 85 |
-
return self.cond
|
| 86 |
-
|
| 87 |
-
def size(self):
|
| 88 |
-
return [1]
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
class CONDList(CONDRegular):
|
| 92 |
-
def __init__(self, cond):
|
| 93 |
-
self.cond = cond
|
| 94 |
-
|
| 95 |
-
def process_cond(self, batch_size, device, **kwargs):
|
| 96 |
-
out = []
|
| 97 |
-
for c in self.cond:
|
| 98 |
-
out.append(comfy.utils.repeat_to_batch_size(c, batch_size).to(device))
|
| 99 |
-
|
| 100 |
-
return self._copy_with(out)
|
| 101 |
-
|
| 102 |
-
def can_concat(self, other):
|
| 103 |
-
if len(self.cond) != len(other.cond):
|
| 104 |
-
return False
|
| 105 |
-
for i in range(len(self.cond)):
|
| 106 |
-
if self.cond[i].shape != other.cond[i].shape:
|
| 107 |
-
return False
|
| 108 |
-
|
| 109 |
-
return True
|
| 110 |
-
|
| 111 |
-
def concat(self, others):
|
| 112 |
-
out = []
|
| 113 |
-
for i in range(len(self.cond)):
|
| 114 |
-
o = [self.cond[i]]
|
| 115 |
-
for x in others:
|
| 116 |
-
o.append(x.cond[i])
|
| 117 |
-
out.append(torch.cat(o))
|
| 118 |
-
|
| 119 |
-
return out
|
| 120 |
-
|
| 121 |
-
def size(self): # hackish implementation to make the mem estimation work
|
| 122 |
-
o = 0
|
| 123 |
-
c = 1
|
| 124 |
-
for c in self.cond:
|
| 125 |
-
size = c.size()
|
| 126 |
-
o += math.prod(size)
|
| 127 |
-
if len(size) > 1:
|
| 128 |
-
c = size[1]
|
| 129 |
-
|
| 130 |
-
return [1, c, o // c]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/controlnet.py
DELETED
|
@@ -1,858 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
This file is part of ComfyUI.
|
| 3 |
-
Copyright (C) 2024 Comfy
|
| 4 |
-
|
| 5 |
-
This program is free software: you can redistribute it and/or modify
|
| 6 |
-
it under the terms of the GNU General Public License as published by
|
| 7 |
-
the Free Software Foundation, either version 3 of the License, or
|
| 8 |
-
(at your option) any later version.
|
| 9 |
-
|
| 10 |
-
This program is distributed in the hope that it will be useful,
|
| 11 |
-
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 12 |
-
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 13 |
-
GNU General Public License for more details.
|
| 14 |
-
|
| 15 |
-
You should have received a copy of the GNU General Public License
|
| 16 |
-
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 17 |
-
"""
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
import torch
|
| 21 |
-
from enum import Enum
|
| 22 |
-
import math
|
| 23 |
-
import os
|
| 24 |
-
import logging
|
| 25 |
-
import comfy.utils
|
| 26 |
-
import comfy.model_management
|
| 27 |
-
import comfy.model_detection
|
| 28 |
-
import comfy.model_patcher
|
| 29 |
-
import comfy.ops
|
| 30 |
-
import comfy.latent_formats
|
| 31 |
-
|
| 32 |
-
import comfy.cldm.cldm
|
| 33 |
-
import comfy.t2i_adapter.adapter
|
| 34 |
-
import comfy.ldm.cascade.controlnet
|
| 35 |
-
import comfy.cldm.mmdit
|
| 36 |
-
import comfy.ldm.hydit.controlnet
|
| 37 |
-
import comfy.ldm.flux.controlnet
|
| 38 |
-
import comfy.cldm.dit_embedder
|
| 39 |
-
from typing import TYPE_CHECKING
|
| 40 |
-
if TYPE_CHECKING:
|
| 41 |
-
from comfy.hooks import HookGroup
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def broadcast_image_to(tensor, target_batch_size, batched_number):
|
| 45 |
-
current_batch_size = tensor.shape[0]
|
| 46 |
-
#print(current_batch_size, target_batch_size)
|
| 47 |
-
if current_batch_size == 1:
|
| 48 |
-
return tensor
|
| 49 |
-
|
| 50 |
-
per_batch = target_batch_size // batched_number
|
| 51 |
-
tensor = tensor[:per_batch]
|
| 52 |
-
|
| 53 |
-
if per_batch > tensor.shape[0]:
|
| 54 |
-
tensor = torch.cat([tensor] * (per_batch // tensor.shape[0]) + [tensor[:(per_batch % tensor.shape[0])]], dim=0)
|
| 55 |
-
|
| 56 |
-
current_batch_size = tensor.shape[0]
|
| 57 |
-
if current_batch_size == target_batch_size:
|
| 58 |
-
return tensor
|
| 59 |
-
else:
|
| 60 |
-
return torch.cat([tensor] * batched_number, dim=0)
|
| 61 |
-
|
| 62 |
-
class StrengthType(Enum):
|
| 63 |
-
CONSTANT = 1
|
| 64 |
-
LINEAR_UP = 2
|
| 65 |
-
|
| 66 |
-
class ControlBase:
|
| 67 |
-
def __init__(self):
|
| 68 |
-
self.cond_hint_original = None
|
| 69 |
-
self.cond_hint = None
|
| 70 |
-
self.strength = 1.0
|
| 71 |
-
self.timestep_percent_range = (0.0, 1.0)
|
| 72 |
-
self.latent_format = None
|
| 73 |
-
self.vae = None
|
| 74 |
-
self.global_average_pooling = False
|
| 75 |
-
self.timestep_range = None
|
| 76 |
-
self.compression_ratio = 8
|
| 77 |
-
self.upscale_algorithm = 'nearest-exact'
|
| 78 |
-
self.extra_args = {}
|
| 79 |
-
self.previous_controlnet = None
|
| 80 |
-
self.extra_conds = []
|
| 81 |
-
self.strength_type = StrengthType.CONSTANT
|
| 82 |
-
self.concat_mask = False
|
| 83 |
-
self.extra_concat_orig = []
|
| 84 |
-
self.extra_concat = None
|
| 85 |
-
self.extra_hooks: HookGroup = None
|
| 86 |
-
self.preprocess_image = lambda a: a
|
| 87 |
-
|
| 88 |
-
def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0), vae=None, extra_concat=[]):
|
| 89 |
-
self.cond_hint_original = cond_hint
|
| 90 |
-
self.strength = strength
|
| 91 |
-
self.timestep_percent_range = timestep_percent_range
|
| 92 |
-
if self.latent_format is not None:
|
| 93 |
-
if vae is None:
|
| 94 |
-
logging.warning("WARNING: no VAE provided to the controlnet apply node when this controlnet requires one.")
|
| 95 |
-
self.vae = vae
|
| 96 |
-
self.extra_concat_orig = extra_concat.copy()
|
| 97 |
-
if self.concat_mask and len(self.extra_concat_orig) == 0:
|
| 98 |
-
self.extra_concat_orig.append(torch.tensor([[[[1.0]]]]))
|
| 99 |
-
return self
|
| 100 |
-
|
| 101 |
-
def pre_run(self, model, percent_to_timestep_function):
|
| 102 |
-
self.timestep_range = (percent_to_timestep_function(self.timestep_percent_range[0]), percent_to_timestep_function(self.timestep_percent_range[1]))
|
| 103 |
-
if self.previous_controlnet is not None:
|
| 104 |
-
self.previous_controlnet.pre_run(model, percent_to_timestep_function)
|
| 105 |
-
|
| 106 |
-
def set_previous_controlnet(self, controlnet):
|
| 107 |
-
self.previous_controlnet = controlnet
|
| 108 |
-
return self
|
| 109 |
-
|
| 110 |
-
def cleanup(self):
|
| 111 |
-
if self.previous_controlnet is not None:
|
| 112 |
-
self.previous_controlnet.cleanup()
|
| 113 |
-
|
| 114 |
-
self.cond_hint = None
|
| 115 |
-
self.extra_concat = None
|
| 116 |
-
self.timestep_range = None
|
| 117 |
-
|
| 118 |
-
def get_models(self):
|
| 119 |
-
out = []
|
| 120 |
-
if self.previous_controlnet is not None:
|
| 121 |
-
out += self.previous_controlnet.get_models()
|
| 122 |
-
return out
|
| 123 |
-
|
| 124 |
-
def get_extra_hooks(self):
|
| 125 |
-
out = []
|
| 126 |
-
if self.extra_hooks is not None:
|
| 127 |
-
out.append(self.extra_hooks)
|
| 128 |
-
if self.previous_controlnet is not None:
|
| 129 |
-
out += self.previous_controlnet.get_extra_hooks()
|
| 130 |
-
return out
|
| 131 |
-
|
| 132 |
-
def copy_to(self, c):
|
| 133 |
-
c.cond_hint_original = self.cond_hint_original
|
| 134 |
-
c.strength = self.strength
|
| 135 |
-
c.timestep_percent_range = self.timestep_percent_range
|
| 136 |
-
c.global_average_pooling = self.global_average_pooling
|
| 137 |
-
c.compression_ratio = self.compression_ratio
|
| 138 |
-
c.upscale_algorithm = self.upscale_algorithm
|
| 139 |
-
c.latent_format = self.latent_format
|
| 140 |
-
c.extra_args = self.extra_args.copy()
|
| 141 |
-
c.vae = self.vae
|
| 142 |
-
c.extra_conds = self.extra_conds.copy()
|
| 143 |
-
c.strength_type = self.strength_type
|
| 144 |
-
c.concat_mask = self.concat_mask
|
| 145 |
-
c.extra_concat_orig = self.extra_concat_orig.copy()
|
| 146 |
-
c.extra_hooks = self.extra_hooks.clone() if self.extra_hooks else None
|
| 147 |
-
c.preprocess_image = self.preprocess_image
|
| 148 |
-
|
| 149 |
-
def inference_memory_requirements(self, dtype):
|
| 150 |
-
if self.previous_controlnet is not None:
|
| 151 |
-
return self.previous_controlnet.inference_memory_requirements(dtype)
|
| 152 |
-
return 0
|
| 153 |
-
|
| 154 |
-
def control_merge(self, control, control_prev, output_dtype):
|
| 155 |
-
out = {'input':[], 'middle':[], 'output': []}
|
| 156 |
-
|
| 157 |
-
for key in control:
|
| 158 |
-
control_output = control[key]
|
| 159 |
-
applied_to = set()
|
| 160 |
-
for i in range(len(control_output)):
|
| 161 |
-
x = control_output[i]
|
| 162 |
-
if x is not None:
|
| 163 |
-
if self.global_average_pooling:
|
| 164 |
-
x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
|
| 165 |
-
|
| 166 |
-
if x not in applied_to: #memory saving strategy, allow shared tensors and only apply strength to shared tensors once
|
| 167 |
-
applied_to.add(x)
|
| 168 |
-
if self.strength_type == StrengthType.CONSTANT:
|
| 169 |
-
x *= self.strength
|
| 170 |
-
elif self.strength_type == StrengthType.LINEAR_UP:
|
| 171 |
-
x *= (self.strength ** float(len(control_output) - i))
|
| 172 |
-
|
| 173 |
-
if output_dtype is not None and x.dtype != output_dtype:
|
| 174 |
-
x = x.to(output_dtype)
|
| 175 |
-
|
| 176 |
-
out[key].append(x)
|
| 177 |
-
|
| 178 |
-
if control_prev is not None:
|
| 179 |
-
for x in ['input', 'middle', 'output']:
|
| 180 |
-
o = out[x]
|
| 181 |
-
for i in range(len(control_prev[x])):
|
| 182 |
-
prev_val = control_prev[x][i]
|
| 183 |
-
if i >= len(o):
|
| 184 |
-
o.append(prev_val)
|
| 185 |
-
elif prev_val is not None:
|
| 186 |
-
if o[i] is None:
|
| 187 |
-
o[i] = prev_val
|
| 188 |
-
else:
|
| 189 |
-
if o[i].shape[0] < prev_val.shape[0]:
|
| 190 |
-
o[i] = prev_val + o[i]
|
| 191 |
-
else:
|
| 192 |
-
o[i] = prev_val + o[i] #TODO: change back to inplace add if shared tensors stop being an issue
|
| 193 |
-
return out
|
| 194 |
-
|
| 195 |
-
def set_extra_arg(self, argument, value=None):
|
| 196 |
-
self.extra_args[argument] = value
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
class ControlNet(ControlBase):
|
| 200 |
-
def __init__(self, control_model=None, global_average_pooling=False, compression_ratio=8, latent_format=None, load_device=None, manual_cast_dtype=None, extra_conds=["y"], strength_type=StrengthType.CONSTANT, concat_mask=False, preprocess_image=lambda a: a):
|
| 201 |
-
super().__init__()
|
| 202 |
-
self.control_model = control_model
|
| 203 |
-
self.load_device = load_device
|
| 204 |
-
if control_model is not None:
|
| 205 |
-
self.control_model_wrapped = comfy.model_patcher.ModelPatcher(self.control_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
|
| 206 |
-
|
| 207 |
-
self.compression_ratio = compression_ratio
|
| 208 |
-
self.global_average_pooling = global_average_pooling
|
| 209 |
-
self.model_sampling_current = None
|
| 210 |
-
self.manual_cast_dtype = manual_cast_dtype
|
| 211 |
-
self.latent_format = latent_format
|
| 212 |
-
self.extra_conds += extra_conds
|
| 213 |
-
self.strength_type = strength_type
|
| 214 |
-
self.concat_mask = concat_mask
|
| 215 |
-
self.preprocess_image = preprocess_image
|
| 216 |
-
|
| 217 |
-
def get_control(self, x_noisy, t, cond, batched_number, transformer_options):
|
| 218 |
-
control_prev = None
|
| 219 |
-
if self.previous_controlnet is not None:
|
| 220 |
-
control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
|
| 221 |
-
|
| 222 |
-
if self.timestep_range is not None:
|
| 223 |
-
if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
|
| 224 |
-
if control_prev is not None:
|
| 225 |
-
return control_prev
|
| 226 |
-
else:
|
| 227 |
-
return None
|
| 228 |
-
|
| 229 |
-
dtype = self.control_model.dtype
|
| 230 |
-
if self.manual_cast_dtype is not None:
|
| 231 |
-
dtype = self.manual_cast_dtype
|
| 232 |
-
|
| 233 |
-
if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
|
| 234 |
-
if self.cond_hint is not None:
|
| 235 |
-
del self.cond_hint
|
| 236 |
-
self.cond_hint = None
|
| 237 |
-
compression_ratio = self.compression_ratio
|
| 238 |
-
if self.vae is not None:
|
| 239 |
-
compression_ratio *= self.vae.downscale_ratio
|
| 240 |
-
else:
|
| 241 |
-
if self.latent_format is not None:
|
| 242 |
-
raise ValueError("This Controlnet needs a VAE but none was provided, please use a ControlNetApply node with a VAE input and connect it.")
|
| 243 |
-
self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * compression_ratio, x_noisy.shape[2] * compression_ratio, self.upscale_algorithm, "center")
|
| 244 |
-
self.cond_hint = self.preprocess_image(self.cond_hint)
|
| 245 |
-
if self.vae is not None:
|
| 246 |
-
loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
|
| 247 |
-
self.cond_hint = self.vae.encode(self.cond_hint.movedim(1, -1))
|
| 248 |
-
comfy.model_management.load_models_gpu(loaded_models)
|
| 249 |
-
if self.latent_format is not None:
|
| 250 |
-
self.cond_hint = self.latent_format.process_in(self.cond_hint)
|
| 251 |
-
if len(self.extra_concat_orig) > 0:
|
| 252 |
-
to_concat = []
|
| 253 |
-
for c in self.extra_concat_orig:
|
| 254 |
-
c = c.to(self.cond_hint.device)
|
| 255 |
-
c = comfy.utils.common_upscale(c, self.cond_hint.shape[3], self.cond_hint.shape[2], self.upscale_algorithm, "center")
|
| 256 |
-
to_concat.append(comfy.utils.repeat_to_batch_size(c, self.cond_hint.shape[0]))
|
| 257 |
-
self.cond_hint = torch.cat([self.cond_hint] + to_concat, dim=1)
|
| 258 |
-
|
| 259 |
-
self.cond_hint = self.cond_hint.to(device=x_noisy.device, dtype=dtype)
|
| 260 |
-
if x_noisy.shape[0] != self.cond_hint.shape[0]:
|
| 261 |
-
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
|
| 262 |
-
|
| 263 |
-
context = cond.get('crossattn_controlnet', cond['c_crossattn'])
|
| 264 |
-
extra = self.extra_args.copy()
|
| 265 |
-
for c in self.extra_conds:
|
| 266 |
-
temp = cond.get(c, None)
|
| 267 |
-
if temp is not None:
|
| 268 |
-
extra[c] = temp.to(dtype)
|
| 269 |
-
|
| 270 |
-
timestep = self.model_sampling_current.timestep(t)
|
| 271 |
-
x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
|
| 272 |
-
|
| 273 |
-
control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.to(dtype), context=context.to(dtype), **extra)
|
| 274 |
-
return self.control_merge(control, control_prev, output_dtype=None)
|
| 275 |
-
|
| 276 |
-
def copy(self):
|
| 277 |
-
c = ControlNet(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
|
| 278 |
-
c.control_model = self.control_model
|
| 279 |
-
c.control_model_wrapped = self.control_model_wrapped
|
| 280 |
-
self.copy_to(c)
|
| 281 |
-
return c
|
| 282 |
-
|
| 283 |
-
def get_models(self):
|
| 284 |
-
out = super().get_models()
|
| 285 |
-
out.append(self.control_model_wrapped)
|
| 286 |
-
return out
|
| 287 |
-
|
| 288 |
-
def pre_run(self, model, percent_to_timestep_function):
|
| 289 |
-
super().pre_run(model, percent_to_timestep_function)
|
| 290 |
-
self.model_sampling_current = model.model_sampling
|
| 291 |
-
|
| 292 |
-
def cleanup(self):
|
| 293 |
-
self.model_sampling_current = None
|
| 294 |
-
super().cleanup()
|
| 295 |
-
|
| 296 |
-
class ControlLoraOps:
|
| 297 |
-
class Linear(torch.nn.Module, comfy.ops.CastWeightBiasOp):
|
| 298 |
-
def __init__(self, in_features: int, out_features: int, bias: bool = True,
|
| 299 |
-
device=None, dtype=None) -> None:
|
| 300 |
-
super().__init__()
|
| 301 |
-
self.in_features = in_features
|
| 302 |
-
self.out_features = out_features
|
| 303 |
-
self.weight = None
|
| 304 |
-
self.up = None
|
| 305 |
-
self.down = None
|
| 306 |
-
self.bias = None
|
| 307 |
-
|
| 308 |
-
def forward(self, input):
|
| 309 |
-
weight, bias = comfy.ops.cast_bias_weight(self, input)
|
| 310 |
-
if self.up is not None:
|
| 311 |
-
return torch.nn.functional.linear(input, weight + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), bias)
|
| 312 |
-
else:
|
| 313 |
-
return torch.nn.functional.linear(input, weight, bias)
|
| 314 |
-
|
| 315 |
-
class Conv2d(torch.nn.Module, comfy.ops.CastWeightBiasOp):
|
| 316 |
-
def __init__(
|
| 317 |
-
self,
|
| 318 |
-
in_channels,
|
| 319 |
-
out_channels,
|
| 320 |
-
kernel_size,
|
| 321 |
-
stride=1,
|
| 322 |
-
padding=0,
|
| 323 |
-
dilation=1,
|
| 324 |
-
groups=1,
|
| 325 |
-
bias=True,
|
| 326 |
-
padding_mode='zeros',
|
| 327 |
-
device=None,
|
| 328 |
-
dtype=None
|
| 329 |
-
):
|
| 330 |
-
super().__init__()
|
| 331 |
-
self.in_channels = in_channels
|
| 332 |
-
self.out_channels = out_channels
|
| 333 |
-
self.kernel_size = kernel_size
|
| 334 |
-
self.stride = stride
|
| 335 |
-
self.padding = padding
|
| 336 |
-
self.dilation = dilation
|
| 337 |
-
self.transposed = False
|
| 338 |
-
self.output_padding = 0
|
| 339 |
-
self.groups = groups
|
| 340 |
-
self.padding_mode = padding_mode
|
| 341 |
-
|
| 342 |
-
self.weight = None
|
| 343 |
-
self.bias = None
|
| 344 |
-
self.up = None
|
| 345 |
-
self.down = None
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
def forward(self, input):
|
| 349 |
-
weight, bias = comfy.ops.cast_bias_weight(self, input)
|
| 350 |
-
if self.up is not None:
|
| 351 |
-
return torch.nn.functional.conv2d(input, weight + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), bias, self.stride, self.padding, self.dilation, self.groups)
|
| 352 |
-
else:
|
| 353 |
-
return torch.nn.functional.conv2d(input, weight, bias, self.stride, self.padding, self.dilation, self.groups)
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
class ControlLora(ControlNet):
|
| 357 |
-
def __init__(self, control_weights, global_average_pooling=False, model_options={}): #TODO? model_options
|
| 358 |
-
ControlBase.__init__(self)
|
| 359 |
-
self.control_weights = control_weights
|
| 360 |
-
self.global_average_pooling = global_average_pooling
|
| 361 |
-
self.extra_conds += ["y"]
|
| 362 |
-
|
| 363 |
-
def pre_run(self, model, percent_to_timestep_function):
|
| 364 |
-
super().pre_run(model, percent_to_timestep_function)
|
| 365 |
-
controlnet_config = model.model_config.unet_config.copy()
|
| 366 |
-
controlnet_config.pop("out_channels")
|
| 367 |
-
controlnet_config["hint_channels"] = self.control_weights["input_hint_block.0.weight"].shape[1]
|
| 368 |
-
self.manual_cast_dtype = model.manual_cast_dtype
|
| 369 |
-
dtype = model.get_dtype()
|
| 370 |
-
if self.manual_cast_dtype is None:
|
| 371 |
-
class control_lora_ops(ControlLoraOps, comfy.ops.disable_weight_init):
|
| 372 |
-
pass
|
| 373 |
-
else:
|
| 374 |
-
class control_lora_ops(ControlLoraOps, comfy.ops.manual_cast):
|
| 375 |
-
pass
|
| 376 |
-
dtype = self.manual_cast_dtype
|
| 377 |
-
|
| 378 |
-
controlnet_config["operations"] = control_lora_ops
|
| 379 |
-
controlnet_config["dtype"] = dtype
|
| 380 |
-
self.control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
|
| 381 |
-
self.control_model.to(comfy.model_management.get_torch_device())
|
| 382 |
-
diffusion_model = model.diffusion_model
|
| 383 |
-
sd = diffusion_model.state_dict()
|
| 384 |
-
|
| 385 |
-
for k in sd:
|
| 386 |
-
weight = sd[k]
|
| 387 |
-
try:
|
| 388 |
-
comfy.utils.set_attr_param(self.control_model, k, weight)
|
| 389 |
-
except:
|
| 390 |
-
pass
|
| 391 |
-
|
| 392 |
-
for k in self.control_weights:
|
| 393 |
-
if (k not in {"lora_controlnet"}):
|
| 394 |
-
if (k.endswith(".up") or k.endswith(".down") or k.endswith(".weight") or k.endswith(".bias")) and ("__" not in k):
|
| 395 |
-
comfy.utils.set_attr_param(self.control_model, k, self.control_weights[k].to(dtype).to(comfy.model_management.get_torch_device()))
|
| 396 |
-
|
| 397 |
-
def copy(self):
|
| 398 |
-
c = ControlLora(self.control_weights, global_average_pooling=self.global_average_pooling)
|
| 399 |
-
self.copy_to(c)
|
| 400 |
-
return c
|
| 401 |
-
|
| 402 |
-
def cleanup(self):
|
| 403 |
-
del self.control_model
|
| 404 |
-
self.control_model = None
|
| 405 |
-
super().cleanup()
|
| 406 |
-
|
| 407 |
-
def get_models(self):
|
| 408 |
-
out = ControlBase.get_models(self)
|
| 409 |
-
return out
|
| 410 |
-
|
| 411 |
-
def inference_memory_requirements(self, dtype):
|
| 412 |
-
return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
|
| 413 |
-
|
| 414 |
-
def controlnet_config(sd, model_options={}):
|
| 415 |
-
model_config = comfy.model_detection.model_config_from_unet(sd, "", True)
|
| 416 |
-
|
| 417 |
-
unet_dtype = model_options.get("dtype", None)
|
| 418 |
-
if unet_dtype is None:
|
| 419 |
-
weight_dtype = comfy.utils.weight_dtype(sd)
|
| 420 |
-
|
| 421 |
-
supported_inference_dtypes = list(model_config.supported_inference_dtypes)
|
| 422 |
-
unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes, weight_dtype=weight_dtype)
|
| 423 |
-
|
| 424 |
-
load_device = comfy.model_management.get_torch_device()
|
| 425 |
-
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
|
| 426 |
-
|
| 427 |
-
operations = model_options.get("custom_operations", None)
|
| 428 |
-
if operations is None:
|
| 429 |
-
operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
|
| 430 |
-
|
| 431 |
-
offload_device = comfy.model_management.unet_offload_device()
|
| 432 |
-
return model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device
|
| 433 |
-
|
| 434 |
-
def controlnet_load_state_dict(control_model, sd):
|
| 435 |
-
missing, unexpected = control_model.load_state_dict(sd, strict=False)
|
| 436 |
-
|
| 437 |
-
if len(missing) > 0:
|
| 438 |
-
logging.warning("missing controlnet keys: {}".format(missing))
|
| 439 |
-
|
| 440 |
-
if len(unexpected) > 0:
|
| 441 |
-
logging.debug("unexpected controlnet keys: {}".format(unexpected))
|
| 442 |
-
return control_model
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
def load_controlnet_mmdit(sd, model_options={}):
|
| 446 |
-
new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
|
| 447 |
-
model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
|
| 448 |
-
num_blocks = comfy.model_detection.count_blocks(new_sd, 'joint_blocks.{}.')
|
| 449 |
-
for k in sd:
|
| 450 |
-
new_sd[k] = sd[k]
|
| 451 |
-
|
| 452 |
-
concat_mask = False
|
| 453 |
-
control_latent_channels = new_sd.get("pos_embed_input.proj.weight").shape[1]
|
| 454 |
-
if control_latent_channels == 17: #inpaint controlnet
|
| 455 |
-
concat_mask = True
|
| 456 |
-
|
| 457 |
-
control_model = comfy.cldm.mmdit.ControlNet(num_blocks=num_blocks, control_latent_channels=control_latent_channels, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
|
| 458 |
-
control_model = controlnet_load_state_dict(control_model, new_sd)
|
| 459 |
-
|
| 460 |
-
latent_format = comfy.latent_formats.SD3()
|
| 461 |
-
latent_format.shift_factor = 0 #SD3 controlnet weirdness
|
| 462 |
-
control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, concat_mask=concat_mask, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
|
| 463 |
-
return control
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
class ControlNetSD35(ControlNet):
|
| 467 |
-
def pre_run(self, model, percent_to_timestep_function):
|
| 468 |
-
if self.control_model.double_y_emb:
|
| 469 |
-
missing, unexpected = self.control_model.orig_y_embedder.load_state_dict(model.diffusion_model.y_embedder.state_dict(), strict=False)
|
| 470 |
-
else:
|
| 471 |
-
missing, unexpected = self.control_model.x_embedder.load_state_dict(model.diffusion_model.x_embedder.state_dict(), strict=False)
|
| 472 |
-
super().pre_run(model, percent_to_timestep_function)
|
| 473 |
-
|
| 474 |
-
def copy(self):
|
| 475 |
-
c = ControlNetSD35(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
|
| 476 |
-
c.control_model = self.control_model
|
| 477 |
-
c.control_model_wrapped = self.control_model_wrapped
|
| 478 |
-
self.copy_to(c)
|
| 479 |
-
return c
|
| 480 |
-
|
| 481 |
-
def load_controlnet_sd35(sd, model_options={}):
|
| 482 |
-
control_type = -1
|
| 483 |
-
if "control_type" in sd:
|
| 484 |
-
control_type = round(sd.pop("control_type").item())
|
| 485 |
-
|
| 486 |
-
# blur_cnet = control_type == 0
|
| 487 |
-
canny_cnet = control_type == 1
|
| 488 |
-
depth_cnet = control_type == 2
|
| 489 |
-
|
| 490 |
-
new_sd = {}
|
| 491 |
-
for k in comfy.utils.MMDIT_MAP_BASIC:
|
| 492 |
-
if k[1] in sd:
|
| 493 |
-
new_sd[k[0]] = sd.pop(k[1])
|
| 494 |
-
for k in sd:
|
| 495 |
-
new_sd[k] = sd[k]
|
| 496 |
-
sd = new_sd
|
| 497 |
-
|
| 498 |
-
y_emb_shape = sd["y_embedder.mlp.0.weight"].shape
|
| 499 |
-
depth = y_emb_shape[0] // 64
|
| 500 |
-
hidden_size = 64 * depth
|
| 501 |
-
num_heads = depth
|
| 502 |
-
head_dim = hidden_size // num_heads
|
| 503 |
-
num_blocks = comfy.model_detection.count_blocks(new_sd, 'transformer_blocks.{}.')
|
| 504 |
-
|
| 505 |
-
load_device = comfy.model_management.get_torch_device()
|
| 506 |
-
offload_device = comfy.model_management.unet_offload_device()
|
| 507 |
-
unet_dtype = comfy.model_management.unet_dtype(model_params=-1)
|
| 508 |
-
|
| 509 |
-
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
|
| 510 |
-
|
| 511 |
-
operations = model_options.get("custom_operations", None)
|
| 512 |
-
if operations is None:
|
| 513 |
-
operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
|
| 514 |
-
|
| 515 |
-
control_model = comfy.cldm.dit_embedder.ControlNetEmbedder(img_size=None,
|
| 516 |
-
patch_size=2,
|
| 517 |
-
in_chans=16,
|
| 518 |
-
num_layers=num_blocks,
|
| 519 |
-
main_model_double=depth,
|
| 520 |
-
double_y_emb=y_emb_shape[0] == y_emb_shape[1],
|
| 521 |
-
attention_head_dim=head_dim,
|
| 522 |
-
num_attention_heads=num_heads,
|
| 523 |
-
adm_in_channels=2048,
|
| 524 |
-
device=offload_device,
|
| 525 |
-
dtype=unet_dtype,
|
| 526 |
-
operations=operations)
|
| 527 |
-
|
| 528 |
-
control_model = controlnet_load_state_dict(control_model, sd)
|
| 529 |
-
|
| 530 |
-
latent_format = comfy.latent_formats.SD3()
|
| 531 |
-
preprocess_image = lambda a: a
|
| 532 |
-
if canny_cnet:
|
| 533 |
-
preprocess_image = lambda a: (a * 255 * 0.5 + 0.5)
|
| 534 |
-
elif depth_cnet:
|
| 535 |
-
preprocess_image = lambda a: 1.0 - a
|
| 536 |
-
|
| 537 |
-
control = ControlNetSD35(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype, preprocess_image=preprocess_image)
|
| 538 |
-
return control
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
def load_controlnet_hunyuandit(controlnet_data, model_options={}):
|
| 543 |
-
model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(controlnet_data, model_options=model_options)
|
| 544 |
-
|
| 545 |
-
control_model = comfy.ldm.hydit.controlnet.HunYuanControlNet(operations=operations, device=offload_device, dtype=unet_dtype)
|
| 546 |
-
control_model = controlnet_load_state_dict(control_model, controlnet_data)
|
| 547 |
-
|
| 548 |
-
latent_format = comfy.latent_formats.SDXL()
|
| 549 |
-
extra_conds = ['text_embedding_mask', 'encoder_hidden_states_t5', 'text_embedding_mask_t5', 'image_meta_size', 'style', 'cos_cis_img', 'sin_cis_img']
|
| 550 |
-
control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds, strength_type=StrengthType.CONSTANT)
|
| 551 |
-
return control
|
| 552 |
-
|
| 553 |
-
def load_controlnet_flux_xlabs_mistoline(sd, mistoline=False, model_options={}):
|
| 554 |
-
model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(sd, model_options=model_options)
|
| 555 |
-
control_model = comfy.ldm.flux.controlnet.ControlNetFlux(mistoline=mistoline, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
|
| 556 |
-
control_model = controlnet_load_state_dict(control_model, sd)
|
| 557 |
-
extra_conds = ['y', 'guidance']
|
| 558 |
-
control = ControlNet(control_model, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
|
| 559 |
-
return control
|
| 560 |
-
|
| 561 |
-
def load_controlnet_flux_instantx(sd, model_options={}):
|
| 562 |
-
new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
|
| 563 |
-
model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
|
| 564 |
-
for k in sd:
|
| 565 |
-
new_sd[k] = sd[k]
|
| 566 |
-
|
| 567 |
-
num_union_modes = 0
|
| 568 |
-
union_cnet = "controlnet_mode_embedder.weight"
|
| 569 |
-
if union_cnet in new_sd:
|
| 570 |
-
num_union_modes = new_sd[union_cnet].shape[0]
|
| 571 |
-
|
| 572 |
-
control_latent_channels = new_sd.get("pos_embed_input.weight").shape[1] // 4
|
| 573 |
-
concat_mask = False
|
| 574 |
-
if control_latent_channels == 17:
|
| 575 |
-
concat_mask = True
|
| 576 |
-
|
| 577 |
-
control_model = comfy.ldm.flux.controlnet.ControlNetFlux(latent_input=True, num_union_modes=num_union_modes, control_latent_channels=control_latent_channels, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
|
| 578 |
-
control_model = controlnet_load_state_dict(control_model, new_sd)
|
| 579 |
-
|
| 580 |
-
latent_format = comfy.latent_formats.Flux()
|
| 581 |
-
extra_conds = ['y', 'guidance']
|
| 582 |
-
control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, concat_mask=concat_mask, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
|
| 583 |
-
return control
|
| 584 |
-
|
| 585 |
-
def convert_mistoline(sd):
|
| 586 |
-
return comfy.utils.state_dict_prefix_replace(sd, {"single_controlnet_blocks.": "controlnet_single_blocks."})
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
def load_controlnet_state_dict(state_dict, model=None, model_options={}):
|
| 590 |
-
controlnet_data = state_dict
|
| 591 |
-
if 'after_proj_list.18.bias' in controlnet_data.keys(): #Hunyuan DiT
|
| 592 |
-
return load_controlnet_hunyuandit(controlnet_data, model_options=model_options)
|
| 593 |
-
|
| 594 |
-
if "lora_controlnet" in controlnet_data:
|
| 595 |
-
return ControlLora(controlnet_data, model_options=model_options)
|
| 596 |
-
|
| 597 |
-
controlnet_config = None
|
| 598 |
-
supported_inference_dtypes = None
|
| 599 |
-
|
| 600 |
-
if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
|
| 601 |
-
controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data)
|
| 602 |
-
diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
|
| 603 |
-
diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
|
| 604 |
-
diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
|
| 605 |
-
|
| 606 |
-
count = 0
|
| 607 |
-
loop = True
|
| 608 |
-
while loop:
|
| 609 |
-
suffix = [".weight", ".bias"]
|
| 610 |
-
for s in suffix:
|
| 611 |
-
k_in = "controlnet_down_blocks.{}{}".format(count, s)
|
| 612 |
-
k_out = "zero_convs.{}.0{}".format(count, s)
|
| 613 |
-
if k_in not in controlnet_data:
|
| 614 |
-
loop = False
|
| 615 |
-
break
|
| 616 |
-
diffusers_keys[k_in] = k_out
|
| 617 |
-
count += 1
|
| 618 |
-
|
| 619 |
-
count = 0
|
| 620 |
-
loop = True
|
| 621 |
-
while loop:
|
| 622 |
-
suffix = [".weight", ".bias"]
|
| 623 |
-
for s in suffix:
|
| 624 |
-
if count == 0:
|
| 625 |
-
k_in = "controlnet_cond_embedding.conv_in{}".format(s)
|
| 626 |
-
else:
|
| 627 |
-
k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
|
| 628 |
-
k_out = "input_hint_block.{}{}".format(count * 2, s)
|
| 629 |
-
if k_in not in controlnet_data:
|
| 630 |
-
k_in = "controlnet_cond_embedding.conv_out{}".format(s)
|
| 631 |
-
loop = False
|
| 632 |
-
diffusers_keys[k_in] = k_out
|
| 633 |
-
count += 1
|
| 634 |
-
|
| 635 |
-
new_sd = {}
|
| 636 |
-
for k in diffusers_keys:
|
| 637 |
-
if k in controlnet_data:
|
| 638 |
-
new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
|
| 639 |
-
|
| 640 |
-
if "control_add_embedding.linear_1.bias" in controlnet_data: #Union Controlnet
|
| 641 |
-
controlnet_config["union_controlnet_num_control_type"] = controlnet_data["task_embedding"].shape[0]
|
| 642 |
-
for k in list(controlnet_data.keys()):
|
| 643 |
-
new_k = k.replace('.attn.in_proj_', '.attn.in_proj.')
|
| 644 |
-
new_sd[new_k] = controlnet_data.pop(k)
|
| 645 |
-
|
| 646 |
-
leftover_keys = controlnet_data.keys()
|
| 647 |
-
if len(leftover_keys) > 0:
|
| 648 |
-
logging.warning("leftover keys: {}".format(leftover_keys))
|
| 649 |
-
controlnet_data = new_sd
|
| 650 |
-
elif "controlnet_blocks.0.weight" in controlnet_data:
|
| 651 |
-
if "double_blocks.0.img_attn.norm.key_norm.scale" in controlnet_data:
|
| 652 |
-
return load_controlnet_flux_xlabs_mistoline(controlnet_data, model_options=model_options)
|
| 653 |
-
elif "pos_embed_input.proj.weight" in controlnet_data:
|
| 654 |
-
if "transformer_blocks.0.adaLN_modulation.1.bias" in controlnet_data:
|
| 655 |
-
return load_controlnet_sd35(controlnet_data, model_options=model_options) #Stability sd3.5 format
|
| 656 |
-
else:
|
| 657 |
-
return load_controlnet_mmdit(controlnet_data, model_options=model_options) #SD3 diffusers controlnet
|
| 658 |
-
elif "controlnet_x_embedder.weight" in controlnet_data:
|
| 659 |
-
return load_controlnet_flux_instantx(controlnet_data, model_options=model_options)
|
| 660 |
-
elif "controlnet_blocks.0.linear.weight" in controlnet_data: #mistoline flux
|
| 661 |
-
return load_controlnet_flux_xlabs_mistoline(convert_mistoline(controlnet_data), mistoline=True, model_options=model_options)
|
| 662 |
-
|
| 663 |
-
pth_key = 'control_model.zero_convs.0.0.weight'
|
| 664 |
-
pth = False
|
| 665 |
-
key = 'zero_convs.0.0.weight'
|
| 666 |
-
if pth_key in controlnet_data:
|
| 667 |
-
pth = True
|
| 668 |
-
key = pth_key
|
| 669 |
-
prefix = "control_model."
|
| 670 |
-
elif key in controlnet_data:
|
| 671 |
-
prefix = ""
|
| 672 |
-
else:
|
| 673 |
-
net = load_t2i_adapter(controlnet_data, model_options=model_options)
|
| 674 |
-
if net is None:
|
| 675 |
-
logging.error("error could not detect control model type.")
|
| 676 |
-
return net
|
| 677 |
-
|
| 678 |
-
if controlnet_config is None:
|
| 679 |
-
model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
|
| 680 |
-
supported_inference_dtypes = list(model_config.supported_inference_dtypes)
|
| 681 |
-
controlnet_config = model_config.unet_config
|
| 682 |
-
|
| 683 |
-
unet_dtype = model_options.get("dtype", None)
|
| 684 |
-
if unet_dtype is None:
|
| 685 |
-
weight_dtype = comfy.utils.weight_dtype(controlnet_data)
|
| 686 |
-
|
| 687 |
-
if supported_inference_dtypes is None:
|
| 688 |
-
supported_inference_dtypes = [comfy.model_management.unet_dtype()]
|
| 689 |
-
|
| 690 |
-
unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes, weight_dtype=weight_dtype)
|
| 691 |
-
|
| 692 |
-
load_device = comfy.model_management.get_torch_device()
|
| 693 |
-
|
| 694 |
-
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
|
| 695 |
-
operations = model_options.get("custom_operations", None)
|
| 696 |
-
if operations is None:
|
| 697 |
-
operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype)
|
| 698 |
-
|
| 699 |
-
controlnet_config["operations"] = operations
|
| 700 |
-
controlnet_config["dtype"] = unet_dtype
|
| 701 |
-
controlnet_config["device"] = comfy.model_management.unet_offload_device()
|
| 702 |
-
controlnet_config.pop("out_channels")
|
| 703 |
-
controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
|
| 704 |
-
control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
|
| 705 |
-
|
| 706 |
-
if pth:
|
| 707 |
-
if 'difference' in controlnet_data:
|
| 708 |
-
if model is not None:
|
| 709 |
-
comfy.model_management.load_models_gpu([model])
|
| 710 |
-
model_sd = model.model_state_dict()
|
| 711 |
-
for x in controlnet_data:
|
| 712 |
-
c_m = "control_model."
|
| 713 |
-
if x.startswith(c_m):
|
| 714 |
-
sd_key = "diffusion_model.{}".format(x[len(c_m):])
|
| 715 |
-
if sd_key in model_sd:
|
| 716 |
-
cd = controlnet_data[x]
|
| 717 |
-
cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
|
| 718 |
-
else:
|
| 719 |
-
logging.warning("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
|
| 720 |
-
|
| 721 |
-
class WeightsLoader(torch.nn.Module):
|
| 722 |
-
pass
|
| 723 |
-
w = WeightsLoader()
|
| 724 |
-
w.control_model = control_model
|
| 725 |
-
missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
|
| 726 |
-
else:
|
| 727 |
-
missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
|
| 728 |
-
|
| 729 |
-
if len(missing) > 0:
|
| 730 |
-
logging.warning("missing controlnet keys: {}".format(missing))
|
| 731 |
-
|
| 732 |
-
if len(unexpected) > 0:
|
| 733 |
-
logging.debug("unexpected controlnet keys: {}".format(unexpected))
|
| 734 |
-
|
| 735 |
-
global_average_pooling = model_options.get("global_average_pooling", False)
|
| 736 |
-
control = ControlNet(control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
|
| 737 |
-
return control
|
| 738 |
-
|
| 739 |
-
def load_controlnet(ckpt_path, model=None, model_options={}):
|
| 740 |
-
model_options = model_options.copy()
|
| 741 |
-
if "global_average_pooling" not in model_options:
|
| 742 |
-
filename = os.path.splitext(ckpt_path)[0]
|
| 743 |
-
if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
|
| 744 |
-
model_options["global_average_pooling"] = True
|
| 745 |
-
|
| 746 |
-
cnet = load_controlnet_state_dict(comfy.utils.load_torch_file(ckpt_path, safe_load=True), model=model, model_options=model_options)
|
| 747 |
-
if cnet is None:
|
| 748 |
-
logging.error("error checkpoint does not contain controlnet or t2i adapter data {}".format(ckpt_path))
|
| 749 |
-
return cnet
|
| 750 |
-
|
| 751 |
-
class T2IAdapter(ControlBase):
|
| 752 |
-
def __init__(self, t2i_model, channels_in, compression_ratio, upscale_algorithm, device=None):
|
| 753 |
-
super().__init__()
|
| 754 |
-
self.t2i_model = t2i_model
|
| 755 |
-
self.channels_in = channels_in
|
| 756 |
-
self.control_input = None
|
| 757 |
-
self.compression_ratio = compression_ratio
|
| 758 |
-
self.upscale_algorithm = upscale_algorithm
|
| 759 |
-
if device is None:
|
| 760 |
-
device = comfy.model_management.get_torch_device()
|
| 761 |
-
self.device = device
|
| 762 |
-
|
| 763 |
-
def scale_image_to(self, width, height):
|
| 764 |
-
unshuffle_amount = self.t2i_model.unshuffle_amount
|
| 765 |
-
width = math.ceil(width / unshuffle_amount) * unshuffle_amount
|
| 766 |
-
height = math.ceil(height / unshuffle_amount) * unshuffle_amount
|
| 767 |
-
return width, height
|
| 768 |
-
|
| 769 |
-
def get_control(self, x_noisy, t, cond, batched_number, transformer_options):
|
| 770 |
-
control_prev = None
|
| 771 |
-
if self.previous_controlnet is not None:
|
| 772 |
-
control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
|
| 773 |
-
|
| 774 |
-
if self.timestep_range is not None:
|
| 775 |
-
if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
|
| 776 |
-
if control_prev is not None:
|
| 777 |
-
return control_prev
|
| 778 |
-
else:
|
| 779 |
-
return None
|
| 780 |
-
|
| 781 |
-
if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
|
| 782 |
-
if self.cond_hint is not None:
|
| 783 |
-
del self.cond_hint
|
| 784 |
-
self.control_input = None
|
| 785 |
-
self.cond_hint = None
|
| 786 |
-
width, height = self.scale_image_to(x_noisy.shape[3] * self.compression_ratio, x_noisy.shape[2] * self.compression_ratio)
|
| 787 |
-
self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, width, height, self.upscale_algorithm, "center").float().to(self.device)
|
| 788 |
-
if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
|
| 789 |
-
self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
|
| 790 |
-
if x_noisy.shape[0] != self.cond_hint.shape[0]:
|
| 791 |
-
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
|
| 792 |
-
if self.control_input is None:
|
| 793 |
-
self.t2i_model.to(x_noisy.dtype)
|
| 794 |
-
self.t2i_model.to(self.device)
|
| 795 |
-
self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
|
| 796 |
-
self.t2i_model.cpu()
|
| 797 |
-
|
| 798 |
-
control_input = {}
|
| 799 |
-
for k in self.control_input:
|
| 800 |
-
control_input[k] = list(map(lambda a: None if a is None else a.clone(), self.control_input[k]))
|
| 801 |
-
|
| 802 |
-
return self.control_merge(control_input, control_prev, x_noisy.dtype)
|
| 803 |
-
|
| 804 |
-
def copy(self):
|
| 805 |
-
c = T2IAdapter(self.t2i_model, self.channels_in, self.compression_ratio, self.upscale_algorithm)
|
| 806 |
-
self.copy_to(c)
|
| 807 |
-
return c
|
| 808 |
-
|
| 809 |
-
def load_t2i_adapter(t2i_data, model_options={}): #TODO: model_options
|
| 810 |
-
compression_ratio = 8
|
| 811 |
-
upscale_algorithm = 'nearest-exact'
|
| 812 |
-
|
| 813 |
-
if 'adapter' in t2i_data:
|
| 814 |
-
t2i_data = t2i_data['adapter']
|
| 815 |
-
if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
|
| 816 |
-
prefix_replace = {}
|
| 817 |
-
for i in range(4):
|
| 818 |
-
for j in range(2):
|
| 819 |
-
prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
|
| 820 |
-
prefix_replace["adapter.body.{}.".format(i, )] = "body.{}.".format(i * 2)
|
| 821 |
-
prefix_replace["adapter."] = ""
|
| 822 |
-
t2i_data = comfy.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
|
| 823 |
-
keys = t2i_data.keys()
|
| 824 |
-
|
| 825 |
-
if "body.0.in_conv.weight" in keys:
|
| 826 |
-
cin = t2i_data['body.0.in_conv.weight'].shape[1]
|
| 827 |
-
model_ad = comfy.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
|
| 828 |
-
elif 'conv_in.weight' in keys:
|
| 829 |
-
cin = t2i_data['conv_in.weight'].shape[1]
|
| 830 |
-
channel = t2i_data['conv_in.weight'].shape[0]
|
| 831 |
-
ksize = t2i_data['body.0.block2.weight'].shape[2]
|
| 832 |
-
use_conv = False
|
| 833 |
-
down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
|
| 834 |
-
if len(down_opts) > 0:
|
| 835 |
-
use_conv = True
|
| 836 |
-
xl = False
|
| 837 |
-
if cin == 256 or cin == 768:
|
| 838 |
-
xl = True
|
| 839 |
-
model_ad = comfy.t2i_adapter.adapter.Adapter(cin=cin, channels=[channel, channel*2, channel*4, channel*4][:4], nums_rb=2, ksize=ksize, sk=True, use_conv=use_conv, xl=xl)
|
| 840 |
-
elif "backbone.0.0.weight" in keys:
|
| 841 |
-
model_ad = comfy.ldm.cascade.controlnet.ControlNet(c_in=t2i_data['backbone.0.0.weight'].shape[1], proj_blocks=[0, 4, 8, 12, 51, 55, 59, 63])
|
| 842 |
-
compression_ratio = 32
|
| 843 |
-
upscale_algorithm = 'bilinear'
|
| 844 |
-
elif "backbone.10.blocks.0.weight" in keys:
|
| 845 |
-
model_ad = comfy.ldm.cascade.controlnet.ControlNet(c_in=t2i_data['backbone.0.weight'].shape[1], bottleneck_mode="large", proj_blocks=[0, 4, 8, 12, 51, 55, 59, 63])
|
| 846 |
-
compression_ratio = 1
|
| 847 |
-
upscale_algorithm = 'nearest-exact'
|
| 848 |
-
else:
|
| 849 |
-
return None
|
| 850 |
-
|
| 851 |
-
missing, unexpected = model_ad.load_state_dict(t2i_data)
|
| 852 |
-
if len(missing) > 0:
|
| 853 |
-
logging.warning("t2i missing {}".format(missing))
|
| 854 |
-
|
| 855 |
-
if len(unexpected) > 0:
|
| 856 |
-
logging.debug("t2i unexpected {}".format(unexpected))
|
| 857 |
-
|
| 858 |
-
return T2IAdapter(model_ad, model_ad.input_channels, compression_ratio, upscale_algorithm)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/diffusers_convert.py
DELETED
|
@@ -1,189 +0,0 @@
|
|
| 1 |
-
import re
|
| 2 |
-
import torch
|
| 3 |
-
import logging
|
| 4 |
-
|
| 5 |
-
# conversion code from https://github.com/huggingface/diffusers/blob/main/scripts/convert_diffusers_to_original_stable_diffusion.py
|
| 6 |
-
|
| 7 |
-
# ================#
|
| 8 |
-
# VAE Conversion #
|
| 9 |
-
# ================#
|
| 10 |
-
|
| 11 |
-
vae_conversion_map = [
|
| 12 |
-
# (stable-diffusion, HF Diffusers)
|
| 13 |
-
("nin_shortcut", "conv_shortcut"),
|
| 14 |
-
("norm_out", "conv_norm_out"),
|
| 15 |
-
("mid.attn_1.", "mid_block.attentions.0."),
|
| 16 |
-
]
|
| 17 |
-
|
| 18 |
-
for i in range(4):
|
| 19 |
-
# down_blocks have two resnets
|
| 20 |
-
for j in range(2):
|
| 21 |
-
hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
|
| 22 |
-
sd_down_prefix = f"encoder.down.{i}.block.{j}."
|
| 23 |
-
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
|
| 24 |
-
|
| 25 |
-
if i < 3:
|
| 26 |
-
hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
|
| 27 |
-
sd_downsample_prefix = f"down.{i}.downsample."
|
| 28 |
-
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
|
| 29 |
-
|
| 30 |
-
hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
|
| 31 |
-
sd_upsample_prefix = f"up.{3 - i}.upsample."
|
| 32 |
-
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
|
| 33 |
-
|
| 34 |
-
# up_blocks have three resnets
|
| 35 |
-
# also, up blocks in hf are numbered in reverse from sd
|
| 36 |
-
for j in range(3):
|
| 37 |
-
hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
|
| 38 |
-
sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
|
| 39 |
-
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
|
| 40 |
-
|
| 41 |
-
# this part accounts for mid blocks in both the encoder and the decoder
|
| 42 |
-
for i in range(2):
|
| 43 |
-
hf_mid_res_prefix = f"mid_block.resnets.{i}."
|
| 44 |
-
sd_mid_res_prefix = f"mid.block_{i + 1}."
|
| 45 |
-
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
|
| 46 |
-
|
| 47 |
-
vae_conversion_map_attn = [
|
| 48 |
-
# (stable-diffusion, HF Diffusers)
|
| 49 |
-
("norm.", "group_norm."),
|
| 50 |
-
("q.", "query."),
|
| 51 |
-
("k.", "key."),
|
| 52 |
-
("v.", "value."),
|
| 53 |
-
("q.", "to_q."),
|
| 54 |
-
("k.", "to_k."),
|
| 55 |
-
("v.", "to_v."),
|
| 56 |
-
("proj_out.", "to_out.0."),
|
| 57 |
-
("proj_out.", "proj_attn."),
|
| 58 |
-
]
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def reshape_weight_for_sd(w, conv3d=False):
|
| 62 |
-
# convert HF linear weights to SD conv2d weights
|
| 63 |
-
if conv3d:
|
| 64 |
-
return w.reshape(*w.shape, 1, 1, 1)
|
| 65 |
-
else:
|
| 66 |
-
return w.reshape(*w.shape, 1, 1)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def convert_vae_state_dict(vae_state_dict):
|
| 70 |
-
mapping = {k: k for k in vae_state_dict.keys()}
|
| 71 |
-
conv3d = False
|
| 72 |
-
for k, v in mapping.items():
|
| 73 |
-
for sd_part, hf_part in vae_conversion_map:
|
| 74 |
-
v = v.replace(hf_part, sd_part)
|
| 75 |
-
if v.endswith(".conv.weight"):
|
| 76 |
-
if not conv3d and vae_state_dict[k].ndim == 5:
|
| 77 |
-
conv3d = True
|
| 78 |
-
mapping[k] = v
|
| 79 |
-
for k, v in mapping.items():
|
| 80 |
-
if "attentions" in k:
|
| 81 |
-
for sd_part, hf_part in vae_conversion_map_attn:
|
| 82 |
-
v = v.replace(hf_part, sd_part)
|
| 83 |
-
mapping[k] = v
|
| 84 |
-
new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
|
| 85 |
-
weights_to_convert = ["q", "k", "v", "proj_out"]
|
| 86 |
-
for k, v in new_state_dict.items():
|
| 87 |
-
for weight_name in weights_to_convert:
|
| 88 |
-
if f"mid.attn_1.{weight_name}.weight" in k:
|
| 89 |
-
logging.debug(f"Reshaping {k} for SD format")
|
| 90 |
-
new_state_dict[k] = reshape_weight_for_sd(v, conv3d=conv3d)
|
| 91 |
-
return new_state_dict
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
# =========================#
|
| 95 |
-
# Text Encoder Conversion #
|
| 96 |
-
# =========================#
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
textenc_conversion_lst = [
|
| 100 |
-
# (stable-diffusion, HF Diffusers)
|
| 101 |
-
("resblocks.", "text_model.encoder.layers."),
|
| 102 |
-
("ln_1", "layer_norm1"),
|
| 103 |
-
("ln_2", "layer_norm2"),
|
| 104 |
-
(".c_fc.", ".fc1."),
|
| 105 |
-
(".c_proj.", ".fc2."),
|
| 106 |
-
(".attn", ".self_attn"),
|
| 107 |
-
("ln_final.", "transformer.text_model.final_layer_norm."),
|
| 108 |
-
("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
|
| 109 |
-
("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
|
| 110 |
-
]
|
| 111 |
-
protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
|
| 112 |
-
textenc_pattern = re.compile("|".join(protected.keys()))
|
| 113 |
-
|
| 114 |
-
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
|
| 115 |
-
code2idx = {"q": 0, "k": 1, "v": 2}
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
# This function exists because at the time of writing torch.cat can't do fp8 with cuda
|
| 119 |
-
def cat_tensors(tensors):
|
| 120 |
-
x = 0
|
| 121 |
-
for t in tensors:
|
| 122 |
-
x += t.shape[0]
|
| 123 |
-
|
| 124 |
-
shape = [x] + list(tensors[0].shape)[1:]
|
| 125 |
-
out = torch.empty(shape, device=tensors[0].device, dtype=tensors[0].dtype)
|
| 126 |
-
|
| 127 |
-
x = 0
|
| 128 |
-
for t in tensors:
|
| 129 |
-
out[x:x + t.shape[0]] = t
|
| 130 |
-
x += t.shape[0]
|
| 131 |
-
|
| 132 |
-
return out
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def convert_text_enc_state_dict_v20(text_enc_dict, prefix=""):
|
| 136 |
-
new_state_dict = {}
|
| 137 |
-
capture_qkv_weight = {}
|
| 138 |
-
capture_qkv_bias = {}
|
| 139 |
-
for k, v in text_enc_dict.items():
|
| 140 |
-
if not k.startswith(prefix):
|
| 141 |
-
continue
|
| 142 |
-
if (
|
| 143 |
-
k.endswith(".self_attn.q_proj.weight")
|
| 144 |
-
or k.endswith(".self_attn.k_proj.weight")
|
| 145 |
-
or k.endswith(".self_attn.v_proj.weight")
|
| 146 |
-
):
|
| 147 |
-
k_pre = k[: -len(".q_proj.weight")]
|
| 148 |
-
k_code = k[-len("q_proj.weight")]
|
| 149 |
-
if k_pre not in capture_qkv_weight:
|
| 150 |
-
capture_qkv_weight[k_pre] = [None, None, None]
|
| 151 |
-
capture_qkv_weight[k_pre][code2idx[k_code]] = v
|
| 152 |
-
continue
|
| 153 |
-
|
| 154 |
-
if (
|
| 155 |
-
k.endswith(".self_attn.q_proj.bias")
|
| 156 |
-
or k.endswith(".self_attn.k_proj.bias")
|
| 157 |
-
or k.endswith(".self_attn.v_proj.bias")
|
| 158 |
-
):
|
| 159 |
-
k_pre = k[: -len(".q_proj.bias")]
|
| 160 |
-
k_code = k[-len("q_proj.bias")]
|
| 161 |
-
if k_pre not in capture_qkv_bias:
|
| 162 |
-
capture_qkv_bias[k_pre] = [None, None, None]
|
| 163 |
-
capture_qkv_bias[k_pre][code2idx[k_code]] = v
|
| 164 |
-
continue
|
| 165 |
-
|
| 166 |
-
text_proj = "transformer.text_projection.weight"
|
| 167 |
-
if k.endswith(text_proj):
|
| 168 |
-
new_state_dict[k.replace(text_proj, "text_projection")] = v.transpose(0, 1).contiguous()
|
| 169 |
-
else:
|
| 170 |
-
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
|
| 171 |
-
new_state_dict[relabelled_key] = v
|
| 172 |
-
|
| 173 |
-
for k_pre, tensors in capture_qkv_weight.items():
|
| 174 |
-
if None in tensors:
|
| 175 |
-
raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
|
| 176 |
-
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
|
| 177 |
-
new_state_dict[relabelled_key + ".in_proj_weight"] = cat_tensors(tensors)
|
| 178 |
-
|
| 179 |
-
for k_pre, tensors in capture_qkv_bias.items():
|
| 180 |
-
if None in tensors:
|
| 181 |
-
raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
|
| 182 |
-
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
|
| 183 |
-
new_state_dict[relabelled_key + ".in_proj_bias"] = cat_tensors(tensors)
|
| 184 |
-
|
| 185 |
-
return new_state_dict
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def convert_text_enc_state_dict(text_enc_dict):
|
| 189 |
-
return text_enc_dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/diffusers_load.py
DELETED
|
@@ -1,36 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
|
| 3 |
-
import comfy.sd
|
| 4 |
-
|
| 5 |
-
def first_file(path, filenames):
|
| 6 |
-
for f in filenames:
|
| 7 |
-
p = os.path.join(path, f)
|
| 8 |
-
if os.path.exists(p):
|
| 9 |
-
return p
|
| 10 |
-
return None
|
| 11 |
-
|
| 12 |
-
def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
|
| 13 |
-
diffusion_model_names = ["diffusion_pytorch_model.fp16.safetensors", "diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.fp16.bin", "diffusion_pytorch_model.bin"]
|
| 14 |
-
unet_path = first_file(os.path.join(model_path, "unet"), diffusion_model_names)
|
| 15 |
-
vae_path = first_file(os.path.join(model_path, "vae"), diffusion_model_names)
|
| 16 |
-
|
| 17 |
-
text_encoder_model_names = ["model.fp16.safetensors", "model.safetensors", "pytorch_model.fp16.bin", "pytorch_model.bin"]
|
| 18 |
-
text_encoder1_path = first_file(os.path.join(model_path, "text_encoder"), text_encoder_model_names)
|
| 19 |
-
text_encoder2_path = first_file(os.path.join(model_path, "text_encoder_2"), text_encoder_model_names)
|
| 20 |
-
|
| 21 |
-
text_encoder_paths = [text_encoder1_path]
|
| 22 |
-
if text_encoder2_path is not None:
|
| 23 |
-
text_encoder_paths.append(text_encoder2_path)
|
| 24 |
-
|
| 25 |
-
unet = comfy.sd.load_diffusion_model(unet_path)
|
| 26 |
-
|
| 27 |
-
clip = None
|
| 28 |
-
if output_clip:
|
| 29 |
-
clip = comfy.sd.load_clip(text_encoder_paths, embedding_directory=embedding_directory)
|
| 30 |
-
|
| 31 |
-
vae = None
|
| 32 |
-
if output_vae:
|
| 33 |
-
sd = comfy.utils.load_torch_file(vae_path)
|
| 34 |
-
vae = comfy.sd.VAE(sd=sd)
|
| 35 |
-
|
| 36 |
-
return (unet, clip, vae)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/extra_samplers/uni_pc.py
DELETED
|
@@ -1,873 +0,0 @@
|
|
| 1 |
-
#code taken from: https://github.com/wl-zhao/UniPC and modified
|
| 2 |
-
|
| 3 |
-
import torch
|
| 4 |
-
import math
|
| 5 |
-
import logging
|
| 6 |
-
|
| 7 |
-
from tqdm.auto import trange
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
class NoiseScheduleVP:
|
| 11 |
-
def __init__(
|
| 12 |
-
self,
|
| 13 |
-
schedule='discrete',
|
| 14 |
-
betas=None,
|
| 15 |
-
alphas_cumprod=None,
|
| 16 |
-
continuous_beta_0=0.1,
|
| 17 |
-
continuous_beta_1=20.,
|
| 18 |
-
):
|
| 19 |
-
r"""Create a wrapper class for the forward SDE (VP type).
|
| 20 |
-
|
| 21 |
-
***
|
| 22 |
-
Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
|
| 23 |
-
We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
|
| 24 |
-
***
|
| 25 |
-
|
| 26 |
-
The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
|
| 27 |
-
We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
|
| 28 |
-
Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
|
| 29 |
-
|
| 30 |
-
log_alpha_t = self.marginal_log_mean_coeff(t)
|
| 31 |
-
sigma_t = self.marginal_std(t)
|
| 32 |
-
lambda_t = self.marginal_lambda(t)
|
| 33 |
-
|
| 34 |
-
Moreover, as lambda(t) is an invertible function, we also support its inverse function:
|
| 35 |
-
|
| 36 |
-
t = self.inverse_lambda(lambda_t)
|
| 37 |
-
|
| 38 |
-
===============================================================
|
| 39 |
-
|
| 40 |
-
We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
|
| 41 |
-
|
| 42 |
-
1. For discrete-time DPMs:
|
| 43 |
-
|
| 44 |
-
For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
|
| 45 |
-
t_i = (i + 1) / N
|
| 46 |
-
e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
|
| 47 |
-
We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
|
| 48 |
-
|
| 49 |
-
Args:
|
| 50 |
-
betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
|
| 51 |
-
alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
|
| 52 |
-
|
| 53 |
-
Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
|
| 54 |
-
|
| 55 |
-
**Important**: Please pay special attention for the args for `alphas_cumprod`:
|
| 56 |
-
The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
|
| 57 |
-
q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
|
| 58 |
-
Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
|
| 59 |
-
alpha_{t_n} = \sqrt{\hat{alpha_n}},
|
| 60 |
-
and
|
| 61 |
-
log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
2. For continuous-time DPMs:
|
| 65 |
-
|
| 66 |
-
We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
|
| 67 |
-
schedule are the default settings in DDPM and improved-DDPM:
|
| 68 |
-
|
| 69 |
-
Args:
|
| 70 |
-
beta_min: A `float` number. The smallest beta for the linear schedule.
|
| 71 |
-
beta_max: A `float` number. The largest beta for the linear schedule.
|
| 72 |
-
cosine_s: A `float` number. The hyperparameter in the cosine schedule.
|
| 73 |
-
cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
|
| 74 |
-
T: A `float` number. The ending time of the forward process.
|
| 75 |
-
|
| 76 |
-
===============================================================
|
| 77 |
-
|
| 78 |
-
Args:
|
| 79 |
-
schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
|
| 80 |
-
'linear' or 'cosine' for continuous-time DPMs.
|
| 81 |
-
Returns:
|
| 82 |
-
A wrapper object of the forward SDE (VP type).
|
| 83 |
-
|
| 84 |
-
===============================================================
|
| 85 |
-
|
| 86 |
-
Example:
|
| 87 |
-
|
| 88 |
-
# For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
|
| 89 |
-
>>> ns = NoiseScheduleVP('discrete', betas=betas)
|
| 90 |
-
|
| 91 |
-
# For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
|
| 92 |
-
>>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
|
| 93 |
-
|
| 94 |
-
# For continuous-time DPMs (VPSDE), linear schedule:
|
| 95 |
-
>>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
|
| 96 |
-
|
| 97 |
-
"""
|
| 98 |
-
|
| 99 |
-
if schedule not in ['discrete', 'linear', 'cosine']:
|
| 100 |
-
raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(schedule))
|
| 101 |
-
|
| 102 |
-
self.schedule = schedule
|
| 103 |
-
if schedule == 'discrete':
|
| 104 |
-
if betas is not None:
|
| 105 |
-
log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
|
| 106 |
-
else:
|
| 107 |
-
assert alphas_cumprod is not None
|
| 108 |
-
log_alphas = 0.5 * torch.log(alphas_cumprod)
|
| 109 |
-
self.total_N = len(log_alphas)
|
| 110 |
-
self.T = 1.
|
| 111 |
-
self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
|
| 112 |
-
self.log_alpha_array = log_alphas.reshape((1, -1,))
|
| 113 |
-
else:
|
| 114 |
-
self.total_N = 1000
|
| 115 |
-
self.beta_0 = continuous_beta_0
|
| 116 |
-
self.beta_1 = continuous_beta_1
|
| 117 |
-
self.cosine_s = 0.008
|
| 118 |
-
self.cosine_beta_max = 999.
|
| 119 |
-
self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
|
| 120 |
-
self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
|
| 121 |
-
self.schedule = schedule
|
| 122 |
-
if schedule == 'cosine':
|
| 123 |
-
# For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
|
| 124 |
-
# Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
|
| 125 |
-
self.T = 0.9946
|
| 126 |
-
else:
|
| 127 |
-
self.T = 1.
|
| 128 |
-
|
| 129 |
-
def marginal_log_mean_coeff(self, t):
|
| 130 |
-
"""
|
| 131 |
-
Compute log(alpha_t) of a given continuous-time label t in [0, T].
|
| 132 |
-
"""
|
| 133 |
-
if self.schedule == 'discrete':
|
| 134 |
-
return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1))
|
| 135 |
-
elif self.schedule == 'linear':
|
| 136 |
-
return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
|
| 137 |
-
elif self.schedule == 'cosine':
|
| 138 |
-
log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
|
| 139 |
-
log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
|
| 140 |
-
return log_alpha_t
|
| 141 |
-
|
| 142 |
-
def marginal_alpha(self, t):
|
| 143 |
-
"""
|
| 144 |
-
Compute alpha_t of a given continuous-time label t in [0, T].
|
| 145 |
-
"""
|
| 146 |
-
return torch.exp(self.marginal_log_mean_coeff(t))
|
| 147 |
-
|
| 148 |
-
def marginal_std(self, t):
|
| 149 |
-
"""
|
| 150 |
-
Compute sigma_t of a given continuous-time label t in [0, T].
|
| 151 |
-
"""
|
| 152 |
-
return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
|
| 153 |
-
|
| 154 |
-
def marginal_lambda(self, t):
|
| 155 |
-
"""
|
| 156 |
-
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
|
| 157 |
-
"""
|
| 158 |
-
log_mean_coeff = self.marginal_log_mean_coeff(t)
|
| 159 |
-
log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
|
| 160 |
-
return log_mean_coeff - log_std
|
| 161 |
-
|
| 162 |
-
def inverse_lambda(self, lamb):
|
| 163 |
-
"""
|
| 164 |
-
Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
|
| 165 |
-
"""
|
| 166 |
-
if self.schedule == 'linear':
|
| 167 |
-
tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
|
| 168 |
-
Delta = self.beta_0**2 + tmp
|
| 169 |
-
return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
|
| 170 |
-
elif self.schedule == 'discrete':
|
| 171 |
-
log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
|
| 172 |
-
t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1]))
|
| 173 |
-
return t.reshape((-1,))
|
| 174 |
-
else:
|
| 175 |
-
log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
|
| 176 |
-
t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
|
| 177 |
-
t = t_fn(log_alpha)
|
| 178 |
-
return t
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def model_wrapper(
|
| 182 |
-
model,
|
| 183 |
-
noise_schedule,
|
| 184 |
-
model_type="noise",
|
| 185 |
-
model_kwargs={},
|
| 186 |
-
guidance_type="uncond",
|
| 187 |
-
condition=None,
|
| 188 |
-
unconditional_condition=None,
|
| 189 |
-
guidance_scale=1.,
|
| 190 |
-
classifier_fn=None,
|
| 191 |
-
classifier_kwargs={},
|
| 192 |
-
):
|
| 193 |
-
"""Create a wrapper function for the noise prediction model.
|
| 194 |
-
|
| 195 |
-
DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
|
| 196 |
-
firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
|
| 197 |
-
|
| 198 |
-
We support four types of the diffusion model by setting `model_type`:
|
| 199 |
-
|
| 200 |
-
1. "noise": noise prediction model. (Trained by predicting noise).
|
| 201 |
-
|
| 202 |
-
2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
|
| 203 |
-
|
| 204 |
-
3. "v": velocity prediction model. (Trained by predicting the velocity).
|
| 205 |
-
The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
|
| 206 |
-
|
| 207 |
-
[1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
|
| 208 |
-
arXiv preprint arXiv:2202.00512 (2022).
|
| 209 |
-
[2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
|
| 210 |
-
arXiv preprint arXiv:2210.02303 (2022).
|
| 211 |
-
|
| 212 |
-
4. "score": marginal score function. (Trained by denoising score matching).
|
| 213 |
-
Note that the score function and the noise prediction model follows a simple relationship:
|
| 214 |
-
```
|
| 215 |
-
noise(x_t, t) = -sigma_t * score(x_t, t)
|
| 216 |
-
```
|
| 217 |
-
|
| 218 |
-
We support three types of guided sampling by DPMs by setting `guidance_type`:
|
| 219 |
-
1. "uncond": unconditional sampling by DPMs.
|
| 220 |
-
The input `model` has the following format:
|
| 221 |
-
``
|
| 222 |
-
model(x, t_input, **model_kwargs) -> noise | x_start | v | score
|
| 223 |
-
``
|
| 224 |
-
|
| 225 |
-
2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
|
| 226 |
-
The input `model` has the following format:
|
| 227 |
-
``
|
| 228 |
-
model(x, t_input, **model_kwargs) -> noise | x_start | v | score
|
| 229 |
-
``
|
| 230 |
-
|
| 231 |
-
The input `classifier_fn` has the following format:
|
| 232 |
-
``
|
| 233 |
-
classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
|
| 234 |
-
``
|
| 235 |
-
|
| 236 |
-
[3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
|
| 237 |
-
in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
|
| 238 |
-
|
| 239 |
-
3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
|
| 240 |
-
The input `model` has the following format:
|
| 241 |
-
``
|
| 242 |
-
model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
|
| 243 |
-
``
|
| 244 |
-
And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
|
| 245 |
-
|
| 246 |
-
[4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
|
| 247 |
-
arXiv preprint arXiv:2207.12598 (2022).
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
|
| 251 |
-
or continuous-time labels (i.e. epsilon to T).
|
| 252 |
-
|
| 253 |
-
We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
|
| 254 |
-
``
|
| 255 |
-
def model_fn(x, t_continuous) -> noise:
|
| 256 |
-
t_input = get_model_input_time(t_continuous)
|
| 257 |
-
return noise_pred(model, x, t_input, **model_kwargs)
|
| 258 |
-
``
|
| 259 |
-
where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
|
| 260 |
-
|
| 261 |
-
===============================================================
|
| 262 |
-
|
| 263 |
-
Args:
|
| 264 |
-
model: A diffusion model with the corresponding format described above.
|
| 265 |
-
noise_schedule: A noise schedule object, such as NoiseScheduleVP.
|
| 266 |
-
model_type: A `str`. The parameterization type of the diffusion model.
|
| 267 |
-
"noise" or "x_start" or "v" or "score".
|
| 268 |
-
model_kwargs: A `dict`. A dict for the other inputs of the model function.
|
| 269 |
-
guidance_type: A `str`. The type of the guidance for sampling.
|
| 270 |
-
"uncond" or "classifier" or "classifier-free".
|
| 271 |
-
condition: A pytorch tensor. The condition for the guided sampling.
|
| 272 |
-
Only used for "classifier" or "classifier-free" guidance type.
|
| 273 |
-
unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
|
| 274 |
-
Only used for "classifier-free" guidance type.
|
| 275 |
-
guidance_scale: A `float`. The scale for the guided sampling.
|
| 276 |
-
classifier_fn: A classifier function. Only used for the classifier guidance.
|
| 277 |
-
classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
|
| 278 |
-
Returns:
|
| 279 |
-
A noise prediction model that accepts the noised data and the continuous time as the inputs.
|
| 280 |
-
"""
|
| 281 |
-
|
| 282 |
-
def get_model_input_time(t_continuous):
|
| 283 |
-
"""
|
| 284 |
-
Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
|
| 285 |
-
For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
|
| 286 |
-
For continuous-time DPMs, we just use `t_continuous`.
|
| 287 |
-
"""
|
| 288 |
-
if noise_schedule.schedule == 'discrete':
|
| 289 |
-
return (t_continuous - 1. / noise_schedule.total_N) * 1000.
|
| 290 |
-
else:
|
| 291 |
-
return t_continuous
|
| 292 |
-
|
| 293 |
-
def noise_pred_fn(x, t_continuous, cond=None):
|
| 294 |
-
if t_continuous.reshape((-1,)).shape[0] == 1:
|
| 295 |
-
t_continuous = t_continuous.expand((x.shape[0]))
|
| 296 |
-
t_input = get_model_input_time(t_continuous)
|
| 297 |
-
output = model(x, t_input, **model_kwargs)
|
| 298 |
-
if model_type == "noise":
|
| 299 |
-
return output
|
| 300 |
-
elif model_type == "x_start":
|
| 301 |
-
alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
|
| 302 |
-
dims = x.dim()
|
| 303 |
-
return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
|
| 304 |
-
elif model_type == "v":
|
| 305 |
-
alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
|
| 306 |
-
dims = x.dim()
|
| 307 |
-
return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
|
| 308 |
-
elif model_type == "score":
|
| 309 |
-
sigma_t = noise_schedule.marginal_std(t_continuous)
|
| 310 |
-
dims = x.dim()
|
| 311 |
-
return -expand_dims(sigma_t, dims) * output
|
| 312 |
-
|
| 313 |
-
def cond_grad_fn(x, t_input):
|
| 314 |
-
"""
|
| 315 |
-
Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
|
| 316 |
-
"""
|
| 317 |
-
with torch.enable_grad():
|
| 318 |
-
x_in = x.detach().requires_grad_(True)
|
| 319 |
-
log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
|
| 320 |
-
return torch.autograd.grad(log_prob.sum(), x_in)[0]
|
| 321 |
-
|
| 322 |
-
def model_fn(x, t_continuous):
|
| 323 |
-
"""
|
| 324 |
-
The noise predicition model function that is used for DPM-Solver.
|
| 325 |
-
"""
|
| 326 |
-
if t_continuous.reshape((-1,)).shape[0] == 1:
|
| 327 |
-
t_continuous = t_continuous.expand((x.shape[0]))
|
| 328 |
-
if guidance_type == "uncond":
|
| 329 |
-
return noise_pred_fn(x, t_continuous)
|
| 330 |
-
elif guidance_type == "classifier":
|
| 331 |
-
assert classifier_fn is not None
|
| 332 |
-
t_input = get_model_input_time(t_continuous)
|
| 333 |
-
cond_grad = cond_grad_fn(x, t_input)
|
| 334 |
-
sigma_t = noise_schedule.marginal_std(t_continuous)
|
| 335 |
-
noise = noise_pred_fn(x, t_continuous)
|
| 336 |
-
return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
|
| 337 |
-
elif guidance_type == "classifier-free":
|
| 338 |
-
if guidance_scale == 1. or unconditional_condition is None:
|
| 339 |
-
return noise_pred_fn(x, t_continuous, cond=condition)
|
| 340 |
-
else:
|
| 341 |
-
x_in = torch.cat([x] * 2)
|
| 342 |
-
t_in = torch.cat([t_continuous] * 2)
|
| 343 |
-
c_in = torch.cat([unconditional_condition, condition])
|
| 344 |
-
noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
|
| 345 |
-
return noise_uncond + guidance_scale * (noise - noise_uncond)
|
| 346 |
-
|
| 347 |
-
assert model_type in ["noise", "x_start", "v"]
|
| 348 |
-
assert guidance_type in ["uncond", "classifier", "classifier-free"]
|
| 349 |
-
return model_fn
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
class UniPC:
|
| 353 |
-
def __init__(
|
| 354 |
-
self,
|
| 355 |
-
model_fn,
|
| 356 |
-
noise_schedule,
|
| 357 |
-
predict_x0=True,
|
| 358 |
-
thresholding=False,
|
| 359 |
-
max_val=1.,
|
| 360 |
-
variant='bh1',
|
| 361 |
-
):
|
| 362 |
-
"""Construct a UniPC.
|
| 363 |
-
|
| 364 |
-
We support both data_prediction and noise_prediction.
|
| 365 |
-
"""
|
| 366 |
-
self.model = model_fn
|
| 367 |
-
self.noise_schedule = noise_schedule
|
| 368 |
-
self.variant = variant
|
| 369 |
-
self.predict_x0 = predict_x0
|
| 370 |
-
self.thresholding = thresholding
|
| 371 |
-
self.max_val = max_val
|
| 372 |
-
|
| 373 |
-
def dynamic_thresholding_fn(self, x0, t=None):
|
| 374 |
-
"""
|
| 375 |
-
The dynamic thresholding method.
|
| 376 |
-
"""
|
| 377 |
-
dims = x0.dim()
|
| 378 |
-
p = self.dynamic_thresholding_ratio
|
| 379 |
-
s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
|
| 380 |
-
s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims)
|
| 381 |
-
x0 = torch.clamp(x0, -s, s) / s
|
| 382 |
-
return x0
|
| 383 |
-
|
| 384 |
-
def noise_prediction_fn(self, x, t):
|
| 385 |
-
"""
|
| 386 |
-
Return the noise prediction model.
|
| 387 |
-
"""
|
| 388 |
-
return self.model(x, t)
|
| 389 |
-
|
| 390 |
-
def data_prediction_fn(self, x, t):
|
| 391 |
-
"""
|
| 392 |
-
Return the data prediction model (with thresholding).
|
| 393 |
-
"""
|
| 394 |
-
noise = self.noise_prediction_fn(x, t)
|
| 395 |
-
dims = x.dim()
|
| 396 |
-
alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
|
| 397 |
-
x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
|
| 398 |
-
if self.thresholding:
|
| 399 |
-
p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
|
| 400 |
-
s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
|
| 401 |
-
s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
|
| 402 |
-
x0 = torch.clamp(x0, -s, s) / s
|
| 403 |
-
return x0
|
| 404 |
-
|
| 405 |
-
def model_fn(self, x, t):
|
| 406 |
-
"""
|
| 407 |
-
Convert the model to the noise prediction model or the data prediction model.
|
| 408 |
-
"""
|
| 409 |
-
if self.predict_x0:
|
| 410 |
-
return self.data_prediction_fn(x, t)
|
| 411 |
-
else:
|
| 412 |
-
return self.noise_prediction_fn(x, t)
|
| 413 |
-
|
| 414 |
-
def get_time_steps(self, skip_type, t_T, t_0, N, device):
|
| 415 |
-
"""Compute the intermediate time steps for sampling.
|
| 416 |
-
"""
|
| 417 |
-
if skip_type == 'logSNR':
|
| 418 |
-
lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
|
| 419 |
-
lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
|
| 420 |
-
logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
|
| 421 |
-
return self.noise_schedule.inverse_lambda(logSNR_steps)
|
| 422 |
-
elif skip_type == 'time_uniform':
|
| 423 |
-
return torch.linspace(t_T, t_0, N + 1).to(device)
|
| 424 |
-
elif skip_type == 'time_quadratic':
|
| 425 |
-
t_order = 2
|
| 426 |
-
t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)
|
| 427 |
-
return t
|
| 428 |
-
else:
|
| 429 |
-
raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
|
| 430 |
-
|
| 431 |
-
def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
|
| 432 |
-
"""
|
| 433 |
-
Get the order of each step for sampling by the singlestep DPM-Solver.
|
| 434 |
-
"""
|
| 435 |
-
if order == 3:
|
| 436 |
-
K = steps // 3 + 1
|
| 437 |
-
if steps % 3 == 0:
|
| 438 |
-
orders = [3,] * (K - 2) + [2, 1]
|
| 439 |
-
elif steps % 3 == 1:
|
| 440 |
-
orders = [3,] * (K - 1) + [1]
|
| 441 |
-
else:
|
| 442 |
-
orders = [3,] * (K - 1) + [2]
|
| 443 |
-
elif order == 2:
|
| 444 |
-
if steps % 2 == 0:
|
| 445 |
-
K = steps // 2
|
| 446 |
-
orders = [2,] * K
|
| 447 |
-
else:
|
| 448 |
-
K = steps // 2 + 1
|
| 449 |
-
orders = [2,] * (K - 1) + [1]
|
| 450 |
-
elif order == 1:
|
| 451 |
-
K = steps
|
| 452 |
-
orders = [1,] * steps
|
| 453 |
-
else:
|
| 454 |
-
raise ValueError("'order' must be '1' or '2' or '3'.")
|
| 455 |
-
if skip_type == 'logSNR':
|
| 456 |
-
# To reproduce the results in DPM-Solver paper
|
| 457 |
-
timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
|
| 458 |
-
else:
|
| 459 |
-
timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)]
|
| 460 |
-
return timesteps_outer, orders
|
| 461 |
-
|
| 462 |
-
def denoise_to_zero_fn(self, x, s):
|
| 463 |
-
"""
|
| 464 |
-
Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
|
| 465 |
-
"""
|
| 466 |
-
return self.data_prediction_fn(x, s)
|
| 467 |
-
|
| 468 |
-
def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs):
|
| 469 |
-
if len(t.shape) == 0:
|
| 470 |
-
t = t.view(-1)
|
| 471 |
-
if 'bh' in self.variant:
|
| 472 |
-
return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
|
| 473 |
-
else:
|
| 474 |
-
assert self.variant == 'vary_coeff'
|
| 475 |
-
return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
|
| 476 |
-
|
| 477 |
-
def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True):
|
| 478 |
-
logging.info(f'using unified predictor-corrector with order {order} (solver type: vary coeff)')
|
| 479 |
-
ns = self.noise_schedule
|
| 480 |
-
assert order <= len(model_prev_list)
|
| 481 |
-
|
| 482 |
-
# first compute rks
|
| 483 |
-
t_prev_0 = t_prev_list[-1]
|
| 484 |
-
lambda_prev_0 = ns.marginal_lambda(t_prev_0)
|
| 485 |
-
lambda_t = ns.marginal_lambda(t)
|
| 486 |
-
model_prev_0 = model_prev_list[-1]
|
| 487 |
-
sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
|
| 488 |
-
log_alpha_t = ns.marginal_log_mean_coeff(t)
|
| 489 |
-
alpha_t = torch.exp(log_alpha_t)
|
| 490 |
-
|
| 491 |
-
h = lambda_t - lambda_prev_0
|
| 492 |
-
|
| 493 |
-
rks = []
|
| 494 |
-
D1s = []
|
| 495 |
-
for i in range(1, order):
|
| 496 |
-
t_prev_i = t_prev_list[-(i + 1)]
|
| 497 |
-
model_prev_i = model_prev_list[-(i + 1)]
|
| 498 |
-
lambda_prev_i = ns.marginal_lambda(t_prev_i)
|
| 499 |
-
rk = (lambda_prev_i - lambda_prev_0) / h
|
| 500 |
-
rks.append(rk)
|
| 501 |
-
D1s.append((model_prev_i - model_prev_0) / rk)
|
| 502 |
-
|
| 503 |
-
rks.append(1.)
|
| 504 |
-
rks = torch.tensor(rks, device=x.device)
|
| 505 |
-
|
| 506 |
-
K = len(rks)
|
| 507 |
-
# build C matrix
|
| 508 |
-
C = []
|
| 509 |
-
|
| 510 |
-
col = torch.ones_like(rks)
|
| 511 |
-
for k in range(1, K + 1):
|
| 512 |
-
C.append(col)
|
| 513 |
-
col = col * rks / (k + 1)
|
| 514 |
-
C = torch.stack(C, dim=1)
|
| 515 |
-
|
| 516 |
-
if len(D1s) > 0:
|
| 517 |
-
D1s = torch.stack(D1s, dim=1) # (B, K)
|
| 518 |
-
C_inv_p = torch.linalg.inv(C[:-1, :-1])
|
| 519 |
-
A_p = C_inv_p
|
| 520 |
-
|
| 521 |
-
if use_corrector:
|
| 522 |
-
C_inv = torch.linalg.inv(C)
|
| 523 |
-
A_c = C_inv
|
| 524 |
-
|
| 525 |
-
hh = -h if self.predict_x0 else h
|
| 526 |
-
h_phi_1 = torch.expm1(hh)
|
| 527 |
-
h_phi_ks = []
|
| 528 |
-
factorial_k = 1
|
| 529 |
-
h_phi_k = h_phi_1
|
| 530 |
-
for k in range(1, K + 2):
|
| 531 |
-
h_phi_ks.append(h_phi_k)
|
| 532 |
-
h_phi_k = h_phi_k / hh - 1 / factorial_k
|
| 533 |
-
factorial_k *= (k + 1)
|
| 534 |
-
|
| 535 |
-
model_t = None
|
| 536 |
-
if self.predict_x0:
|
| 537 |
-
x_t_ = (
|
| 538 |
-
sigma_t / sigma_prev_0 * x
|
| 539 |
-
- alpha_t * h_phi_1 * model_prev_0
|
| 540 |
-
)
|
| 541 |
-
# now predictor
|
| 542 |
-
x_t = x_t_
|
| 543 |
-
if len(D1s) > 0:
|
| 544 |
-
# compute the residuals for predictor
|
| 545 |
-
for k in range(K - 1):
|
| 546 |
-
x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
|
| 547 |
-
# now corrector
|
| 548 |
-
if use_corrector:
|
| 549 |
-
model_t = self.model_fn(x_t, t)
|
| 550 |
-
D1_t = (model_t - model_prev_0)
|
| 551 |
-
x_t = x_t_
|
| 552 |
-
k = 0
|
| 553 |
-
for k in range(K - 1):
|
| 554 |
-
x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
|
| 555 |
-
x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
|
| 556 |
-
else:
|
| 557 |
-
log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
|
| 558 |
-
x_t_ = (
|
| 559 |
-
(torch.exp(log_alpha_t - log_alpha_prev_0)) * x
|
| 560 |
-
- (sigma_t * h_phi_1) * model_prev_0
|
| 561 |
-
)
|
| 562 |
-
# now predictor
|
| 563 |
-
x_t = x_t_
|
| 564 |
-
if len(D1s) > 0:
|
| 565 |
-
# compute the residuals for predictor
|
| 566 |
-
for k in range(K - 1):
|
| 567 |
-
x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
|
| 568 |
-
# now corrector
|
| 569 |
-
if use_corrector:
|
| 570 |
-
model_t = self.model_fn(x_t, t)
|
| 571 |
-
D1_t = (model_t - model_prev_0)
|
| 572 |
-
x_t = x_t_
|
| 573 |
-
k = 0
|
| 574 |
-
for k in range(K - 1):
|
| 575 |
-
x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
|
| 576 |
-
x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
|
| 577 |
-
return x_t, model_t
|
| 578 |
-
|
| 579 |
-
def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True):
|
| 580 |
-
# print(f'using unified predictor-corrector with order {order} (solver type: B(h))')
|
| 581 |
-
ns = self.noise_schedule
|
| 582 |
-
assert order <= len(model_prev_list)
|
| 583 |
-
dims = x.dim()
|
| 584 |
-
|
| 585 |
-
# first compute rks
|
| 586 |
-
t_prev_0 = t_prev_list[-1]
|
| 587 |
-
lambda_prev_0 = ns.marginal_lambda(t_prev_0)
|
| 588 |
-
lambda_t = ns.marginal_lambda(t)
|
| 589 |
-
model_prev_0 = model_prev_list[-1]
|
| 590 |
-
sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
|
| 591 |
-
log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
|
| 592 |
-
alpha_t = torch.exp(log_alpha_t)
|
| 593 |
-
|
| 594 |
-
h = lambda_t - lambda_prev_0
|
| 595 |
-
|
| 596 |
-
rks = []
|
| 597 |
-
D1s = []
|
| 598 |
-
for i in range(1, order):
|
| 599 |
-
t_prev_i = t_prev_list[-(i + 1)]
|
| 600 |
-
model_prev_i = model_prev_list[-(i + 1)]
|
| 601 |
-
lambda_prev_i = ns.marginal_lambda(t_prev_i)
|
| 602 |
-
rk = ((lambda_prev_i - lambda_prev_0) / h)[0]
|
| 603 |
-
rks.append(rk)
|
| 604 |
-
D1s.append((model_prev_i - model_prev_0) / rk)
|
| 605 |
-
|
| 606 |
-
rks.append(1.)
|
| 607 |
-
rks = torch.tensor(rks, device=x.device)
|
| 608 |
-
|
| 609 |
-
R = []
|
| 610 |
-
b = []
|
| 611 |
-
|
| 612 |
-
hh = -h[0] if self.predict_x0 else h[0]
|
| 613 |
-
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 614 |
-
h_phi_k = h_phi_1 / hh - 1
|
| 615 |
-
|
| 616 |
-
factorial_i = 1
|
| 617 |
-
|
| 618 |
-
if self.variant == 'bh1':
|
| 619 |
-
B_h = hh
|
| 620 |
-
elif self.variant == 'bh2':
|
| 621 |
-
B_h = torch.expm1(hh)
|
| 622 |
-
else:
|
| 623 |
-
raise NotImplementedError()
|
| 624 |
-
|
| 625 |
-
for i in range(1, order + 1):
|
| 626 |
-
R.append(torch.pow(rks, i - 1))
|
| 627 |
-
b.append(h_phi_k * factorial_i / B_h)
|
| 628 |
-
factorial_i *= (i + 1)
|
| 629 |
-
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 630 |
-
|
| 631 |
-
R = torch.stack(R)
|
| 632 |
-
b = torch.tensor(b, device=x.device)
|
| 633 |
-
|
| 634 |
-
# now predictor
|
| 635 |
-
use_predictor = len(D1s) > 0 and x_t is None
|
| 636 |
-
if len(D1s) > 0:
|
| 637 |
-
D1s = torch.stack(D1s, dim=1) # (B, K)
|
| 638 |
-
if x_t is None:
|
| 639 |
-
# for order 2, we use a simplified version
|
| 640 |
-
if order == 2:
|
| 641 |
-
rhos_p = torch.tensor([0.5], device=b.device)
|
| 642 |
-
else:
|
| 643 |
-
rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1])
|
| 644 |
-
else:
|
| 645 |
-
D1s = None
|
| 646 |
-
|
| 647 |
-
if use_corrector:
|
| 648 |
-
# print('using corrector')
|
| 649 |
-
# for order 1, we use a simplified version
|
| 650 |
-
if order == 1:
|
| 651 |
-
rhos_c = torch.tensor([0.5], device=b.device)
|
| 652 |
-
else:
|
| 653 |
-
rhos_c = torch.linalg.solve(R, b)
|
| 654 |
-
|
| 655 |
-
model_t = None
|
| 656 |
-
if self.predict_x0:
|
| 657 |
-
x_t_ = (
|
| 658 |
-
expand_dims(sigma_t / sigma_prev_0, dims) * x
|
| 659 |
-
- expand_dims(alpha_t * h_phi_1, dims)* model_prev_0
|
| 660 |
-
)
|
| 661 |
-
|
| 662 |
-
if x_t is None:
|
| 663 |
-
if use_predictor:
|
| 664 |
-
pred_res = torch.tensordot(D1s, rhos_p, dims=([1], [0])) # torch.einsum('k,bkchw->bchw', rhos_p, D1s)
|
| 665 |
-
else:
|
| 666 |
-
pred_res = 0
|
| 667 |
-
x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res
|
| 668 |
-
|
| 669 |
-
if use_corrector:
|
| 670 |
-
model_t = self.model_fn(x_t, t)
|
| 671 |
-
if D1s is not None:
|
| 672 |
-
corr_res = torch.tensordot(D1s, rhos_c[:-1], dims=([1], [0])) # torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
|
| 673 |
-
else:
|
| 674 |
-
corr_res = 0
|
| 675 |
-
D1_t = (model_t - model_prev_0)
|
| 676 |
-
x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
|
| 677 |
-
else:
|
| 678 |
-
x_t_ = (
|
| 679 |
-
expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
|
| 680 |
-
- expand_dims(sigma_t * h_phi_1, dims) * model_prev_0
|
| 681 |
-
)
|
| 682 |
-
if x_t is None:
|
| 683 |
-
if use_predictor:
|
| 684 |
-
pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
|
| 685 |
-
else:
|
| 686 |
-
pred_res = 0
|
| 687 |
-
x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res
|
| 688 |
-
|
| 689 |
-
if use_corrector:
|
| 690 |
-
model_t = self.model_fn(x_t, t)
|
| 691 |
-
if D1s is not None:
|
| 692 |
-
corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
|
| 693 |
-
else:
|
| 694 |
-
corr_res = 0
|
| 695 |
-
D1_t = (model_t - model_prev_0)
|
| 696 |
-
x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
|
| 697 |
-
return x_t, model_t
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
def sample(self, x, timesteps, t_start=None, t_end=None, order=3, skip_type='time_uniform',
|
| 701 |
-
method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
|
| 702 |
-
atol=0.0078, rtol=0.05, corrector=False, callback=None, disable_pbar=False
|
| 703 |
-
):
|
| 704 |
-
# t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
|
| 705 |
-
# t_T = self.noise_schedule.T if t_start is None else t_start
|
| 706 |
-
steps = len(timesteps) - 1
|
| 707 |
-
if method == 'multistep':
|
| 708 |
-
assert steps >= order
|
| 709 |
-
# timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
|
| 710 |
-
assert timesteps.shape[0] - 1 == steps
|
| 711 |
-
# with torch.no_grad():
|
| 712 |
-
for step_index in trange(steps, disable=disable_pbar):
|
| 713 |
-
if step_index == 0:
|
| 714 |
-
vec_t = timesteps[0].expand((x.shape[0]))
|
| 715 |
-
model_prev_list = [self.model_fn(x, vec_t)]
|
| 716 |
-
t_prev_list = [vec_t]
|
| 717 |
-
elif step_index < order:
|
| 718 |
-
init_order = step_index
|
| 719 |
-
# Init the first `order` values by lower order multistep DPM-Solver.
|
| 720 |
-
# for init_order in range(1, order):
|
| 721 |
-
vec_t = timesteps[init_order].expand(x.shape[0])
|
| 722 |
-
x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True)
|
| 723 |
-
if model_x is None:
|
| 724 |
-
model_x = self.model_fn(x, vec_t)
|
| 725 |
-
model_prev_list.append(model_x)
|
| 726 |
-
t_prev_list.append(vec_t)
|
| 727 |
-
else:
|
| 728 |
-
extra_final_step = 0
|
| 729 |
-
if step_index == (steps - 1):
|
| 730 |
-
extra_final_step = 1
|
| 731 |
-
for step in range(step_index, step_index + 1 + extra_final_step):
|
| 732 |
-
vec_t = timesteps[step].expand(x.shape[0])
|
| 733 |
-
if lower_order_final:
|
| 734 |
-
step_order = min(order, steps + 1 - step)
|
| 735 |
-
else:
|
| 736 |
-
step_order = order
|
| 737 |
-
# print('this step order:', step_order)
|
| 738 |
-
if step == steps:
|
| 739 |
-
# print('do not run corrector at the last step')
|
| 740 |
-
use_corrector = False
|
| 741 |
-
else:
|
| 742 |
-
use_corrector = True
|
| 743 |
-
x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector)
|
| 744 |
-
for i in range(order - 1):
|
| 745 |
-
t_prev_list[i] = t_prev_list[i + 1]
|
| 746 |
-
model_prev_list[i] = model_prev_list[i + 1]
|
| 747 |
-
t_prev_list[-1] = vec_t
|
| 748 |
-
# We do not need to evaluate the final model value.
|
| 749 |
-
if step < steps:
|
| 750 |
-
if model_x is None:
|
| 751 |
-
model_x = self.model_fn(x, vec_t)
|
| 752 |
-
model_prev_list[-1] = model_x
|
| 753 |
-
if callback is not None:
|
| 754 |
-
callback({'x': x, 'i': step_index, 'denoised': model_prev_list[-1]})
|
| 755 |
-
else:
|
| 756 |
-
raise NotImplementedError()
|
| 757 |
-
# if denoise_to_zero:
|
| 758 |
-
# x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
|
| 759 |
-
return x
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
#############################################################
|
| 763 |
-
# other utility functions
|
| 764 |
-
#############################################################
|
| 765 |
-
|
| 766 |
-
def interpolate_fn(x, xp, yp):
|
| 767 |
-
"""
|
| 768 |
-
A piecewise linear function y = f(x), using xp and yp as keypoints.
|
| 769 |
-
We implement f(x) in a differentiable way (i.e. applicable for autograd).
|
| 770 |
-
The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
|
| 771 |
-
|
| 772 |
-
Args:
|
| 773 |
-
x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
|
| 774 |
-
xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
|
| 775 |
-
yp: PyTorch tensor with shape [C, K].
|
| 776 |
-
Returns:
|
| 777 |
-
The function values f(x), with shape [N, C].
|
| 778 |
-
"""
|
| 779 |
-
N, K = x.shape[0], xp.shape[1]
|
| 780 |
-
all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
|
| 781 |
-
sorted_all_x, x_indices = torch.sort(all_x, dim=2)
|
| 782 |
-
x_idx = torch.argmin(x_indices, dim=2)
|
| 783 |
-
cand_start_idx = x_idx - 1
|
| 784 |
-
start_idx = torch.where(
|
| 785 |
-
torch.eq(x_idx, 0),
|
| 786 |
-
torch.tensor(1, device=x.device),
|
| 787 |
-
torch.where(
|
| 788 |
-
torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
|
| 789 |
-
),
|
| 790 |
-
)
|
| 791 |
-
end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
|
| 792 |
-
start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
|
| 793 |
-
end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
|
| 794 |
-
start_idx2 = torch.where(
|
| 795 |
-
torch.eq(x_idx, 0),
|
| 796 |
-
torch.tensor(0, device=x.device),
|
| 797 |
-
torch.where(
|
| 798 |
-
torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
|
| 799 |
-
),
|
| 800 |
-
)
|
| 801 |
-
y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
|
| 802 |
-
start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
|
| 803 |
-
end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
|
| 804 |
-
cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
|
| 805 |
-
return cand
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
def expand_dims(v, dims):
|
| 809 |
-
"""
|
| 810 |
-
Expand the tensor `v` to the dim `dims`.
|
| 811 |
-
|
| 812 |
-
Args:
|
| 813 |
-
`v`: a PyTorch tensor with shape [N].
|
| 814 |
-
`dim`: a `int`.
|
| 815 |
-
Returns:
|
| 816 |
-
a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
|
| 817 |
-
"""
|
| 818 |
-
return v[(...,) + (None,)*(dims - 1)]
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
class SigmaConvert:
|
| 822 |
-
schedule = ""
|
| 823 |
-
def marginal_log_mean_coeff(self, sigma):
|
| 824 |
-
return 0.5 * torch.log(1 / ((sigma * sigma) + 1))
|
| 825 |
-
|
| 826 |
-
def marginal_alpha(self, t):
|
| 827 |
-
return torch.exp(self.marginal_log_mean_coeff(t))
|
| 828 |
-
|
| 829 |
-
def marginal_std(self, t):
|
| 830 |
-
return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
|
| 831 |
-
|
| 832 |
-
def marginal_lambda(self, t):
|
| 833 |
-
"""
|
| 834 |
-
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
|
| 835 |
-
"""
|
| 836 |
-
log_mean_coeff = self.marginal_log_mean_coeff(t)
|
| 837 |
-
log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
|
| 838 |
-
return log_mean_coeff - log_std
|
| 839 |
-
|
| 840 |
-
def predict_eps_sigma(model, input, sigma_in, **kwargs):
|
| 841 |
-
sigma = sigma_in.view(sigma_in.shape[:1] + (1,) * (input.ndim - 1))
|
| 842 |
-
input = input * ((sigma ** 2 + 1.0) ** 0.5)
|
| 843 |
-
return (input - model(input, sigma_in, **kwargs)) / sigma
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
def sample_unipc(model, noise, sigmas, extra_args=None, callback=None, disable=False, variant='bh1'):
|
| 847 |
-
timesteps = sigmas.clone()
|
| 848 |
-
if sigmas[-1] == 0:
|
| 849 |
-
timesteps = sigmas[:]
|
| 850 |
-
timesteps[-1] = 0.001
|
| 851 |
-
else:
|
| 852 |
-
timesteps = sigmas.clone()
|
| 853 |
-
ns = SigmaConvert()
|
| 854 |
-
|
| 855 |
-
noise = noise / torch.sqrt(1.0 + timesteps[0] ** 2.0)
|
| 856 |
-
model_type = "noise"
|
| 857 |
-
|
| 858 |
-
model_fn = model_wrapper(
|
| 859 |
-
lambda input, sigma, **kwargs: predict_eps_sigma(model, input, sigma, **kwargs),
|
| 860 |
-
ns,
|
| 861 |
-
model_type=model_type,
|
| 862 |
-
guidance_type="uncond",
|
| 863 |
-
model_kwargs=extra_args,
|
| 864 |
-
)
|
| 865 |
-
|
| 866 |
-
order = min(3, len(timesteps) - 2)
|
| 867 |
-
uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, variant=variant)
|
| 868 |
-
x = uni_pc.sample(noise, timesteps=timesteps, skip_type="time_uniform", method="multistep", order=order, lower_order_final=True, callback=callback, disable_pbar=disable)
|
| 869 |
-
x /= ns.marginal_alpha(timesteps[-1])
|
| 870 |
-
return x
|
| 871 |
-
|
| 872 |
-
def sample_unipc_bh2(model, noise, sigmas, extra_args=None, callback=None, disable=False):
|
| 873 |
-
return sample_unipc(model, noise, sigmas, extra_args, callback, disable, variant='bh2')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/float.py
DELETED
|
@@ -1,67 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
|
| 3 |
-
def calc_mantissa(abs_x, exponent, normal_mask, MANTISSA_BITS, EXPONENT_BIAS, generator=None):
|
| 4 |
-
mantissa_scaled = torch.where(
|
| 5 |
-
normal_mask,
|
| 6 |
-
(abs_x / (2.0 ** (exponent - EXPONENT_BIAS)) - 1.0) * (2**MANTISSA_BITS),
|
| 7 |
-
(abs_x / (2.0 ** (-EXPONENT_BIAS + 1 - MANTISSA_BITS)))
|
| 8 |
-
)
|
| 9 |
-
|
| 10 |
-
mantissa_scaled += torch.rand(mantissa_scaled.size(), dtype=mantissa_scaled.dtype, layout=mantissa_scaled.layout, device=mantissa_scaled.device, generator=generator)
|
| 11 |
-
return mantissa_scaled.floor() / (2**MANTISSA_BITS)
|
| 12 |
-
|
| 13 |
-
#Not 100% sure about this
|
| 14 |
-
def manual_stochastic_round_to_float8(x, dtype, generator=None):
|
| 15 |
-
if dtype == torch.float8_e4m3fn:
|
| 16 |
-
EXPONENT_BITS, MANTISSA_BITS, EXPONENT_BIAS = 4, 3, 7
|
| 17 |
-
elif dtype == torch.float8_e5m2:
|
| 18 |
-
EXPONENT_BITS, MANTISSA_BITS, EXPONENT_BIAS = 5, 2, 15
|
| 19 |
-
else:
|
| 20 |
-
raise ValueError("Unsupported dtype")
|
| 21 |
-
|
| 22 |
-
x = x.half()
|
| 23 |
-
sign = torch.sign(x)
|
| 24 |
-
abs_x = x.abs()
|
| 25 |
-
sign = torch.where(abs_x == 0, 0, sign)
|
| 26 |
-
|
| 27 |
-
# Combine exponent calculation and clamping
|
| 28 |
-
exponent = torch.clamp(
|
| 29 |
-
torch.floor(torch.log2(abs_x)) + EXPONENT_BIAS,
|
| 30 |
-
0, 2**EXPONENT_BITS - 1
|
| 31 |
-
)
|
| 32 |
-
|
| 33 |
-
# Combine mantissa calculation and rounding
|
| 34 |
-
normal_mask = ~(exponent == 0)
|
| 35 |
-
|
| 36 |
-
abs_x[:] = calc_mantissa(abs_x, exponent, normal_mask, MANTISSA_BITS, EXPONENT_BIAS, generator=generator)
|
| 37 |
-
|
| 38 |
-
sign *= torch.where(
|
| 39 |
-
normal_mask,
|
| 40 |
-
(2.0 ** (exponent - EXPONENT_BIAS)) * (1.0 + abs_x),
|
| 41 |
-
(2.0 ** (-EXPONENT_BIAS + 1)) * abs_x
|
| 42 |
-
)
|
| 43 |
-
|
| 44 |
-
inf = torch.finfo(dtype)
|
| 45 |
-
torch.clamp(sign, min=inf.min, max=inf.max, out=sign)
|
| 46 |
-
return sign
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def stochastic_rounding(value, dtype, seed=0):
|
| 51 |
-
if dtype == torch.float32:
|
| 52 |
-
return value.to(dtype=torch.float32)
|
| 53 |
-
if dtype == torch.float16:
|
| 54 |
-
return value.to(dtype=torch.float16)
|
| 55 |
-
if dtype == torch.bfloat16:
|
| 56 |
-
return value.to(dtype=torch.bfloat16)
|
| 57 |
-
if dtype == torch.float8_e4m3fn or dtype == torch.float8_e5m2:
|
| 58 |
-
generator = torch.Generator(device=value.device)
|
| 59 |
-
generator.manual_seed(seed)
|
| 60 |
-
output = torch.empty_like(value, dtype=dtype)
|
| 61 |
-
num_slices = max(1, (value.numel() / (4096 * 4096)))
|
| 62 |
-
slice_size = max(1, round(value.shape[0] / num_slices))
|
| 63 |
-
for i in range(0, value.shape[0], slice_size):
|
| 64 |
-
output[i:i+slice_size].copy_(manual_stochastic_round_to_float8(value[i:i+slice_size], dtype, generator=generator))
|
| 65 |
-
return output
|
| 66 |
-
|
| 67 |
-
return value.to(dtype=dtype)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/gligen.py
DELETED
|
@@ -1,299 +0,0 @@
|
|
| 1 |
-
import math
|
| 2 |
-
import torch
|
| 3 |
-
from torch import nn
|
| 4 |
-
from .ldm.modules.attention import CrossAttention, FeedForward
|
| 5 |
-
import comfy.ops
|
| 6 |
-
ops = comfy.ops.manual_cast
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
class GatedCrossAttentionDense(nn.Module):
|
| 10 |
-
def __init__(self, query_dim, context_dim, n_heads, d_head):
|
| 11 |
-
super().__init__()
|
| 12 |
-
|
| 13 |
-
self.attn = CrossAttention(
|
| 14 |
-
query_dim=query_dim,
|
| 15 |
-
context_dim=context_dim,
|
| 16 |
-
heads=n_heads,
|
| 17 |
-
dim_head=d_head,
|
| 18 |
-
operations=ops)
|
| 19 |
-
self.ff = FeedForward(query_dim, glu=True)
|
| 20 |
-
|
| 21 |
-
self.norm1 = ops.LayerNorm(query_dim)
|
| 22 |
-
self.norm2 = ops.LayerNorm(query_dim)
|
| 23 |
-
|
| 24 |
-
self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
|
| 25 |
-
self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
|
| 26 |
-
|
| 27 |
-
# this can be useful: we can externally change magnitude of tanh(alpha)
|
| 28 |
-
# for example, when it is set to 0, then the entire model is same as
|
| 29 |
-
# original one
|
| 30 |
-
self.scale = 1
|
| 31 |
-
|
| 32 |
-
def forward(self, x, objs):
|
| 33 |
-
|
| 34 |
-
x = x + self.scale * \
|
| 35 |
-
torch.tanh(self.alpha_attn) * self.attn(self.norm1(x), objs, objs)
|
| 36 |
-
x = x + self.scale * \
|
| 37 |
-
torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
|
| 38 |
-
|
| 39 |
-
return x
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
class GatedSelfAttentionDense(nn.Module):
|
| 43 |
-
def __init__(self, query_dim, context_dim, n_heads, d_head):
|
| 44 |
-
super().__init__()
|
| 45 |
-
|
| 46 |
-
# we need a linear projection since we need cat visual feature and obj
|
| 47 |
-
# feature
|
| 48 |
-
self.linear = ops.Linear(context_dim, query_dim)
|
| 49 |
-
|
| 50 |
-
self.attn = CrossAttention(
|
| 51 |
-
query_dim=query_dim,
|
| 52 |
-
context_dim=query_dim,
|
| 53 |
-
heads=n_heads,
|
| 54 |
-
dim_head=d_head,
|
| 55 |
-
operations=ops)
|
| 56 |
-
self.ff = FeedForward(query_dim, glu=True)
|
| 57 |
-
|
| 58 |
-
self.norm1 = ops.LayerNorm(query_dim)
|
| 59 |
-
self.norm2 = ops.LayerNorm(query_dim)
|
| 60 |
-
|
| 61 |
-
self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
|
| 62 |
-
self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
|
| 63 |
-
|
| 64 |
-
# this can be useful: we can externally change magnitude of tanh(alpha)
|
| 65 |
-
# for example, when it is set to 0, then the entire model is same as
|
| 66 |
-
# original one
|
| 67 |
-
self.scale = 1
|
| 68 |
-
|
| 69 |
-
def forward(self, x, objs):
|
| 70 |
-
|
| 71 |
-
N_visual = x.shape[1]
|
| 72 |
-
objs = self.linear(objs)
|
| 73 |
-
|
| 74 |
-
x = x + self.scale * torch.tanh(self.alpha_attn) * self.attn(
|
| 75 |
-
self.norm1(torch.cat([x, objs], dim=1)))[:, 0:N_visual, :]
|
| 76 |
-
x = x + self.scale * \
|
| 77 |
-
torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
|
| 78 |
-
|
| 79 |
-
return x
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
class GatedSelfAttentionDense2(nn.Module):
|
| 83 |
-
def __init__(self, query_dim, context_dim, n_heads, d_head):
|
| 84 |
-
super().__init__()
|
| 85 |
-
|
| 86 |
-
# we need a linear projection since we need cat visual feature and obj
|
| 87 |
-
# feature
|
| 88 |
-
self.linear = ops.Linear(context_dim, query_dim)
|
| 89 |
-
|
| 90 |
-
self.attn = CrossAttention(
|
| 91 |
-
query_dim=query_dim, context_dim=query_dim, dim_head=d_head, operations=ops)
|
| 92 |
-
self.ff = FeedForward(query_dim, glu=True)
|
| 93 |
-
|
| 94 |
-
self.norm1 = ops.LayerNorm(query_dim)
|
| 95 |
-
self.norm2 = ops.LayerNorm(query_dim)
|
| 96 |
-
|
| 97 |
-
self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
|
| 98 |
-
self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
|
| 99 |
-
|
| 100 |
-
# this can be useful: we can externally change magnitude of tanh(alpha)
|
| 101 |
-
# for example, when it is set to 0, then the entire model is same as
|
| 102 |
-
# original one
|
| 103 |
-
self.scale = 1
|
| 104 |
-
|
| 105 |
-
def forward(self, x, objs):
|
| 106 |
-
|
| 107 |
-
B, N_visual, _ = x.shape
|
| 108 |
-
B, N_ground, _ = objs.shape
|
| 109 |
-
|
| 110 |
-
objs = self.linear(objs)
|
| 111 |
-
|
| 112 |
-
# sanity check
|
| 113 |
-
size_v = math.sqrt(N_visual)
|
| 114 |
-
size_g = math.sqrt(N_ground)
|
| 115 |
-
assert int(size_v) == size_v, "Visual tokens must be square rootable"
|
| 116 |
-
assert int(size_g) == size_g, "Grounding tokens must be square rootable"
|
| 117 |
-
size_v = int(size_v)
|
| 118 |
-
size_g = int(size_g)
|
| 119 |
-
|
| 120 |
-
# select grounding token and resize it to visual token size as residual
|
| 121 |
-
out = self.attn(self.norm1(torch.cat([x, objs], dim=1)))[
|
| 122 |
-
:, N_visual:, :]
|
| 123 |
-
out = out.permute(0, 2, 1).reshape(B, -1, size_g, size_g)
|
| 124 |
-
out = torch.nn.functional.interpolate(
|
| 125 |
-
out, (size_v, size_v), mode='bicubic')
|
| 126 |
-
residual = out.reshape(B, -1, N_visual).permute(0, 2, 1)
|
| 127 |
-
|
| 128 |
-
# add residual to visual feature
|
| 129 |
-
x = x + self.scale * torch.tanh(self.alpha_attn) * residual
|
| 130 |
-
x = x + self.scale * \
|
| 131 |
-
torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
|
| 132 |
-
|
| 133 |
-
return x
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class FourierEmbedder():
|
| 137 |
-
def __init__(self, num_freqs=64, temperature=100):
|
| 138 |
-
|
| 139 |
-
self.num_freqs = num_freqs
|
| 140 |
-
self.temperature = temperature
|
| 141 |
-
self.freq_bands = temperature ** (torch.arange(num_freqs) / num_freqs)
|
| 142 |
-
|
| 143 |
-
@torch.no_grad()
|
| 144 |
-
def __call__(self, x, cat_dim=-1):
|
| 145 |
-
"x: arbitrary shape of tensor. dim: cat dim"
|
| 146 |
-
out = []
|
| 147 |
-
for freq in self.freq_bands:
|
| 148 |
-
out.append(torch.sin(freq * x))
|
| 149 |
-
out.append(torch.cos(freq * x))
|
| 150 |
-
return torch.cat(out, cat_dim)
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
class PositionNet(nn.Module):
|
| 154 |
-
def __init__(self, in_dim, out_dim, fourier_freqs=8):
|
| 155 |
-
super().__init__()
|
| 156 |
-
self.in_dim = in_dim
|
| 157 |
-
self.out_dim = out_dim
|
| 158 |
-
|
| 159 |
-
self.fourier_embedder = FourierEmbedder(num_freqs=fourier_freqs)
|
| 160 |
-
self.position_dim = fourier_freqs * 2 * 4 # 2 is sin&cos, 4 is xyxy
|
| 161 |
-
|
| 162 |
-
self.linears = nn.Sequential(
|
| 163 |
-
ops.Linear(self.in_dim + self.position_dim, 512),
|
| 164 |
-
nn.SiLU(),
|
| 165 |
-
ops.Linear(512, 512),
|
| 166 |
-
nn.SiLU(),
|
| 167 |
-
ops.Linear(512, out_dim),
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
self.null_positive_feature = torch.nn.Parameter(
|
| 171 |
-
torch.zeros([self.in_dim]))
|
| 172 |
-
self.null_position_feature = torch.nn.Parameter(
|
| 173 |
-
torch.zeros([self.position_dim]))
|
| 174 |
-
|
| 175 |
-
def forward(self, boxes, masks, positive_embeddings):
|
| 176 |
-
B, N, _ = boxes.shape
|
| 177 |
-
masks = masks.unsqueeze(-1)
|
| 178 |
-
positive_embeddings = positive_embeddings
|
| 179 |
-
|
| 180 |
-
# embedding position (it may includes padding as placeholder)
|
| 181 |
-
xyxy_embedding = self.fourier_embedder(boxes) # B*N*4 --> B*N*C
|
| 182 |
-
|
| 183 |
-
# learnable null embedding
|
| 184 |
-
positive_null = self.null_positive_feature.to(device=boxes.device, dtype=boxes.dtype).view(1, 1, -1)
|
| 185 |
-
xyxy_null = self.null_position_feature.to(device=boxes.device, dtype=boxes.dtype).view(1, 1, -1)
|
| 186 |
-
|
| 187 |
-
# replace padding with learnable null embedding
|
| 188 |
-
positive_embeddings = positive_embeddings * \
|
| 189 |
-
masks + (1 - masks) * positive_null
|
| 190 |
-
xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
|
| 191 |
-
|
| 192 |
-
objs = self.linears(
|
| 193 |
-
torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
|
| 194 |
-
assert objs.shape == torch.Size([B, N, self.out_dim])
|
| 195 |
-
return objs
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
class Gligen(nn.Module):
|
| 199 |
-
def __init__(self, modules, position_net, key_dim):
|
| 200 |
-
super().__init__()
|
| 201 |
-
self.module_list = nn.ModuleList(modules)
|
| 202 |
-
self.position_net = position_net
|
| 203 |
-
self.key_dim = key_dim
|
| 204 |
-
self.max_objs = 30
|
| 205 |
-
self.current_device = torch.device("cpu")
|
| 206 |
-
|
| 207 |
-
def _set_position(self, boxes, masks, positive_embeddings):
|
| 208 |
-
objs = self.position_net(boxes, masks, positive_embeddings)
|
| 209 |
-
def func(x, extra_options):
|
| 210 |
-
key = extra_options["transformer_index"]
|
| 211 |
-
module = self.module_list[key]
|
| 212 |
-
return module(x, objs.to(device=x.device, dtype=x.dtype))
|
| 213 |
-
return func
|
| 214 |
-
|
| 215 |
-
def set_position(self, latent_image_shape, position_params, device):
|
| 216 |
-
batch, c, h, w = latent_image_shape
|
| 217 |
-
masks = torch.zeros([self.max_objs], device="cpu")
|
| 218 |
-
boxes = []
|
| 219 |
-
positive_embeddings = []
|
| 220 |
-
for p in position_params:
|
| 221 |
-
x1 = (p[4]) / w
|
| 222 |
-
y1 = (p[3]) / h
|
| 223 |
-
x2 = (p[4] + p[2]) / w
|
| 224 |
-
y2 = (p[3] + p[1]) / h
|
| 225 |
-
masks[len(boxes)] = 1.0
|
| 226 |
-
boxes += [torch.tensor((x1, y1, x2, y2)).unsqueeze(0)]
|
| 227 |
-
positive_embeddings += [p[0]]
|
| 228 |
-
append_boxes = []
|
| 229 |
-
append_conds = []
|
| 230 |
-
if len(boxes) < self.max_objs:
|
| 231 |
-
append_boxes = [torch.zeros(
|
| 232 |
-
[self.max_objs - len(boxes), 4], device="cpu")]
|
| 233 |
-
append_conds = [torch.zeros(
|
| 234 |
-
[self.max_objs - len(boxes), self.key_dim], device="cpu")]
|
| 235 |
-
|
| 236 |
-
box_out = torch.cat(
|
| 237 |
-
boxes + append_boxes).unsqueeze(0).repeat(batch, 1, 1)
|
| 238 |
-
masks = masks.unsqueeze(0).repeat(batch, 1)
|
| 239 |
-
conds = torch.cat(positive_embeddings +
|
| 240 |
-
append_conds).unsqueeze(0).repeat(batch, 1, 1)
|
| 241 |
-
return self._set_position(
|
| 242 |
-
box_out.to(device),
|
| 243 |
-
masks.to(device),
|
| 244 |
-
conds.to(device))
|
| 245 |
-
|
| 246 |
-
def set_empty(self, latent_image_shape, device):
|
| 247 |
-
batch, c, h, w = latent_image_shape
|
| 248 |
-
masks = torch.zeros([self.max_objs], device="cpu").repeat(batch, 1)
|
| 249 |
-
box_out = torch.zeros([self.max_objs, 4],
|
| 250 |
-
device="cpu").repeat(batch, 1, 1)
|
| 251 |
-
conds = torch.zeros([self.max_objs, self.key_dim],
|
| 252 |
-
device="cpu").repeat(batch, 1, 1)
|
| 253 |
-
return self._set_position(
|
| 254 |
-
box_out.to(device),
|
| 255 |
-
masks.to(device),
|
| 256 |
-
conds.to(device))
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
def load_gligen(sd):
|
| 260 |
-
sd_k = sd.keys()
|
| 261 |
-
output_list = []
|
| 262 |
-
key_dim = 768
|
| 263 |
-
for a in ["input_blocks", "middle_block", "output_blocks"]:
|
| 264 |
-
for b in range(20):
|
| 265 |
-
k_temp = filter(lambda k: "{}.{}.".format(a, b)
|
| 266 |
-
in k and ".fuser." in k, sd_k)
|
| 267 |
-
k_temp = map(lambda k: (k, k.split(".fuser.")[-1]), k_temp)
|
| 268 |
-
|
| 269 |
-
n_sd = {}
|
| 270 |
-
for k in k_temp:
|
| 271 |
-
n_sd[k[1]] = sd[k[0]]
|
| 272 |
-
if len(n_sd) > 0:
|
| 273 |
-
query_dim = n_sd["linear.weight"].shape[0]
|
| 274 |
-
key_dim = n_sd["linear.weight"].shape[1]
|
| 275 |
-
|
| 276 |
-
if key_dim == 768: # SD1.x
|
| 277 |
-
n_heads = 8
|
| 278 |
-
d_head = query_dim // n_heads
|
| 279 |
-
else:
|
| 280 |
-
d_head = 64
|
| 281 |
-
n_heads = query_dim // d_head
|
| 282 |
-
|
| 283 |
-
gated = GatedSelfAttentionDense(
|
| 284 |
-
query_dim, key_dim, n_heads, d_head)
|
| 285 |
-
gated.load_state_dict(n_sd, strict=False)
|
| 286 |
-
output_list.append(gated)
|
| 287 |
-
|
| 288 |
-
if "position_net.null_positive_feature" in sd_k:
|
| 289 |
-
in_dim = sd["position_net.null_positive_feature"].shape[0]
|
| 290 |
-
out_dim = sd["position_net.linears.4.weight"].shape[0]
|
| 291 |
-
|
| 292 |
-
class WeightsLoader(torch.nn.Module):
|
| 293 |
-
pass
|
| 294 |
-
w = WeightsLoader()
|
| 295 |
-
w.position_net = PositionNet(in_dim, out_dim)
|
| 296 |
-
w.load_state_dict(sd, strict=False)
|
| 297 |
-
|
| 298 |
-
gligen = Gligen(output_list, w.position_net, key_dim)
|
| 299 |
-
return gligen
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/hooks.py
DELETED
|
@@ -1,785 +0,0 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
from typing import TYPE_CHECKING, Callable
|
| 3 |
-
import enum
|
| 4 |
-
import math
|
| 5 |
-
import torch
|
| 6 |
-
import numpy as np
|
| 7 |
-
import itertools
|
| 8 |
-
import logging
|
| 9 |
-
|
| 10 |
-
if TYPE_CHECKING:
|
| 11 |
-
from comfy.model_patcher import ModelPatcher, PatcherInjection
|
| 12 |
-
from comfy.model_base import BaseModel
|
| 13 |
-
from comfy.sd import CLIP
|
| 14 |
-
import comfy.lora
|
| 15 |
-
import comfy.model_management
|
| 16 |
-
import comfy.patcher_extension
|
| 17 |
-
from node_helpers import conditioning_set_values
|
| 18 |
-
|
| 19 |
-
# #######################################################################################################
|
| 20 |
-
# Hooks explanation
|
| 21 |
-
# -------------------
|
| 22 |
-
# The purpose of hooks is to allow conds to influence sampling without the need for ComfyUI core code to
|
| 23 |
-
# make explicit special cases like it does for ControlNet and GLIGEN.
|
| 24 |
-
#
|
| 25 |
-
# This is necessary for nodes/features that are intended for use with masked or scheduled conds, or those
|
| 26 |
-
# that should run special code when a 'marked' cond is used in sampling.
|
| 27 |
-
# #######################################################################################################
|
| 28 |
-
|
| 29 |
-
class EnumHookMode(enum.Enum):
|
| 30 |
-
'''
|
| 31 |
-
Priority of hook memory optimization vs. speed, mostly related to WeightHooks.
|
| 32 |
-
|
| 33 |
-
MinVram: No caching will occur for any operations related to hooks.
|
| 34 |
-
MaxSpeed: Excess VRAM (and RAM, once VRAM is sufficiently depleted) will be used to cache hook weights when switching hook groups.
|
| 35 |
-
'''
|
| 36 |
-
MinVram = "minvram"
|
| 37 |
-
MaxSpeed = "maxspeed"
|
| 38 |
-
|
| 39 |
-
class EnumHookType(enum.Enum):
|
| 40 |
-
'''
|
| 41 |
-
Hook types, each of which has different expected behavior.
|
| 42 |
-
'''
|
| 43 |
-
Weight = "weight"
|
| 44 |
-
ObjectPatch = "object_patch"
|
| 45 |
-
AdditionalModels = "add_models"
|
| 46 |
-
TransformerOptions = "transformer_options"
|
| 47 |
-
Injections = "add_injections"
|
| 48 |
-
|
| 49 |
-
class EnumWeightTarget(enum.Enum):
|
| 50 |
-
Model = "model"
|
| 51 |
-
Clip = "clip"
|
| 52 |
-
|
| 53 |
-
class EnumHookScope(enum.Enum):
|
| 54 |
-
'''
|
| 55 |
-
Determines if hook should be limited in its influence over sampling.
|
| 56 |
-
|
| 57 |
-
AllConditioning: hook will affect all conds used in sampling.
|
| 58 |
-
HookedOnly: hook will only affect the conds it was attached to.
|
| 59 |
-
'''
|
| 60 |
-
AllConditioning = "all_conditioning"
|
| 61 |
-
HookedOnly = "hooked_only"
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
class _HookRef:
|
| 65 |
-
pass
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def default_should_register(hook: Hook, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
|
| 69 |
-
'''Example for how custom_should_register function can look like.'''
|
| 70 |
-
return True
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def create_target_dict(target: EnumWeightTarget=None, **kwargs) -> dict[str]:
|
| 74 |
-
'''Creates base dictionary for use with Hooks' target param.'''
|
| 75 |
-
d = {}
|
| 76 |
-
if target is not None:
|
| 77 |
-
d['target'] = target
|
| 78 |
-
d.update(kwargs)
|
| 79 |
-
return d
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
class Hook:
|
| 83 |
-
def __init__(self, hook_type: EnumHookType=None, hook_ref: _HookRef=None, hook_id: str=None,
|
| 84 |
-
hook_keyframe: HookKeyframeGroup=None, hook_scope=EnumHookScope.AllConditioning):
|
| 85 |
-
self.hook_type = hook_type
|
| 86 |
-
'''Enum identifying the general class of this hook.'''
|
| 87 |
-
self.hook_ref = hook_ref if hook_ref else _HookRef()
|
| 88 |
-
'''Reference shared between hook clones that have the same value. Should NOT be modified.'''
|
| 89 |
-
self.hook_id = hook_id
|
| 90 |
-
'''Optional string ID to identify hook; useful if need to consolidate duplicates at registration time.'''
|
| 91 |
-
self.hook_keyframe = hook_keyframe if hook_keyframe else HookKeyframeGroup()
|
| 92 |
-
'''Keyframe storage that can be referenced to get strength for current sampling step.'''
|
| 93 |
-
self.hook_scope = hook_scope
|
| 94 |
-
'''Scope of where this hook should apply in terms of the conds used in sampling run.'''
|
| 95 |
-
self.custom_should_register = default_should_register
|
| 96 |
-
'''Can be overriden with a compatible function to decide if this hook should be registered without the need to override .should_register'''
|
| 97 |
-
|
| 98 |
-
@property
|
| 99 |
-
def strength(self):
|
| 100 |
-
return self.hook_keyframe.strength
|
| 101 |
-
|
| 102 |
-
def initialize_timesteps(self, model: BaseModel):
|
| 103 |
-
self.reset()
|
| 104 |
-
self.hook_keyframe.initialize_timesteps(model)
|
| 105 |
-
|
| 106 |
-
def reset(self):
|
| 107 |
-
self.hook_keyframe.reset()
|
| 108 |
-
|
| 109 |
-
def clone(self):
|
| 110 |
-
c: Hook = self.__class__()
|
| 111 |
-
c.hook_type = self.hook_type
|
| 112 |
-
c.hook_ref = self.hook_ref
|
| 113 |
-
c.hook_id = self.hook_id
|
| 114 |
-
c.hook_keyframe = self.hook_keyframe
|
| 115 |
-
c.hook_scope = self.hook_scope
|
| 116 |
-
c.custom_should_register = self.custom_should_register
|
| 117 |
-
return c
|
| 118 |
-
|
| 119 |
-
def should_register(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
|
| 120 |
-
return self.custom_should_register(self, model, model_options, target_dict, registered)
|
| 121 |
-
|
| 122 |
-
def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
|
| 123 |
-
raise NotImplementedError("add_hook_patches should be defined for Hook subclasses")
|
| 124 |
-
|
| 125 |
-
def __eq__(self, other: Hook):
|
| 126 |
-
return self.__class__ == other.__class__ and self.hook_ref == other.hook_ref
|
| 127 |
-
|
| 128 |
-
def __hash__(self):
|
| 129 |
-
return hash(self.hook_ref)
|
| 130 |
-
|
| 131 |
-
class WeightHook(Hook):
|
| 132 |
-
'''
|
| 133 |
-
Hook responsible for tracking weights to be applied to some model/clip.
|
| 134 |
-
|
| 135 |
-
Note, value of hook_scope is ignored and is treated as HookedOnly.
|
| 136 |
-
'''
|
| 137 |
-
def __init__(self, strength_model=1.0, strength_clip=1.0):
|
| 138 |
-
super().__init__(hook_type=EnumHookType.Weight, hook_scope=EnumHookScope.HookedOnly)
|
| 139 |
-
self.weights: dict = None
|
| 140 |
-
self.weights_clip: dict = None
|
| 141 |
-
self.need_weight_init = True
|
| 142 |
-
self._strength_model = strength_model
|
| 143 |
-
self._strength_clip = strength_clip
|
| 144 |
-
self.hook_scope = EnumHookScope.HookedOnly # this value does not matter for WeightHooks, just for docs
|
| 145 |
-
|
| 146 |
-
@property
|
| 147 |
-
def strength_model(self):
|
| 148 |
-
return self._strength_model * self.strength
|
| 149 |
-
|
| 150 |
-
@property
|
| 151 |
-
def strength_clip(self):
|
| 152 |
-
return self._strength_clip * self.strength
|
| 153 |
-
|
| 154 |
-
def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
|
| 155 |
-
if not self.should_register(model, model_options, target_dict, registered):
|
| 156 |
-
return False
|
| 157 |
-
weights = None
|
| 158 |
-
|
| 159 |
-
target = target_dict.get('target', None)
|
| 160 |
-
if target == EnumWeightTarget.Clip:
|
| 161 |
-
strength = self._strength_clip
|
| 162 |
-
else:
|
| 163 |
-
strength = self._strength_model
|
| 164 |
-
|
| 165 |
-
if self.need_weight_init:
|
| 166 |
-
key_map = {}
|
| 167 |
-
if target == EnumWeightTarget.Clip:
|
| 168 |
-
key_map = comfy.lora.model_lora_keys_clip(model.model, key_map)
|
| 169 |
-
else:
|
| 170 |
-
key_map = comfy.lora.model_lora_keys_unet(model.model, key_map)
|
| 171 |
-
weights = comfy.lora.load_lora(self.weights, key_map, log_missing=False)
|
| 172 |
-
else:
|
| 173 |
-
if target == EnumWeightTarget.Clip:
|
| 174 |
-
weights = self.weights_clip
|
| 175 |
-
else:
|
| 176 |
-
weights = self.weights
|
| 177 |
-
model.add_hook_patches(hook=self, patches=weights, strength_patch=strength)
|
| 178 |
-
registered.add(self)
|
| 179 |
-
return True
|
| 180 |
-
# TODO: add logs about any keys that were not applied
|
| 181 |
-
|
| 182 |
-
def clone(self):
|
| 183 |
-
c: WeightHook = super().clone()
|
| 184 |
-
c.weights = self.weights
|
| 185 |
-
c.weights_clip = self.weights_clip
|
| 186 |
-
c.need_weight_init = self.need_weight_init
|
| 187 |
-
c._strength_model = self._strength_model
|
| 188 |
-
c._strength_clip = self._strength_clip
|
| 189 |
-
return c
|
| 190 |
-
|
| 191 |
-
class ObjectPatchHook(Hook):
|
| 192 |
-
def __init__(self, object_patches: dict[str]=None,
|
| 193 |
-
hook_scope=EnumHookScope.AllConditioning):
|
| 194 |
-
super().__init__(hook_type=EnumHookType.ObjectPatch)
|
| 195 |
-
self.object_patches = object_patches
|
| 196 |
-
self.hook_scope = hook_scope
|
| 197 |
-
|
| 198 |
-
def clone(self):
|
| 199 |
-
c: ObjectPatchHook = super().clone()
|
| 200 |
-
c.object_patches = self.object_patches
|
| 201 |
-
return c
|
| 202 |
-
|
| 203 |
-
def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
|
| 204 |
-
raise NotImplementedError("ObjectPatchHook is not supported yet in ComfyUI.")
|
| 205 |
-
|
| 206 |
-
class AdditionalModelsHook(Hook):
|
| 207 |
-
'''
|
| 208 |
-
Hook responsible for telling model management any additional models that should be loaded.
|
| 209 |
-
|
| 210 |
-
Note, value of hook_scope is ignored and is treated as AllConditioning.
|
| 211 |
-
'''
|
| 212 |
-
def __init__(self, models: list[ModelPatcher]=None, key: str=None):
|
| 213 |
-
super().__init__(hook_type=EnumHookType.AdditionalModels)
|
| 214 |
-
self.models = models
|
| 215 |
-
self.key = key
|
| 216 |
-
|
| 217 |
-
def clone(self):
|
| 218 |
-
c: AdditionalModelsHook = super().clone()
|
| 219 |
-
c.models = self.models.copy() if self.models else self.models
|
| 220 |
-
c.key = self.key
|
| 221 |
-
return c
|
| 222 |
-
|
| 223 |
-
def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
|
| 224 |
-
if not self.should_register(model, model_options, target_dict, registered):
|
| 225 |
-
return False
|
| 226 |
-
registered.add(self)
|
| 227 |
-
return True
|
| 228 |
-
|
| 229 |
-
class TransformerOptionsHook(Hook):
|
| 230 |
-
'''
|
| 231 |
-
Hook responsible for adding wrappers, callbacks, patches, or anything else related to transformer_options.
|
| 232 |
-
'''
|
| 233 |
-
def __init__(self, transformers_dict: dict[str, dict[str, dict[str, list[Callable]]]]=None,
|
| 234 |
-
hook_scope=EnumHookScope.AllConditioning):
|
| 235 |
-
super().__init__(hook_type=EnumHookType.TransformerOptions)
|
| 236 |
-
self.transformers_dict = transformers_dict
|
| 237 |
-
self.hook_scope = hook_scope
|
| 238 |
-
self._skip_adding = False
|
| 239 |
-
'''Internal value used to avoid double load of transformer_options when hook_scope is AllConditioning.'''
|
| 240 |
-
|
| 241 |
-
def clone(self):
|
| 242 |
-
c: TransformerOptionsHook = super().clone()
|
| 243 |
-
c.transformers_dict = self.transformers_dict
|
| 244 |
-
c._skip_adding = self._skip_adding
|
| 245 |
-
return c
|
| 246 |
-
|
| 247 |
-
def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
|
| 248 |
-
if not self.should_register(model, model_options, target_dict, registered):
|
| 249 |
-
return False
|
| 250 |
-
# NOTE: to_load_options will be used to manually load patches/wrappers/callbacks from hooks
|
| 251 |
-
self._skip_adding = False
|
| 252 |
-
if self.hook_scope == EnumHookScope.AllConditioning:
|
| 253 |
-
add_model_options = {"transformer_options": self.transformers_dict,
|
| 254 |
-
"to_load_options": self.transformers_dict}
|
| 255 |
-
# skip_adding if included in AllConditioning to avoid double loading
|
| 256 |
-
self._skip_adding = True
|
| 257 |
-
else:
|
| 258 |
-
add_model_options = {"to_load_options": self.transformers_dict}
|
| 259 |
-
registered.add(self)
|
| 260 |
-
comfy.patcher_extension.merge_nested_dicts(model_options, add_model_options, copy_dict1=False)
|
| 261 |
-
return True
|
| 262 |
-
|
| 263 |
-
def on_apply_hooks(self, model: ModelPatcher, transformer_options: dict[str]):
|
| 264 |
-
if not self._skip_adding:
|
| 265 |
-
comfy.patcher_extension.merge_nested_dicts(transformer_options, self.transformers_dict, copy_dict1=False)
|
| 266 |
-
|
| 267 |
-
WrapperHook = TransformerOptionsHook
|
| 268 |
-
'''Only here for backwards compatibility, WrapperHook is identical to TransformerOptionsHook.'''
|
| 269 |
-
|
| 270 |
-
class InjectionsHook(Hook):
|
| 271 |
-
def __init__(self, key: str=None, injections: list[PatcherInjection]=None,
|
| 272 |
-
hook_scope=EnumHookScope.AllConditioning):
|
| 273 |
-
super().__init__(hook_type=EnumHookType.Injections)
|
| 274 |
-
self.key = key
|
| 275 |
-
self.injections = injections
|
| 276 |
-
self.hook_scope = hook_scope
|
| 277 |
-
|
| 278 |
-
def clone(self):
|
| 279 |
-
c: InjectionsHook = super().clone()
|
| 280 |
-
c.key = self.key
|
| 281 |
-
c.injections = self.injections.copy() if self.injections else self.injections
|
| 282 |
-
return c
|
| 283 |
-
|
| 284 |
-
def add_hook_patches(self, model: ModelPatcher, model_options: dict, target_dict: dict[str], registered: HookGroup):
|
| 285 |
-
raise NotImplementedError("InjectionsHook is not supported yet in ComfyUI.")
|
| 286 |
-
|
| 287 |
-
class HookGroup:
|
| 288 |
-
'''
|
| 289 |
-
Stores groups of hooks, and allows them to be queried by type.
|
| 290 |
-
|
| 291 |
-
To prevent breaking their functionality, never modify the underlying self.hooks or self._hook_dict vars directly;
|
| 292 |
-
always use the provided functions on HookGroup.
|
| 293 |
-
'''
|
| 294 |
-
def __init__(self):
|
| 295 |
-
self.hooks: list[Hook] = []
|
| 296 |
-
self._hook_dict: dict[EnumHookType, list[Hook]] = {}
|
| 297 |
-
|
| 298 |
-
def __len__(self):
|
| 299 |
-
return len(self.hooks)
|
| 300 |
-
|
| 301 |
-
def add(self, hook: Hook):
|
| 302 |
-
if hook not in self.hooks:
|
| 303 |
-
self.hooks.append(hook)
|
| 304 |
-
self._hook_dict.setdefault(hook.hook_type, []).append(hook)
|
| 305 |
-
|
| 306 |
-
def remove(self, hook: Hook):
|
| 307 |
-
if hook in self.hooks:
|
| 308 |
-
self.hooks.remove(hook)
|
| 309 |
-
self._hook_dict[hook.hook_type].remove(hook)
|
| 310 |
-
|
| 311 |
-
def get_type(self, hook_type: EnumHookType):
|
| 312 |
-
return self._hook_dict.get(hook_type, [])
|
| 313 |
-
|
| 314 |
-
def contains(self, hook: Hook):
|
| 315 |
-
return hook in self.hooks
|
| 316 |
-
|
| 317 |
-
def is_subset_of(self, other: HookGroup):
|
| 318 |
-
self_hooks = set(self.hooks)
|
| 319 |
-
other_hooks = set(other.hooks)
|
| 320 |
-
return self_hooks.issubset(other_hooks)
|
| 321 |
-
|
| 322 |
-
def new_with_common_hooks(self, other: HookGroup):
|
| 323 |
-
c = HookGroup()
|
| 324 |
-
for hook in self.hooks:
|
| 325 |
-
if other.contains(hook):
|
| 326 |
-
c.add(hook.clone())
|
| 327 |
-
return c
|
| 328 |
-
|
| 329 |
-
def clone(self):
|
| 330 |
-
c = HookGroup()
|
| 331 |
-
for hook in self.hooks:
|
| 332 |
-
c.add(hook.clone())
|
| 333 |
-
return c
|
| 334 |
-
|
| 335 |
-
def clone_and_combine(self, other: HookGroup):
|
| 336 |
-
c = self.clone()
|
| 337 |
-
if other is not None:
|
| 338 |
-
for hook in other.hooks:
|
| 339 |
-
c.add(hook.clone())
|
| 340 |
-
return c
|
| 341 |
-
|
| 342 |
-
def set_keyframes_on_hooks(self, hook_kf: HookKeyframeGroup):
|
| 343 |
-
if hook_kf is None:
|
| 344 |
-
hook_kf = HookKeyframeGroup()
|
| 345 |
-
else:
|
| 346 |
-
hook_kf = hook_kf.clone()
|
| 347 |
-
for hook in self.hooks:
|
| 348 |
-
hook.hook_keyframe = hook_kf
|
| 349 |
-
|
| 350 |
-
def get_hooks_for_clip_schedule(self):
|
| 351 |
-
scheduled_hooks: dict[WeightHook, list[tuple[tuple[float,float], HookKeyframe]]] = {}
|
| 352 |
-
# only care about WeightHooks, for now
|
| 353 |
-
for hook in self.get_type(EnumHookType.Weight):
|
| 354 |
-
hook: WeightHook
|
| 355 |
-
hook_schedule = []
|
| 356 |
-
# if no hook keyframes, assign default value
|
| 357 |
-
if len(hook.hook_keyframe.keyframes) == 0:
|
| 358 |
-
hook_schedule.append(((0.0, 1.0), None))
|
| 359 |
-
scheduled_hooks[hook] = hook_schedule
|
| 360 |
-
continue
|
| 361 |
-
# find ranges of values
|
| 362 |
-
prev_keyframe = hook.hook_keyframe.keyframes[0]
|
| 363 |
-
for keyframe in hook.hook_keyframe.keyframes:
|
| 364 |
-
if keyframe.start_percent > prev_keyframe.start_percent and not math.isclose(keyframe.strength, prev_keyframe.strength):
|
| 365 |
-
hook_schedule.append(((prev_keyframe.start_percent, keyframe.start_percent), prev_keyframe))
|
| 366 |
-
prev_keyframe = keyframe
|
| 367 |
-
elif keyframe.start_percent == prev_keyframe.start_percent:
|
| 368 |
-
prev_keyframe = keyframe
|
| 369 |
-
# create final range, assuming last start_percent was not 1.0
|
| 370 |
-
if not math.isclose(prev_keyframe.start_percent, 1.0):
|
| 371 |
-
hook_schedule.append(((prev_keyframe.start_percent, 1.0), prev_keyframe))
|
| 372 |
-
scheduled_hooks[hook] = hook_schedule
|
| 373 |
-
# hooks should not have their schedules in a list of tuples
|
| 374 |
-
all_ranges: list[tuple[float, float]] = []
|
| 375 |
-
for range_kfs in scheduled_hooks.values():
|
| 376 |
-
for t_range, keyframe in range_kfs:
|
| 377 |
-
all_ranges.append(t_range)
|
| 378 |
-
# turn list of ranges into boundaries
|
| 379 |
-
boundaries_set = set(itertools.chain.from_iterable(all_ranges))
|
| 380 |
-
boundaries_set.add(0.0)
|
| 381 |
-
boundaries = sorted(boundaries_set)
|
| 382 |
-
real_ranges = [(boundaries[i], boundaries[i + 1]) for i in range(len(boundaries) - 1)]
|
| 383 |
-
# with real ranges defined, give appropriate hooks w/ keyframes for each range
|
| 384 |
-
scheduled_keyframes: list[tuple[tuple[float,float], list[tuple[WeightHook, HookKeyframe]]]] = []
|
| 385 |
-
for t_range in real_ranges:
|
| 386 |
-
hooks_schedule = []
|
| 387 |
-
for hook, val in scheduled_hooks.items():
|
| 388 |
-
keyframe = None
|
| 389 |
-
# check if is a keyframe that works for the current t_range
|
| 390 |
-
for stored_range, stored_kf in val:
|
| 391 |
-
# if stored start is less than current end, then fits - give it assigned keyframe
|
| 392 |
-
if stored_range[0] < t_range[1] and stored_range[1] > t_range[0]:
|
| 393 |
-
keyframe = stored_kf
|
| 394 |
-
break
|
| 395 |
-
hooks_schedule.append((hook, keyframe))
|
| 396 |
-
scheduled_keyframes.append((t_range, hooks_schedule))
|
| 397 |
-
return scheduled_keyframes
|
| 398 |
-
|
| 399 |
-
def reset(self):
|
| 400 |
-
for hook in self.hooks:
|
| 401 |
-
hook.reset()
|
| 402 |
-
|
| 403 |
-
@staticmethod
|
| 404 |
-
def combine_all_hooks(hooks_list: list[HookGroup], require_count=0) -> HookGroup:
|
| 405 |
-
actual: list[HookGroup] = []
|
| 406 |
-
for group in hooks_list:
|
| 407 |
-
if group is not None:
|
| 408 |
-
actual.append(group)
|
| 409 |
-
if len(actual) < require_count:
|
| 410 |
-
raise Exception(f"Need at least {require_count} hooks to combine, but only had {len(actual)}.")
|
| 411 |
-
# if no hooks, then return None
|
| 412 |
-
if len(actual) == 0:
|
| 413 |
-
return None
|
| 414 |
-
# if only 1 hook, just return itself without cloning
|
| 415 |
-
elif len(actual) == 1:
|
| 416 |
-
return actual[0]
|
| 417 |
-
final_hook: HookGroup = None
|
| 418 |
-
for hook in actual:
|
| 419 |
-
if final_hook is None:
|
| 420 |
-
final_hook = hook.clone()
|
| 421 |
-
else:
|
| 422 |
-
final_hook = final_hook.clone_and_combine(hook)
|
| 423 |
-
return final_hook
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
class HookKeyframe:
|
| 427 |
-
def __init__(self, strength: float, start_percent=0.0, guarantee_steps=1):
|
| 428 |
-
self.strength = strength
|
| 429 |
-
# scheduling
|
| 430 |
-
self.start_percent = float(start_percent)
|
| 431 |
-
self.start_t = 999999999.9
|
| 432 |
-
self.guarantee_steps = guarantee_steps
|
| 433 |
-
|
| 434 |
-
def get_effective_guarantee_steps(self, max_sigma: torch.Tensor):
|
| 435 |
-
'''If keyframe starts before current sampling range (max_sigma), treat as 0.'''
|
| 436 |
-
if self.start_t > max_sigma:
|
| 437 |
-
return 0
|
| 438 |
-
return self.guarantee_steps
|
| 439 |
-
|
| 440 |
-
def clone(self):
|
| 441 |
-
c = HookKeyframe(strength=self.strength,
|
| 442 |
-
start_percent=self.start_percent, guarantee_steps=self.guarantee_steps)
|
| 443 |
-
c.start_t = self.start_t
|
| 444 |
-
return c
|
| 445 |
-
|
| 446 |
-
class HookKeyframeGroup:
|
| 447 |
-
def __init__(self):
|
| 448 |
-
self.keyframes: list[HookKeyframe] = []
|
| 449 |
-
self._current_keyframe: HookKeyframe = None
|
| 450 |
-
self._current_used_steps = 0
|
| 451 |
-
self._current_index = 0
|
| 452 |
-
self._current_strength = None
|
| 453 |
-
self._curr_t = -1.
|
| 454 |
-
|
| 455 |
-
# properties shadow those of HookWeightsKeyframe
|
| 456 |
-
@property
|
| 457 |
-
def strength(self):
|
| 458 |
-
if self._current_keyframe is not None:
|
| 459 |
-
return self._current_keyframe.strength
|
| 460 |
-
return 1.0
|
| 461 |
-
|
| 462 |
-
def reset(self):
|
| 463 |
-
self._current_keyframe = None
|
| 464 |
-
self._current_used_steps = 0
|
| 465 |
-
self._current_index = 0
|
| 466 |
-
self._current_strength = None
|
| 467 |
-
self.curr_t = -1.
|
| 468 |
-
self._set_first_as_current()
|
| 469 |
-
|
| 470 |
-
def add(self, keyframe: HookKeyframe):
|
| 471 |
-
# add to end of list, then sort
|
| 472 |
-
self.keyframes.append(keyframe)
|
| 473 |
-
self.keyframes = get_sorted_list_via_attr(self.keyframes, "start_percent")
|
| 474 |
-
self._set_first_as_current()
|
| 475 |
-
|
| 476 |
-
def _set_first_as_current(self):
|
| 477 |
-
if len(self.keyframes) > 0:
|
| 478 |
-
self._current_keyframe = self.keyframes[0]
|
| 479 |
-
else:
|
| 480 |
-
self._current_keyframe = None
|
| 481 |
-
|
| 482 |
-
def has_guarantee_steps(self):
|
| 483 |
-
for kf in self.keyframes:
|
| 484 |
-
if kf.guarantee_steps > 0:
|
| 485 |
-
return True
|
| 486 |
-
return False
|
| 487 |
-
|
| 488 |
-
def has_index(self, index: int):
|
| 489 |
-
return index >= 0 and index < len(self.keyframes)
|
| 490 |
-
|
| 491 |
-
def is_empty(self):
|
| 492 |
-
return len(self.keyframes) == 0
|
| 493 |
-
|
| 494 |
-
def clone(self):
|
| 495 |
-
c = HookKeyframeGroup()
|
| 496 |
-
for keyframe in self.keyframes:
|
| 497 |
-
c.keyframes.append(keyframe.clone())
|
| 498 |
-
c._set_first_as_current()
|
| 499 |
-
return c
|
| 500 |
-
|
| 501 |
-
def initialize_timesteps(self, model: BaseModel):
|
| 502 |
-
for keyframe in self.keyframes:
|
| 503 |
-
keyframe.start_t = model.model_sampling.percent_to_sigma(keyframe.start_percent)
|
| 504 |
-
|
| 505 |
-
def prepare_current_keyframe(self, curr_t: float, transformer_options: dict[str, torch.Tensor]) -> bool:
|
| 506 |
-
if self.is_empty():
|
| 507 |
-
return False
|
| 508 |
-
if curr_t == self._curr_t:
|
| 509 |
-
return False
|
| 510 |
-
max_sigma = torch.max(transformer_options["sample_sigmas"])
|
| 511 |
-
prev_index = self._current_index
|
| 512 |
-
prev_strength = self._current_strength
|
| 513 |
-
# if met guaranteed steps, look for next keyframe in case need to switch
|
| 514 |
-
if self._current_used_steps >= self._current_keyframe.get_effective_guarantee_steps(max_sigma):
|
| 515 |
-
# if has next index, loop through and see if need to switch
|
| 516 |
-
if self.has_index(self._current_index+1):
|
| 517 |
-
for i in range(self._current_index+1, len(self.keyframes)):
|
| 518 |
-
eval_c = self.keyframes[i]
|
| 519 |
-
# check if start_t is greater or equal to curr_t
|
| 520 |
-
# NOTE: t is in terms of sigmas, not percent, so bigger number = earlier step in sampling
|
| 521 |
-
if eval_c.start_t >= curr_t:
|
| 522 |
-
self._current_index = i
|
| 523 |
-
self._current_strength = eval_c.strength
|
| 524 |
-
self._current_keyframe = eval_c
|
| 525 |
-
self._current_used_steps = 0
|
| 526 |
-
# if guarantee_steps greater than zero, stop searching for other keyframes
|
| 527 |
-
if self._current_keyframe.get_effective_guarantee_steps(max_sigma) > 0:
|
| 528 |
-
break
|
| 529 |
-
# if eval_c is outside the percent range, stop looking further
|
| 530 |
-
else: break
|
| 531 |
-
# update steps current context is used
|
| 532 |
-
self._current_used_steps += 1
|
| 533 |
-
# update current timestep this was performed on
|
| 534 |
-
self._curr_t = curr_t
|
| 535 |
-
# return True if keyframe changed, False if no change
|
| 536 |
-
return prev_index != self._current_index and prev_strength != self._current_strength
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
class InterpolationMethod:
|
| 540 |
-
LINEAR = "linear"
|
| 541 |
-
EASE_IN = "ease_in"
|
| 542 |
-
EASE_OUT = "ease_out"
|
| 543 |
-
EASE_IN_OUT = "ease_in_out"
|
| 544 |
-
|
| 545 |
-
_LIST = [LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT]
|
| 546 |
-
|
| 547 |
-
@classmethod
|
| 548 |
-
def get_weights(cls, num_from: float, num_to: float, length: int, method: str, reverse=False):
|
| 549 |
-
diff = num_to - num_from
|
| 550 |
-
if method == cls.LINEAR:
|
| 551 |
-
weights = torch.linspace(num_from, num_to, length)
|
| 552 |
-
elif method == cls.EASE_IN:
|
| 553 |
-
index = torch.linspace(0, 1, length)
|
| 554 |
-
weights = diff * np.power(index, 2) + num_from
|
| 555 |
-
elif method == cls.EASE_OUT:
|
| 556 |
-
index = torch.linspace(0, 1, length)
|
| 557 |
-
weights = diff * (1 - np.power(1 - index, 2)) + num_from
|
| 558 |
-
elif method == cls.EASE_IN_OUT:
|
| 559 |
-
index = torch.linspace(0, 1, length)
|
| 560 |
-
weights = diff * ((1 - np.cos(index * np.pi)) / 2) + num_from
|
| 561 |
-
else:
|
| 562 |
-
raise ValueError(f"Unrecognized interpolation method '{method}'.")
|
| 563 |
-
if reverse:
|
| 564 |
-
weights = weights.flip(dims=(0,))
|
| 565 |
-
return weights
|
| 566 |
-
|
| 567 |
-
def get_sorted_list_via_attr(objects: list, attr: str) -> list:
|
| 568 |
-
if not objects:
|
| 569 |
-
return objects
|
| 570 |
-
elif len(objects) <= 1:
|
| 571 |
-
return [x for x in objects]
|
| 572 |
-
# now that we know we have to sort, do it following these rules:
|
| 573 |
-
# a) if objects have same value of attribute, maintain their relative order
|
| 574 |
-
# b) perform sorting of the groups of objects with same attributes
|
| 575 |
-
unique_attrs = {}
|
| 576 |
-
for o in objects:
|
| 577 |
-
val_attr = getattr(o, attr)
|
| 578 |
-
attr_list: list = unique_attrs.get(val_attr, list())
|
| 579 |
-
attr_list.append(o)
|
| 580 |
-
if val_attr not in unique_attrs:
|
| 581 |
-
unique_attrs[val_attr] = attr_list
|
| 582 |
-
# now that we have the unique attr values grouped together in relative order, sort them by key
|
| 583 |
-
sorted_attrs = dict(sorted(unique_attrs.items()))
|
| 584 |
-
# now flatten out the dict into a list to return
|
| 585 |
-
sorted_list = []
|
| 586 |
-
for object_list in sorted_attrs.values():
|
| 587 |
-
sorted_list.extend(object_list)
|
| 588 |
-
return sorted_list
|
| 589 |
-
|
| 590 |
-
def create_transformer_options_from_hooks(model: ModelPatcher, hooks: HookGroup, transformer_options: dict[str]=None):
|
| 591 |
-
# if no hooks or is not a ModelPatcher for sampling, return empty dict
|
| 592 |
-
if hooks is None or model.is_clip:
|
| 593 |
-
return {}
|
| 594 |
-
if transformer_options is None:
|
| 595 |
-
transformer_options = {}
|
| 596 |
-
for hook in hooks.get_type(EnumHookType.TransformerOptions):
|
| 597 |
-
hook: TransformerOptionsHook
|
| 598 |
-
hook.on_apply_hooks(model, transformer_options)
|
| 599 |
-
return transformer_options
|
| 600 |
-
|
| 601 |
-
def create_hook_lora(lora: dict[str, torch.Tensor], strength_model: float, strength_clip: float):
|
| 602 |
-
hook_group = HookGroup()
|
| 603 |
-
hook = WeightHook(strength_model=strength_model, strength_clip=strength_clip)
|
| 604 |
-
hook_group.add(hook)
|
| 605 |
-
hook.weights = lora
|
| 606 |
-
return hook_group
|
| 607 |
-
|
| 608 |
-
def create_hook_model_as_lora(weights_model, weights_clip, strength_model: float, strength_clip: float):
|
| 609 |
-
hook_group = HookGroup()
|
| 610 |
-
hook = WeightHook(strength_model=strength_model, strength_clip=strength_clip)
|
| 611 |
-
hook_group.add(hook)
|
| 612 |
-
patches_model = None
|
| 613 |
-
patches_clip = None
|
| 614 |
-
if weights_model is not None:
|
| 615 |
-
patches_model = {}
|
| 616 |
-
for key in weights_model:
|
| 617 |
-
patches_model[key] = ("model_as_lora", (weights_model[key],))
|
| 618 |
-
if weights_clip is not None:
|
| 619 |
-
patches_clip = {}
|
| 620 |
-
for key in weights_clip:
|
| 621 |
-
patches_clip[key] = ("model_as_lora", (weights_clip[key],))
|
| 622 |
-
hook.weights = patches_model
|
| 623 |
-
hook.weights_clip = patches_clip
|
| 624 |
-
hook.need_weight_init = False
|
| 625 |
-
return hook_group
|
| 626 |
-
|
| 627 |
-
def get_patch_weights_from_model(model: ModelPatcher, discard_model_sampling=True):
|
| 628 |
-
if model is None:
|
| 629 |
-
return None
|
| 630 |
-
patches_model: dict[str, torch.Tensor] = model.model.state_dict()
|
| 631 |
-
if discard_model_sampling:
|
| 632 |
-
# do not include ANY model_sampling components of the model that should act as a patch
|
| 633 |
-
for key in list(patches_model.keys()):
|
| 634 |
-
if key.startswith("model_sampling"):
|
| 635 |
-
patches_model.pop(key, None)
|
| 636 |
-
return patches_model
|
| 637 |
-
|
| 638 |
-
# NOTE: this function shows how to register weight hooks directly on the ModelPatchers
|
| 639 |
-
def load_hook_lora_for_models(model: ModelPatcher, clip: CLIP, lora: dict[str, torch.Tensor],
|
| 640 |
-
strength_model: float, strength_clip: float):
|
| 641 |
-
key_map = {}
|
| 642 |
-
if model is not None:
|
| 643 |
-
key_map = comfy.lora.model_lora_keys_unet(model.model, key_map)
|
| 644 |
-
if clip is not None:
|
| 645 |
-
key_map = comfy.lora.model_lora_keys_clip(clip.cond_stage_model, key_map)
|
| 646 |
-
|
| 647 |
-
hook_group = HookGroup()
|
| 648 |
-
hook = WeightHook()
|
| 649 |
-
hook_group.add(hook)
|
| 650 |
-
loaded: dict[str] = comfy.lora.load_lora(lora, key_map)
|
| 651 |
-
if model is not None:
|
| 652 |
-
new_modelpatcher = model.clone()
|
| 653 |
-
k = new_modelpatcher.add_hook_patches(hook=hook, patches=loaded, strength_patch=strength_model)
|
| 654 |
-
else:
|
| 655 |
-
k = ()
|
| 656 |
-
new_modelpatcher = None
|
| 657 |
-
|
| 658 |
-
if clip is not None:
|
| 659 |
-
new_clip = clip.clone()
|
| 660 |
-
k1 = new_clip.patcher.add_hook_patches(hook=hook, patches=loaded, strength_patch=strength_clip)
|
| 661 |
-
else:
|
| 662 |
-
k1 = ()
|
| 663 |
-
new_clip = None
|
| 664 |
-
k = set(k)
|
| 665 |
-
k1 = set(k1)
|
| 666 |
-
for x in loaded:
|
| 667 |
-
if (x not in k) and (x not in k1):
|
| 668 |
-
logging.warning(f"NOT LOADED {x}")
|
| 669 |
-
return (new_modelpatcher, new_clip, hook_group)
|
| 670 |
-
|
| 671 |
-
def _combine_hooks_from_values(c_dict: dict[str, HookGroup], values: dict[str, HookGroup], cache: dict[tuple[HookGroup, HookGroup], HookGroup]):
|
| 672 |
-
hooks_key = 'hooks'
|
| 673 |
-
# if hooks only exist in one dict, do what's needed so that it ends up in c_dict
|
| 674 |
-
if hooks_key not in values:
|
| 675 |
-
return
|
| 676 |
-
if hooks_key not in c_dict:
|
| 677 |
-
hooks_value = values.get(hooks_key, None)
|
| 678 |
-
if hooks_value is not None:
|
| 679 |
-
c_dict[hooks_key] = hooks_value
|
| 680 |
-
return
|
| 681 |
-
# otherwise, need to combine with minimum duplication via cache
|
| 682 |
-
hooks_tuple = (c_dict[hooks_key], values[hooks_key])
|
| 683 |
-
cached_hooks = cache.get(hooks_tuple, None)
|
| 684 |
-
if cached_hooks is None:
|
| 685 |
-
new_hooks = hooks_tuple[0].clone_and_combine(hooks_tuple[1])
|
| 686 |
-
cache[hooks_tuple] = new_hooks
|
| 687 |
-
c_dict[hooks_key] = new_hooks
|
| 688 |
-
else:
|
| 689 |
-
c_dict[hooks_key] = cache[hooks_tuple]
|
| 690 |
-
|
| 691 |
-
def conditioning_set_values_with_hooks(conditioning, values={}, append_hooks=True,
|
| 692 |
-
cache: dict[tuple[HookGroup, HookGroup], HookGroup]=None):
|
| 693 |
-
c = []
|
| 694 |
-
if cache is None:
|
| 695 |
-
cache = {}
|
| 696 |
-
for t in conditioning:
|
| 697 |
-
n = [t[0], t[1].copy()]
|
| 698 |
-
for k in values:
|
| 699 |
-
if append_hooks and k == 'hooks':
|
| 700 |
-
_combine_hooks_from_values(n[1], values, cache)
|
| 701 |
-
else:
|
| 702 |
-
n[1][k] = values[k]
|
| 703 |
-
c.append(n)
|
| 704 |
-
|
| 705 |
-
return c
|
| 706 |
-
|
| 707 |
-
def set_hooks_for_conditioning(cond, hooks: HookGroup, append_hooks=True, cache: dict[tuple[HookGroup, HookGroup], HookGroup]=None):
|
| 708 |
-
if hooks is None:
|
| 709 |
-
return cond
|
| 710 |
-
return conditioning_set_values_with_hooks(cond, {'hooks': hooks}, append_hooks=append_hooks, cache=cache)
|
| 711 |
-
|
| 712 |
-
def set_timesteps_for_conditioning(cond, timestep_range: tuple[float,float]):
|
| 713 |
-
if timestep_range is None:
|
| 714 |
-
return cond
|
| 715 |
-
return conditioning_set_values(cond, {"start_percent": timestep_range[0],
|
| 716 |
-
"end_percent": timestep_range[1]})
|
| 717 |
-
|
| 718 |
-
def set_mask_for_conditioning(cond, mask: torch.Tensor, set_cond_area: str, strength: float):
|
| 719 |
-
if mask is None:
|
| 720 |
-
return cond
|
| 721 |
-
set_area_to_bounds = False
|
| 722 |
-
if set_cond_area != 'default':
|
| 723 |
-
set_area_to_bounds = True
|
| 724 |
-
if len(mask.shape) < 3:
|
| 725 |
-
mask = mask.unsqueeze(0)
|
| 726 |
-
return conditioning_set_values(cond, {'mask': mask,
|
| 727 |
-
'set_area_to_bounds': set_area_to_bounds,
|
| 728 |
-
'mask_strength': strength})
|
| 729 |
-
|
| 730 |
-
def combine_conditioning(conds: list):
|
| 731 |
-
combined_conds = []
|
| 732 |
-
for cond in conds:
|
| 733 |
-
combined_conds.extend(cond)
|
| 734 |
-
return combined_conds
|
| 735 |
-
|
| 736 |
-
def combine_with_new_conds(conds: list, new_conds: list):
|
| 737 |
-
combined_conds = []
|
| 738 |
-
for c, new_c in zip(conds, new_conds):
|
| 739 |
-
combined_conds.append(combine_conditioning([c, new_c]))
|
| 740 |
-
return combined_conds
|
| 741 |
-
|
| 742 |
-
def set_conds_props(conds: list, strength: float, set_cond_area: str,
|
| 743 |
-
mask: torch.Tensor=None, hooks: HookGroup=None, timesteps_range: tuple[float,float]=None, append_hooks=True):
|
| 744 |
-
final_conds = []
|
| 745 |
-
cache = {}
|
| 746 |
-
for c in conds:
|
| 747 |
-
# first, apply lora_hook to conditioning, if provided
|
| 748 |
-
c = set_hooks_for_conditioning(c, hooks, append_hooks=append_hooks, cache=cache)
|
| 749 |
-
# next, apply mask to conditioning
|
| 750 |
-
c = set_mask_for_conditioning(cond=c, mask=mask, strength=strength, set_cond_area=set_cond_area)
|
| 751 |
-
# apply timesteps, if present
|
| 752 |
-
c = set_timesteps_for_conditioning(cond=c, timestep_range=timesteps_range)
|
| 753 |
-
# finally, apply mask to conditioning and store
|
| 754 |
-
final_conds.append(c)
|
| 755 |
-
return final_conds
|
| 756 |
-
|
| 757 |
-
def set_conds_props_and_combine(conds: list, new_conds: list, strength: float=1.0, set_cond_area: str="default",
|
| 758 |
-
mask: torch.Tensor=None, hooks: HookGroup=None, timesteps_range: tuple[float,float]=None, append_hooks=True):
|
| 759 |
-
combined_conds = []
|
| 760 |
-
cache = {}
|
| 761 |
-
for c, masked_c in zip(conds, new_conds):
|
| 762 |
-
# first, apply lora_hook to new conditioning, if provided
|
| 763 |
-
masked_c = set_hooks_for_conditioning(masked_c, hooks, append_hooks=append_hooks, cache=cache)
|
| 764 |
-
# next, apply mask to new conditioning, if provided
|
| 765 |
-
masked_c = set_mask_for_conditioning(cond=masked_c, mask=mask, set_cond_area=set_cond_area, strength=strength)
|
| 766 |
-
# apply timesteps, if present
|
| 767 |
-
masked_c = set_timesteps_for_conditioning(cond=masked_c, timestep_range=timesteps_range)
|
| 768 |
-
# finally, combine with existing conditioning and store
|
| 769 |
-
combined_conds.append(combine_conditioning([c, masked_c]))
|
| 770 |
-
return combined_conds
|
| 771 |
-
|
| 772 |
-
def set_default_conds_and_combine(conds: list, new_conds: list,
|
| 773 |
-
hooks: HookGroup=None, timesteps_range: tuple[float,float]=None, append_hooks=True):
|
| 774 |
-
combined_conds = []
|
| 775 |
-
cache = {}
|
| 776 |
-
for c, new_c in zip(conds, new_conds):
|
| 777 |
-
# first, apply lora_hook to new conditioning, if provided
|
| 778 |
-
new_c = set_hooks_for_conditioning(new_c, hooks, append_hooks=append_hooks, cache=cache)
|
| 779 |
-
# next, add default_cond key to cond so that during sampling, it can be identified
|
| 780 |
-
new_c = conditioning_set_values(new_c, {'default': True})
|
| 781 |
-
# apply timesteps, if present
|
| 782 |
-
new_c = set_timesteps_for_conditioning(cond=new_c, timestep_range=timesteps_range)
|
| 783 |
-
# finally, combine with existing conditioning and store
|
| 784 |
-
combined_conds.append(combine_conditioning([c, new_c]))
|
| 785 |
-
return combined_conds
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/image_encoders/dino2.py
DELETED
|
@@ -1,141 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
from comfy.text_encoders.bert import BertAttention
|
| 3 |
-
import comfy.model_management
|
| 4 |
-
from comfy.ldm.modules.attention import optimized_attention_for_device
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
class Dino2AttentionOutput(torch.nn.Module):
|
| 8 |
-
def __init__(self, input_dim, output_dim, layer_norm_eps, dtype, device, operations):
|
| 9 |
-
super().__init__()
|
| 10 |
-
self.dense = operations.Linear(input_dim, output_dim, dtype=dtype, device=device)
|
| 11 |
-
|
| 12 |
-
def forward(self, x):
|
| 13 |
-
return self.dense(x)
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
class Dino2AttentionBlock(torch.nn.Module):
|
| 17 |
-
def __init__(self, embed_dim, heads, layer_norm_eps, dtype, device, operations):
|
| 18 |
-
super().__init__()
|
| 19 |
-
self.attention = BertAttention(embed_dim, heads, dtype, device, operations)
|
| 20 |
-
self.output = Dino2AttentionOutput(embed_dim, embed_dim, layer_norm_eps, dtype, device, operations)
|
| 21 |
-
|
| 22 |
-
def forward(self, x, mask, optimized_attention):
|
| 23 |
-
return self.output(self.attention(x, mask, optimized_attention))
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
class LayerScale(torch.nn.Module):
|
| 27 |
-
def __init__(self, dim, dtype, device, operations):
|
| 28 |
-
super().__init__()
|
| 29 |
-
self.lambda1 = torch.nn.Parameter(torch.empty(dim, device=device, dtype=dtype))
|
| 30 |
-
|
| 31 |
-
def forward(self, x):
|
| 32 |
-
return x * comfy.model_management.cast_to_device(self.lambda1, x.device, x.dtype)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
class SwiGLUFFN(torch.nn.Module):
|
| 36 |
-
def __init__(self, dim, dtype, device, operations):
|
| 37 |
-
super().__init__()
|
| 38 |
-
in_features = out_features = dim
|
| 39 |
-
hidden_features = int(dim * 4)
|
| 40 |
-
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 41 |
-
|
| 42 |
-
self.weights_in = operations.Linear(in_features, 2 * hidden_features, bias=True, device=device, dtype=dtype)
|
| 43 |
-
self.weights_out = operations.Linear(hidden_features, out_features, bias=True, device=device, dtype=dtype)
|
| 44 |
-
|
| 45 |
-
def forward(self, x):
|
| 46 |
-
x = self.weights_in(x)
|
| 47 |
-
x1, x2 = x.chunk(2, dim=-1)
|
| 48 |
-
x = torch.nn.functional.silu(x1) * x2
|
| 49 |
-
return self.weights_out(x)
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
class Dino2Block(torch.nn.Module):
|
| 53 |
-
def __init__(self, dim, num_heads, layer_norm_eps, dtype, device, operations):
|
| 54 |
-
super().__init__()
|
| 55 |
-
self.attention = Dino2AttentionBlock(dim, num_heads, layer_norm_eps, dtype, device, operations)
|
| 56 |
-
self.layer_scale1 = LayerScale(dim, dtype, device, operations)
|
| 57 |
-
self.layer_scale2 = LayerScale(dim, dtype, device, operations)
|
| 58 |
-
self.mlp = SwiGLUFFN(dim, dtype, device, operations)
|
| 59 |
-
self.norm1 = operations.LayerNorm(dim, eps=layer_norm_eps, dtype=dtype, device=device)
|
| 60 |
-
self.norm2 = operations.LayerNorm(dim, eps=layer_norm_eps, dtype=dtype, device=device)
|
| 61 |
-
|
| 62 |
-
def forward(self, x, optimized_attention):
|
| 63 |
-
x = x + self.layer_scale1(self.attention(self.norm1(x), None, optimized_attention))
|
| 64 |
-
x = x + self.layer_scale2(self.mlp(self.norm2(x)))
|
| 65 |
-
return x
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
class Dino2Encoder(torch.nn.Module):
|
| 69 |
-
def __init__(self, dim, num_heads, layer_norm_eps, num_layers, dtype, device, operations):
|
| 70 |
-
super().__init__()
|
| 71 |
-
self.layer = torch.nn.ModuleList([Dino2Block(dim, num_heads, layer_norm_eps, dtype, device, operations) for _ in range(num_layers)])
|
| 72 |
-
|
| 73 |
-
def forward(self, x, intermediate_output=None):
|
| 74 |
-
optimized_attention = optimized_attention_for_device(x.device, False, small_input=True)
|
| 75 |
-
|
| 76 |
-
if intermediate_output is not None:
|
| 77 |
-
if intermediate_output < 0:
|
| 78 |
-
intermediate_output = len(self.layer) + intermediate_output
|
| 79 |
-
|
| 80 |
-
intermediate = None
|
| 81 |
-
for i, l in enumerate(self.layer):
|
| 82 |
-
x = l(x, optimized_attention)
|
| 83 |
-
if i == intermediate_output:
|
| 84 |
-
intermediate = x.clone()
|
| 85 |
-
return x, intermediate
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
class Dino2PatchEmbeddings(torch.nn.Module):
|
| 89 |
-
def __init__(self, dim, num_channels=3, patch_size=14, image_size=518, dtype=None, device=None, operations=None):
|
| 90 |
-
super().__init__()
|
| 91 |
-
self.projection = operations.Conv2d(
|
| 92 |
-
in_channels=num_channels,
|
| 93 |
-
out_channels=dim,
|
| 94 |
-
kernel_size=patch_size,
|
| 95 |
-
stride=patch_size,
|
| 96 |
-
bias=True,
|
| 97 |
-
dtype=dtype,
|
| 98 |
-
device=device
|
| 99 |
-
)
|
| 100 |
-
|
| 101 |
-
def forward(self, pixel_values):
|
| 102 |
-
return self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
class Dino2Embeddings(torch.nn.Module):
|
| 106 |
-
def __init__(self, dim, dtype, device, operations):
|
| 107 |
-
super().__init__()
|
| 108 |
-
patch_size = 14
|
| 109 |
-
image_size = 518
|
| 110 |
-
|
| 111 |
-
self.patch_embeddings = Dino2PatchEmbeddings(dim, patch_size=patch_size, image_size=image_size, dtype=dtype, device=device, operations=operations)
|
| 112 |
-
self.position_embeddings = torch.nn.Parameter(torch.empty(1, (image_size // patch_size) ** 2 + 1, dim, dtype=dtype, device=device))
|
| 113 |
-
self.cls_token = torch.nn.Parameter(torch.empty(1, 1, dim, dtype=dtype, device=device))
|
| 114 |
-
self.mask_token = torch.nn.Parameter(torch.empty(1, dim, dtype=dtype, device=device))
|
| 115 |
-
|
| 116 |
-
def forward(self, pixel_values):
|
| 117 |
-
x = self.patch_embeddings(pixel_values)
|
| 118 |
-
# TODO: mask_token?
|
| 119 |
-
x = torch.cat((self.cls_token.to(device=x.device, dtype=x.dtype).expand(x.shape[0], -1, -1), x), dim=1)
|
| 120 |
-
x = x + comfy.model_management.cast_to_device(self.position_embeddings, x.device, x.dtype)
|
| 121 |
-
return x
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
class Dinov2Model(torch.nn.Module):
|
| 125 |
-
def __init__(self, config_dict, dtype, device, operations):
|
| 126 |
-
super().__init__()
|
| 127 |
-
num_layers = config_dict["num_hidden_layers"]
|
| 128 |
-
dim = config_dict["hidden_size"]
|
| 129 |
-
heads = config_dict["num_attention_heads"]
|
| 130 |
-
layer_norm_eps = config_dict["layer_norm_eps"]
|
| 131 |
-
|
| 132 |
-
self.embeddings = Dino2Embeddings(dim, dtype, device, operations)
|
| 133 |
-
self.encoder = Dino2Encoder(dim, heads, layer_norm_eps, num_layers, dtype, device, operations)
|
| 134 |
-
self.layernorm = operations.LayerNorm(dim, eps=layer_norm_eps, dtype=dtype, device=device)
|
| 135 |
-
|
| 136 |
-
def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
|
| 137 |
-
x = self.embeddings(pixel_values)
|
| 138 |
-
x, i = self.encoder(x, intermediate_output=intermediate_output)
|
| 139 |
-
x = self.layernorm(x)
|
| 140 |
-
pooled_output = x[:, 0, :]
|
| 141 |
-
return x, i, pooled_output, None
|
|
|
|
|
|
|
|
|
|
|
|
|
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": 518,
|
| 8 |
-
"initializer_range": 0.02,
|
| 9 |
-
"layer_norm_eps": 1e-06,
|
| 10 |
-
"layerscale_value": 1.0,
|
| 11 |
-
"mlp_ratio": 4,
|
| 12 |
-
"model_type": "dinov2",
|
| 13 |
-
"num_attention_heads": 24,
|
| 14 |
-
"num_channels": 3,
|
| 15 |
-
"num_hidden_layers": 40,
|
| 16 |
-
"patch_size": 14,
|
| 17 |
-
"qkv_bias": true,
|
| 18 |
-
"use_swiglu_ffn": true,
|
| 19 |
-
"image_mean": [0.485, 0.456, 0.406],
|
| 20 |
-
"image_std": [0.229, 0.224, 0.225]
|
| 21 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/k_diffusion/deis.py
DELETED
|
@@ -1,120 +0,0 @@
|
|
| 1 |
-
#Taken from: https://github.com/zju-pi/diff-sampler/blob/main/gits-main/solver_utils.py
|
| 2 |
-
#under Apache 2 license
|
| 3 |
-
import torch
|
| 4 |
-
import numpy as np
|
| 5 |
-
|
| 6 |
-
# A pytorch reimplementation of DEIS (https://github.com/qsh-zh/deis).
|
| 7 |
-
#############################
|
| 8 |
-
### Utils for DEIS solver ###
|
| 9 |
-
#############################
|
| 10 |
-
#----------------------------------------------------------------------------
|
| 11 |
-
# Transfer from the input time (sigma) used in EDM to that (t) used in DEIS.
|
| 12 |
-
|
| 13 |
-
def edm2t(edm_steps, epsilon_s=1e-3, sigma_min=0.002, sigma_max=80):
|
| 14 |
-
vp_sigma_inv = lambda beta_d, beta_min: lambda sigma: ((beta_min ** 2 + 2 * beta_d * (sigma ** 2 + 1).log()).sqrt() - beta_min) / beta_d
|
| 15 |
-
vp_beta_d = 2 * (np.log(torch.tensor(sigma_min).cpu() ** 2 + 1) / epsilon_s - np.log(torch.tensor(sigma_max).cpu() ** 2 + 1)) / (epsilon_s - 1)
|
| 16 |
-
vp_beta_min = np.log(torch.tensor(sigma_max).cpu() ** 2 + 1) - 0.5 * vp_beta_d
|
| 17 |
-
t_steps = vp_sigma_inv(vp_beta_d.clone().detach().cpu(), vp_beta_min.clone().detach().cpu())(edm_steps.clone().detach().cpu())
|
| 18 |
-
return t_steps, vp_beta_min, vp_beta_d + vp_beta_min
|
| 19 |
-
|
| 20 |
-
#----------------------------------------------------------------------------
|
| 21 |
-
|
| 22 |
-
def cal_poly(prev_t, j, taus):
|
| 23 |
-
poly = 1
|
| 24 |
-
for k in range(prev_t.shape[0]):
|
| 25 |
-
if k == j:
|
| 26 |
-
continue
|
| 27 |
-
poly *= (taus - prev_t[k]) / (prev_t[j] - prev_t[k])
|
| 28 |
-
return poly
|
| 29 |
-
|
| 30 |
-
#----------------------------------------------------------------------------
|
| 31 |
-
# Transfer from t to alpha_t.
|
| 32 |
-
|
| 33 |
-
def t2alpha_fn(beta_0, beta_1, t):
|
| 34 |
-
return torch.exp(-0.5 * t ** 2 * (beta_1 - beta_0) - t * beta_0)
|
| 35 |
-
|
| 36 |
-
#----------------------------------------------------------------------------
|
| 37 |
-
|
| 38 |
-
def cal_intergrand(beta_0, beta_1, taus):
|
| 39 |
-
with torch.inference_mode(mode=False):
|
| 40 |
-
taus = taus.clone()
|
| 41 |
-
beta_0 = beta_0.clone()
|
| 42 |
-
beta_1 = beta_1.clone()
|
| 43 |
-
with torch.enable_grad():
|
| 44 |
-
taus.requires_grad_(True)
|
| 45 |
-
alpha = t2alpha_fn(beta_0, beta_1, taus)
|
| 46 |
-
log_alpha = alpha.log()
|
| 47 |
-
log_alpha.sum().backward()
|
| 48 |
-
d_log_alpha_dtau = taus.grad
|
| 49 |
-
integrand = -0.5 * d_log_alpha_dtau / torch.sqrt(alpha * (1 - alpha))
|
| 50 |
-
return integrand
|
| 51 |
-
|
| 52 |
-
#----------------------------------------------------------------------------
|
| 53 |
-
|
| 54 |
-
def get_deis_coeff_list(t_steps, max_order, N=10000, deis_mode='tab'):
|
| 55 |
-
"""
|
| 56 |
-
Get the coefficient list for DEIS sampling.
|
| 57 |
-
|
| 58 |
-
Args:
|
| 59 |
-
t_steps: A pytorch tensor. The time steps for sampling.
|
| 60 |
-
max_order: A `int`. Maximum order of the solver. 1 <= max_order <= 4
|
| 61 |
-
N: A `int`. Use how many points to perform the numerical integration when deis_mode=='tab'.
|
| 62 |
-
deis_mode: A `str`. Select between 'tab' and 'rhoab'. Type of DEIS.
|
| 63 |
-
Returns:
|
| 64 |
-
A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
|
| 65 |
-
"""
|
| 66 |
-
if deis_mode == 'tab':
|
| 67 |
-
t_steps, beta_0, beta_1 = edm2t(t_steps)
|
| 68 |
-
C = []
|
| 69 |
-
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):
|
| 70 |
-
order = min(i+1, max_order)
|
| 71 |
-
if order == 1:
|
| 72 |
-
C.append([])
|
| 73 |
-
else:
|
| 74 |
-
taus = torch.linspace(t_cur, t_next, N) # split the interval for integral appximation
|
| 75 |
-
dtau = (t_next - t_cur) / N
|
| 76 |
-
prev_t = t_steps[[i - k for k in range(order)]]
|
| 77 |
-
coeff_temp = []
|
| 78 |
-
integrand = cal_intergrand(beta_0, beta_1, taus)
|
| 79 |
-
for j in range(order):
|
| 80 |
-
poly = cal_poly(prev_t, j, taus)
|
| 81 |
-
coeff_temp.append(torch.sum(integrand * poly) * dtau)
|
| 82 |
-
C.append(coeff_temp)
|
| 83 |
-
|
| 84 |
-
elif deis_mode == 'rhoab':
|
| 85 |
-
# Analytical solution, second order
|
| 86 |
-
def get_def_intergral_2(a, b, start, end, c):
|
| 87 |
-
coeff = (end**3 - start**3) / 3 - (end**2 - start**2) * (a + b) / 2 + (end - start) * a * b
|
| 88 |
-
return coeff / ((c - a) * (c - b))
|
| 89 |
-
|
| 90 |
-
# Analytical solution, third order
|
| 91 |
-
def get_def_intergral_3(a, b, c, start, end, d):
|
| 92 |
-
coeff = (end**4 - start**4) / 4 - (end**3 - start**3) * (a + b + c) / 3 \
|
| 93 |
-
+ (end**2 - start**2) * (a*b + a*c + b*c) / 2 - (end - start) * a * b * c
|
| 94 |
-
return coeff / ((d - a) * (d - b) * (d - c))
|
| 95 |
-
|
| 96 |
-
C = []
|
| 97 |
-
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):
|
| 98 |
-
order = min(i, max_order)
|
| 99 |
-
if order == 0:
|
| 100 |
-
C.append([])
|
| 101 |
-
else:
|
| 102 |
-
prev_t = t_steps[[i - k for k in range(order+1)]]
|
| 103 |
-
if order == 1:
|
| 104 |
-
coeff_cur = ((t_next - prev_t[1])**2 - (t_cur - prev_t[1])**2) / (2 * (t_cur - prev_t[1]))
|
| 105 |
-
coeff_prev1 = (t_next - t_cur)**2 / (2 * (prev_t[1] - t_cur))
|
| 106 |
-
coeff_temp = [coeff_cur, coeff_prev1]
|
| 107 |
-
elif order == 2:
|
| 108 |
-
coeff_cur = get_def_intergral_2(prev_t[1], prev_t[2], t_cur, t_next, t_cur)
|
| 109 |
-
coeff_prev1 = get_def_intergral_2(t_cur, prev_t[2], t_cur, t_next, prev_t[1])
|
| 110 |
-
coeff_prev2 = get_def_intergral_2(t_cur, prev_t[1], t_cur, t_next, prev_t[2])
|
| 111 |
-
coeff_temp = [coeff_cur, coeff_prev1, coeff_prev2]
|
| 112 |
-
elif order == 3:
|
| 113 |
-
coeff_cur = get_def_intergral_3(prev_t[1], prev_t[2], prev_t[3], t_cur, t_next, t_cur)
|
| 114 |
-
coeff_prev1 = get_def_intergral_3(t_cur, prev_t[2], prev_t[3], t_cur, t_next, prev_t[1])
|
| 115 |
-
coeff_prev2 = get_def_intergral_3(t_cur, prev_t[1], prev_t[3], t_cur, t_next, prev_t[2])
|
| 116 |
-
coeff_prev3 = get_def_intergral_3(t_cur, prev_t[1], prev_t[2], t_cur, t_next, prev_t[3])
|
| 117 |
-
coeff_temp = [coeff_cur, coeff_prev1, coeff_prev2, coeff_prev3]
|
| 118 |
-
C.append(coeff_temp)
|
| 119 |
-
return C
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/k_diffusion/sa_solver.py
DELETED
|
@@ -1,121 +0,0 @@
|
|
| 1 |
-
# SA-Solver: Stochastic Adams Solver (NeurIPS 2023, arXiv:2309.05019)
|
| 2 |
-
# Conference: https://proceedings.neurips.cc/paper_files/paper/2023/file/f4a6806490d31216a3ba667eb240c897-Paper-Conference.pdf
|
| 3 |
-
# Codebase ref: https://github.com/scxue/SA-Solver
|
| 4 |
-
|
| 5 |
-
import math
|
| 6 |
-
from typing import Union, Callable
|
| 7 |
-
import torch
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
def compute_exponential_coeffs(s: torch.Tensor, t: torch.Tensor, solver_order: int, tau_t: float) -> torch.Tensor:
|
| 11 |
-
"""Compute (1 + tau^2) * integral of exp((1 + tau^2) * x) * x^p dx from s to t with exp((1 + tau^2) * t) factored out, using integration by parts.
|
| 12 |
-
|
| 13 |
-
Integral of exp((1 + tau^2) * x) * x^p dx
|
| 14 |
-
= product_terms[p] - (p / (1 + tau^2)) * integral of exp((1 + tau^2) * x) * x^(p-1) dx,
|
| 15 |
-
with base case p=0 where integral equals product_terms[0].
|
| 16 |
-
|
| 17 |
-
where
|
| 18 |
-
product_terms[p] = x^p * exp((1 + tau^2) * x) / (1 + tau^2).
|
| 19 |
-
|
| 20 |
-
Construct a recursive coefficient matrix following the above recursive relation to compute all integral terms up to p = (solver_order - 1).
|
| 21 |
-
Return coefficients used by the SA-Solver in data prediction mode.
|
| 22 |
-
|
| 23 |
-
Args:
|
| 24 |
-
s: Start time s.
|
| 25 |
-
t: End time t.
|
| 26 |
-
solver_order: Current order of the solver.
|
| 27 |
-
tau_t: Stochastic strength parameter in the SDE.
|
| 28 |
-
|
| 29 |
-
Returns:
|
| 30 |
-
Exponential coefficients used in data prediction, with exp((1 + tau^2) * t) factored out, ordered from p=0 to p=solver_order−1, shape (solver_order,).
|
| 31 |
-
"""
|
| 32 |
-
tau_mul = 1 + tau_t ** 2
|
| 33 |
-
h = t - s
|
| 34 |
-
p = torch.arange(solver_order, dtype=s.dtype, device=s.device)
|
| 35 |
-
|
| 36 |
-
# product_terms after factoring out exp((1 + tau^2) * t)
|
| 37 |
-
# Includes (1 + tau^2) factor from outside the integral
|
| 38 |
-
product_terms_factored = (t ** p - s ** p * (-tau_mul * h).exp())
|
| 39 |
-
|
| 40 |
-
# Lower triangular recursive coefficient matrix
|
| 41 |
-
# Accumulates recursive coefficients based on p / (1 + tau^2)
|
| 42 |
-
recursive_depth_mat = p.unsqueeze(1) - p.unsqueeze(0)
|
| 43 |
-
log_factorial = (p + 1).lgamma()
|
| 44 |
-
recursive_coeff_mat = log_factorial.unsqueeze(1) - log_factorial.unsqueeze(0)
|
| 45 |
-
if tau_t > 0:
|
| 46 |
-
recursive_coeff_mat = recursive_coeff_mat - (recursive_depth_mat * math.log(tau_mul))
|
| 47 |
-
signs = torch.where(recursive_depth_mat % 2 == 0, 1.0, -1.0)
|
| 48 |
-
recursive_coeff_mat = (recursive_coeff_mat.exp() * signs).tril()
|
| 49 |
-
|
| 50 |
-
return recursive_coeff_mat @ product_terms_factored
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def compute_simple_stochastic_adams_b_coeffs(sigma_next: torch.Tensor, curr_lambdas: torch.Tensor, lambda_s: torch.Tensor, lambda_t: torch.Tensor, tau_t: float, is_corrector_step: bool = False) -> torch.Tensor:
|
| 54 |
-
"""Compute simple order-2 b coefficients from SA-Solver paper (Appendix D. Implementation Details)."""
|
| 55 |
-
tau_mul = 1 + tau_t ** 2
|
| 56 |
-
h = lambda_t - lambda_s
|
| 57 |
-
alpha_t = sigma_next * lambda_t.exp()
|
| 58 |
-
if is_corrector_step:
|
| 59 |
-
# Simplified 1-step (order-2) corrector
|
| 60 |
-
b_1 = alpha_t * (0.5 * tau_mul * h)
|
| 61 |
-
b_2 = alpha_t * (-h * tau_mul).expm1().neg() - b_1
|
| 62 |
-
else:
|
| 63 |
-
# Simplified 2-step predictor
|
| 64 |
-
b_2 = alpha_t * (0.5 * tau_mul * h ** 2) / (curr_lambdas[-2] - lambda_s)
|
| 65 |
-
b_1 = alpha_t * (-h * tau_mul).expm1().neg() - b_2
|
| 66 |
-
return torch.stack([b_2, b_1])
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def compute_stochastic_adams_b_coeffs(sigma_next: torch.Tensor, curr_lambdas: torch.Tensor, lambda_s: torch.Tensor, lambda_t: torch.Tensor, tau_t: float, simple_order_2: bool = False, is_corrector_step: bool = False) -> torch.Tensor:
|
| 70 |
-
"""Compute b_i coefficients for the SA-Solver (see eqs. 15 and 18).
|
| 71 |
-
|
| 72 |
-
The solver order corresponds to the number of input lambdas (half-logSNR points).
|
| 73 |
-
|
| 74 |
-
Args:
|
| 75 |
-
sigma_next: Sigma at end time t.
|
| 76 |
-
curr_lambdas: Lambda time points used to construct the Lagrange basis, shape (N,).
|
| 77 |
-
lambda_s: Lambda at start time s.
|
| 78 |
-
lambda_t: Lambda at end time t.
|
| 79 |
-
tau_t: Stochastic strength parameter in the SDE.
|
| 80 |
-
simple_order_2: Whether to enable the simple order-2 scheme.
|
| 81 |
-
is_corrector_step: Flag for corrector step in simple order-2 mode.
|
| 82 |
-
|
| 83 |
-
Returns:
|
| 84 |
-
b_i coefficients for the SA-Solver, shape (N,), where N is the solver order.
|
| 85 |
-
"""
|
| 86 |
-
num_timesteps = curr_lambdas.shape[0]
|
| 87 |
-
|
| 88 |
-
if simple_order_2 and num_timesteps == 2:
|
| 89 |
-
return compute_simple_stochastic_adams_b_coeffs(sigma_next, curr_lambdas, lambda_s, lambda_t, tau_t, is_corrector_step)
|
| 90 |
-
|
| 91 |
-
# Compute coefficients by solving a linear system from Lagrange basis interpolation
|
| 92 |
-
exp_integral_coeffs = compute_exponential_coeffs(lambda_s, lambda_t, num_timesteps, tau_t)
|
| 93 |
-
vandermonde_matrix_T = torch.vander(curr_lambdas, num_timesteps, increasing=True).T
|
| 94 |
-
lagrange_integrals = torch.linalg.solve(vandermonde_matrix_T, exp_integral_coeffs)
|
| 95 |
-
|
| 96 |
-
# (sigma_t * exp(-tau^2 * lambda_t)) * exp((1 + tau^2) * lambda_t)
|
| 97 |
-
# = sigma_t * exp(lambda_t) = alpha_t
|
| 98 |
-
# exp((1 + tau^2) * lambda_t) is extracted from the integral
|
| 99 |
-
alpha_t = sigma_next * lambda_t.exp()
|
| 100 |
-
return alpha_t * lagrange_integrals
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
def get_tau_interval_func(start_sigma: float, end_sigma: float, eta: float = 1.0) -> Callable[[Union[torch.Tensor, float]], float]:
|
| 104 |
-
"""Return a function that controls the stochasticity of SA-Solver.
|
| 105 |
-
|
| 106 |
-
When eta = 0, SA-Solver runs as ODE. The official approach uses
|
| 107 |
-
time t to determine the SDE interval, while here we use sigma instead.
|
| 108 |
-
|
| 109 |
-
See:
|
| 110 |
-
https://github.com/scxue/SA-Solver/blob/main/README.md
|
| 111 |
-
"""
|
| 112 |
-
|
| 113 |
-
def tau_func(sigma: Union[torch.Tensor, float]) -> float:
|
| 114 |
-
if eta <= 0:
|
| 115 |
-
return 0.0 # ODE
|
| 116 |
-
|
| 117 |
-
if isinstance(sigma, torch.Tensor):
|
| 118 |
-
sigma = sigma.item()
|
| 119 |
-
return eta if start_sigma >= sigma >= end_sigma else 0.0
|
| 120 |
-
|
| 121 |
-
return tau_func
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/k_diffusion/sampling.py
DELETED
|
@@ -1,1761 +0,0 @@
|
|
| 1 |
-
import math
|
| 2 |
-
from functools import partial
|
| 3 |
-
|
| 4 |
-
from scipy import integrate
|
| 5 |
-
import torch
|
| 6 |
-
from torch import nn
|
| 7 |
-
import torchsde
|
| 8 |
-
from tqdm.auto import trange, tqdm
|
| 9 |
-
|
| 10 |
-
from . import utils
|
| 11 |
-
from . import deis
|
| 12 |
-
from . import sa_solver
|
| 13 |
-
import comfy.model_patcher
|
| 14 |
-
import comfy.model_sampling
|
| 15 |
-
|
| 16 |
-
def append_zero(x):
|
| 17 |
-
return torch.cat([x, x.new_zeros([1])])
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def get_sigmas_karras(n, sigma_min, sigma_max, rho=7., device='cpu'):
|
| 21 |
-
"""Constructs the noise schedule of Karras et al. (2022)."""
|
| 22 |
-
ramp = torch.linspace(0, 1, n, device=device)
|
| 23 |
-
min_inv_rho = sigma_min ** (1 / rho)
|
| 24 |
-
max_inv_rho = sigma_max ** (1 / rho)
|
| 25 |
-
sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
|
| 26 |
-
return append_zero(sigmas).to(device)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def get_sigmas_exponential(n, sigma_min, sigma_max, device='cpu'):
|
| 30 |
-
"""Constructs an exponential noise schedule."""
|
| 31 |
-
sigmas = torch.linspace(math.log(sigma_max), math.log(sigma_min), n, device=device).exp()
|
| 32 |
-
return append_zero(sigmas)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def get_sigmas_polyexponential(n, sigma_min, sigma_max, rho=1., device='cpu'):
|
| 36 |
-
"""Constructs an polynomial in log sigma noise schedule."""
|
| 37 |
-
ramp = torch.linspace(1, 0, n, device=device) ** rho
|
| 38 |
-
sigmas = torch.exp(ramp * (math.log(sigma_max) - math.log(sigma_min)) + math.log(sigma_min))
|
| 39 |
-
return append_zero(sigmas)
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def get_sigmas_vp(n, beta_d=19.9, beta_min=0.1, eps_s=1e-3, device='cpu'):
|
| 43 |
-
"""Constructs a continuous VP noise schedule."""
|
| 44 |
-
t = torch.linspace(1, eps_s, n, device=device)
|
| 45 |
-
sigmas = torch.sqrt(torch.special.expm1(beta_d * t ** 2 / 2 + beta_min * t))
|
| 46 |
-
return append_zero(sigmas)
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def get_sigmas_laplace(n, sigma_min, sigma_max, mu=0., beta=0.5, device='cpu'):
|
| 50 |
-
"""Constructs the noise schedule proposed by Tiankai et al. (2024). """
|
| 51 |
-
epsilon = 1e-5 # avoid log(0)
|
| 52 |
-
x = torch.linspace(0, 1, n, device=device)
|
| 53 |
-
clamp = lambda x: torch.clamp(x, min=sigma_min, max=sigma_max)
|
| 54 |
-
lmb = mu - beta * torch.sign(0.5-x) * torch.log(1 - 2 * torch.abs(0.5-x) + epsilon)
|
| 55 |
-
sigmas = clamp(torch.exp(lmb))
|
| 56 |
-
return sigmas
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def to_d(x, sigma, denoised):
|
| 61 |
-
"""Converts a denoiser output to a Karras ODE derivative."""
|
| 62 |
-
return (x - denoised) / utils.append_dims(sigma, x.ndim)
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def get_ancestral_step(sigma_from, sigma_to, eta=1.):
|
| 66 |
-
"""Calculates the noise level (sigma_down) to step down to and the amount
|
| 67 |
-
of noise to add (sigma_up) when doing an ancestral sampling step."""
|
| 68 |
-
if not eta:
|
| 69 |
-
return sigma_to, 0.
|
| 70 |
-
sigma_up = min(sigma_to, eta * (sigma_to ** 2 * (sigma_from ** 2 - sigma_to ** 2) / sigma_from ** 2) ** 0.5)
|
| 71 |
-
sigma_down = (sigma_to ** 2 - sigma_up ** 2) ** 0.5
|
| 72 |
-
return sigma_down, sigma_up
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def default_noise_sampler(x, seed=None):
|
| 76 |
-
if seed is not None:
|
| 77 |
-
generator = torch.Generator(device=x.device)
|
| 78 |
-
generator.manual_seed(seed)
|
| 79 |
-
else:
|
| 80 |
-
generator = None
|
| 81 |
-
|
| 82 |
-
return lambda sigma, sigma_next: torch.randn(x.size(), dtype=x.dtype, layout=x.layout, device=x.device, generator=generator)
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
class BatchedBrownianTree:
|
| 86 |
-
"""A wrapper around torchsde.BrownianTree that enables batches of entropy."""
|
| 87 |
-
|
| 88 |
-
def __init__(self, x, t0, t1, seed=None, **kwargs):
|
| 89 |
-
self.cpu_tree = True
|
| 90 |
-
if "cpu" in kwargs:
|
| 91 |
-
self.cpu_tree = kwargs.pop("cpu")
|
| 92 |
-
t0, t1, self.sign = self.sort(t0, t1)
|
| 93 |
-
w0 = kwargs.get('w0', torch.zeros_like(x))
|
| 94 |
-
if seed is None:
|
| 95 |
-
seed = torch.randint(0, 2 ** 63 - 1, []).item()
|
| 96 |
-
self.batched = True
|
| 97 |
-
try:
|
| 98 |
-
assert len(seed) == x.shape[0]
|
| 99 |
-
w0 = w0[0]
|
| 100 |
-
except TypeError:
|
| 101 |
-
seed = [seed]
|
| 102 |
-
self.batched = False
|
| 103 |
-
if self.cpu_tree:
|
| 104 |
-
self.trees = [torchsde.BrownianTree(t0.cpu(), w0.cpu(), t1.cpu(), entropy=s, **kwargs) for s in seed]
|
| 105 |
-
else:
|
| 106 |
-
self.trees = [torchsde.BrownianTree(t0, w0, t1, entropy=s, **kwargs) for s in seed]
|
| 107 |
-
|
| 108 |
-
@staticmethod
|
| 109 |
-
def sort(a, b):
|
| 110 |
-
return (a, b, 1) if a < b else (b, a, -1)
|
| 111 |
-
|
| 112 |
-
def __call__(self, t0, t1):
|
| 113 |
-
t0, t1, sign = self.sort(t0, t1)
|
| 114 |
-
if self.cpu_tree:
|
| 115 |
-
w = torch.stack([tree(t0.cpu().float(), t1.cpu().float()).to(t0.dtype).to(t0.device) for tree in self.trees]) * (self.sign * sign)
|
| 116 |
-
else:
|
| 117 |
-
w = torch.stack([tree(t0, t1) for tree in self.trees]) * (self.sign * sign)
|
| 118 |
-
|
| 119 |
-
return w if self.batched else w[0]
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
class BrownianTreeNoiseSampler:
|
| 123 |
-
"""A noise sampler backed by a torchsde.BrownianTree.
|
| 124 |
-
|
| 125 |
-
Args:
|
| 126 |
-
x (Tensor): The tensor whose shape, device and dtype to use to generate
|
| 127 |
-
random samples.
|
| 128 |
-
sigma_min (float): The low end of the valid interval.
|
| 129 |
-
sigma_max (float): The high end of the valid interval.
|
| 130 |
-
seed (int or List[int]): The random seed. If a list of seeds is
|
| 131 |
-
supplied instead of a single integer, then the noise sampler will
|
| 132 |
-
use one BrownianTree per batch item, each with its own seed.
|
| 133 |
-
transform (callable): A function that maps sigma to the sampler's
|
| 134 |
-
internal timestep.
|
| 135 |
-
"""
|
| 136 |
-
|
| 137 |
-
def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x, cpu=False):
|
| 138 |
-
self.transform = transform
|
| 139 |
-
t0, t1 = self.transform(torch.as_tensor(sigma_min)), self.transform(torch.as_tensor(sigma_max))
|
| 140 |
-
self.tree = BatchedBrownianTree(x, t0, t1, seed, cpu=cpu)
|
| 141 |
-
|
| 142 |
-
def __call__(self, sigma, sigma_next):
|
| 143 |
-
t0, t1 = self.transform(torch.as_tensor(sigma)), self.transform(torch.as_tensor(sigma_next))
|
| 144 |
-
return self.tree(t0, t1) / (t1 - t0).abs().sqrt()
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
def sigma_to_half_log_snr(sigma, model_sampling):
|
| 148 |
-
"""Convert sigma to half-logSNR log(alpha_t / sigma_t)."""
|
| 149 |
-
if isinstance(model_sampling, comfy.model_sampling.CONST):
|
| 150 |
-
# log((1 - t) / t) = log((1 - sigma) / sigma)
|
| 151 |
-
return sigma.logit().neg()
|
| 152 |
-
return sigma.log().neg()
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
def half_log_snr_to_sigma(half_log_snr, model_sampling):
|
| 156 |
-
"""Convert half-logSNR log(alpha_t / sigma_t) to sigma."""
|
| 157 |
-
if isinstance(model_sampling, comfy.model_sampling.CONST):
|
| 158 |
-
# 1 / (1 + exp(half_log_snr))
|
| 159 |
-
return half_log_snr.neg().sigmoid()
|
| 160 |
-
return half_log_snr.neg().exp()
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
def offset_first_sigma_for_snr(sigmas, model_sampling, percent_offset=1e-4):
|
| 164 |
-
"""Adjust the first sigma to avoid invalid logSNR."""
|
| 165 |
-
if len(sigmas) <= 1:
|
| 166 |
-
return sigmas
|
| 167 |
-
if isinstance(model_sampling, comfy.model_sampling.CONST):
|
| 168 |
-
if sigmas[0] >= 1:
|
| 169 |
-
sigmas = sigmas.clone()
|
| 170 |
-
sigmas[0] = model_sampling.percent_to_sigma(percent_offset)
|
| 171 |
-
return sigmas
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
@torch.no_grad()
|
| 175 |
-
def sample_euler(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
|
| 176 |
-
"""Implements Algorithm 2 (Euler steps) from Karras et al. (2022)."""
|
| 177 |
-
extra_args = {} if extra_args is None else extra_args
|
| 178 |
-
s_in = x.new_ones([x.shape[0]])
|
| 179 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 180 |
-
if s_churn > 0:
|
| 181 |
-
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
| 182 |
-
sigma_hat = sigmas[i] * (gamma + 1)
|
| 183 |
-
else:
|
| 184 |
-
gamma = 0
|
| 185 |
-
sigma_hat = sigmas[i]
|
| 186 |
-
|
| 187 |
-
if gamma > 0:
|
| 188 |
-
eps = torch.randn_like(x) * s_noise
|
| 189 |
-
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
| 190 |
-
denoised = model(x, sigma_hat * s_in, **extra_args)
|
| 191 |
-
d = to_d(x, sigma_hat, denoised)
|
| 192 |
-
if callback is not None:
|
| 193 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
| 194 |
-
dt = sigmas[i + 1] - sigma_hat
|
| 195 |
-
# Euler method
|
| 196 |
-
x = x + d * dt
|
| 197 |
-
return x
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
@torch.no_grad()
|
| 201 |
-
def sample_euler_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 202 |
-
if isinstance(model.inner_model.inner_model.model_sampling, comfy.model_sampling.CONST):
|
| 203 |
-
return sample_euler_ancestral_RF(model, x, sigmas, extra_args, callback, disable, eta, s_noise, noise_sampler)
|
| 204 |
-
"""Ancestral sampling with Euler method steps."""
|
| 205 |
-
extra_args = {} if extra_args is None else extra_args
|
| 206 |
-
seed = extra_args.get("seed", None)
|
| 207 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 208 |
-
s_in = x.new_ones([x.shape[0]])
|
| 209 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 210 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 211 |
-
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
| 212 |
-
if callback is not None:
|
| 213 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 214 |
-
|
| 215 |
-
if sigma_down == 0:
|
| 216 |
-
x = denoised
|
| 217 |
-
else:
|
| 218 |
-
d = to_d(x, sigmas[i], denoised)
|
| 219 |
-
# Euler method
|
| 220 |
-
dt = sigma_down - sigmas[i]
|
| 221 |
-
x = x + d * dt + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
| 222 |
-
return x
|
| 223 |
-
|
| 224 |
-
@torch.no_grad()
|
| 225 |
-
def sample_euler_ancestral_RF(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1., noise_sampler=None):
|
| 226 |
-
"""Ancestral sampling with Euler method steps."""
|
| 227 |
-
extra_args = {} if extra_args is None else extra_args
|
| 228 |
-
seed = extra_args.get("seed", None)
|
| 229 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 230 |
-
s_in = x.new_ones([x.shape[0]])
|
| 231 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 232 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 233 |
-
# sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
| 234 |
-
if callback is not None:
|
| 235 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 236 |
-
|
| 237 |
-
if sigmas[i + 1] == 0:
|
| 238 |
-
x = denoised
|
| 239 |
-
else:
|
| 240 |
-
downstep_ratio = 1 + (sigmas[i + 1] / sigmas[i] - 1) * eta
|
| 241 |
-
sigma_down = sigmas[i + 1] * downstep_ratio
|
| 242 |
-
alpha_ip1 = 1 - sigmas[i + 1]
|
| 243 |
-
alpha_down = 1 - sigma_down
|
| 244 |
-
renoise_coeff = (sigmas[i + 1]**2 - sigma_down**2 * alpha_ip1**2 / alpha_down**2)**0.5
|
| 245 |
-
# Euler method
|
| 246 |
-
sigma_down_i_ratio = sigma_down / sigmas[i]
|
| 247 |
-
x = sigma_down_i_ratio * x + (1 - sigma_down_i_ratio) * denoised
|
| 248 |
-
if eta > 0:
|
| 249 |
-
x = (alpha_ip1 / alpha_down) * x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * renoise_coeff
|
| 250 |
-
return x
|
| 251 |
-
|
| 252 |
-
@torch.no_grad()
|
| 253 |
-
def sample_heun(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
|
| 254 |
-
"""Implements Algorithm 2 (Heun steps) from Karras et al. (2022)."""
|
| 255 |
-
extra_args = {} if extra_args is None else extra_args
|
| 256 |
-
s_in = x.new_ones([x.shape[0]])
|
| 257 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 258 |
-
if s_churn > 0:
|
| 259 |
-
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
| 260 |
-
sigma_hat = sigmas[i] * (gamma + 1)
|
| 261 |
-
else:
|
| 262 |
-
gamma = 0
|
| 263 |
-
sigma_hat = sigmas[i]
|
| 264 |
-
|
| 265 |
-
sigma_hat = sigmas[i] * (gamma + 1)
|
| 266 |
-
if gamma > 0:
|
| 267 |
-
eps = torch.randn_like(x) * s_noise
|
| 268 |
-
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
| 269 |
-
denoised = model(x, sigma_hat * s_in, **extra_args)
|
| 270 |
-
d = to_d(x, sigma_hat, denoised)
|
| 271 |
-
if callback is not None:
|
| 272 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
| 273 |
-
dt = sigmas[i + 1] - sigma_hat
|
| 274 |
-
if sigmas[i + 1] == 0:
|
| 275 |
-
# Euler method
|
| 276 |
-
x = x + d * dt
|
| 277 |
-
else:
|
| 278 |
-
# Heun's method
|
| 279 |
-
x_2 = x + d * dt
|
| 280 |
-
denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
|
| 281 |
-
d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
|
| 282 |
-
d_prime = (d + d_2) / 2
|
| 283 |
-
x = x + d_prime * dt
|
| 284 |
-
return x
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
@torch.no_grad()
|
| 288 |
-
def sample_dpm_2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
|
| 289 |
-
"""A sampler inspired by DPM-Solver-2 and Algorithm 2 from Karras et al. (2022)."""
|
| 290 |
-
extra_args = {} if extra_args is None else extra_args
|
| 291 |
-
s_in = x.new_ones([x.shape[0]])
|
| 292 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 293 |
-
if s_churn > 0:
|
| 294 |
-
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
| 295 |
-
sigma_hat = sigmas[i] * (gamma + 1)
|
| 296 |
-
else:
|
| 297 |
-
gamma = 0
|
| 298 |
-
sigma_hat = sigmas[i]
|
| 299 |
-
|
| 300 |
-
if gamma > 0:
|
| 301 |
-
eps = torch.randn_like(x) * s_noise
|
| 302 |
-
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
| 303 |
-
denoised = model(x, sigma_hat * s_in, **extra_args)
|
| 304 |
-
d = to_d(x, sigma_hat, denoised)
|
| 305 |
-
if callback is not None:
|
| 306 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
| 307 |
-
if sigmas[i + 1] == 0:
|
| 308 |
-
# Euler method
|
| 309 |
-
dt = sigmas[i + 1] - sigma_hat
|
| 310 |
-
x = x + d * dt
|
| 311 |
-
else:
|
| 312 |
-
# DPM-Solver-2
|
| 313 |
-
sigma_mid = sigma_hat.log().lerp(sigmas[i + 1].log(), 0.5).exp()
|
| 314 |
-
dt_1 = sigma_mid - sigma_hat
|
| 315 |
-
dt_2 = sigmas[i + 1] - sigma_hat
|
| 316 |
-
x_2 = x + d * dt_1
|
| 317 |
-
denoised_2 = model(x_2, sigma_mid * s_in, **extra_args)
|
| 318 |
-
d_2 = to_d(x_2, sigma_mid, denoised_2)
|
| 319 |
-
x = x + d_2 * dt_2
|
| 320 |
-
return x
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
@torch.no_grad()
|
| 324 |
-
def sample_dpm_2_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 325 |
-
if isinstance(model.inner_model.inner_model.model_sampling, comfy.model_sampling.CONST):
|
| 326 |
-
return sample_dpm_2_ancestral_RF(model, x, sigmas, extra_args, callback, disable, eta, s_noise, noise_sampler)
|
| 327 |
-
|
| 328 |
-
"""Ancestral sampling with DPM-Solver second-order steps."""
|
| 329 |
-
extra_args = {} if extra_args is None else extra_args
|
| 330 |
-
seed = extra_args.get("seed", None)
|
| 331 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 332 |
-
s_in = x.new_ones([x.shape[0]])
|
| 333 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 334 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 335 |
-
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
| 336 |
-
if callback is not None:
|
| 337 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 338 |
-
d = to_d(x, sigmas[i], denoised)
|
| 339 |
-
if sigma_down == 0:
|
| 340 |
-
# Euler method
|
| 341 |
-
dt = sigma_down - sigmas[i]
|
| 342 |
-
x = x + d * dt
|
| 343 |
-
else:
|
| 344 |
-
# DPM-Solver-2
|
| 345 |
-
sigma_mid = sigmas[i].log().lerp(sigma_down.log(), 0.5).exp()
|
| 346 |
-
dt_1 = sigma_mid - sigmas[i]
|
| 347 |
-
dt_2 = sigma_down - sigmas[i]
|
| 348 |
-
x_2 = x + d * dt_1
|
| 349 |
-
denoised_2 = model(x_2, sigma_mid * s_in, **extra_args)
|
| 350 |
-
d_2 = to_d(x_2, sigma_mid, denoised_2)
|
| 351 |
-
x = x + d_2 * dt_2
|
| 352 |
-
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
| 353 |
-
return x
|
| 354 |
-
|
| 355 |
-
@torch.no_grad()
|
| 356 |
-
def sample_dpm_2_ancestral_RF(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 357 |
-
"""Ancestral sampling with DPM-Solver second-order steps."""
|
| 358 |
-
extra_args = {} if extra_args is None else extra_args
|
| 359 |
-
seed = extra_args.get("seed", None)
|
| 360 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 361 |
-
s_in = x.new_ones([x.shape[0]])
|
| 362 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 363 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 364 |
-
downstep_ratio = 1 + (sigmas[i+1]/sigmas[i] - 1) * eta
|
| 365 |
-
sigma_down = sigmas[i+1] * downstep_ratio
|
| 366 |
-
alpha_ip1 = 1 - sigmas[i+1]
|
| 367 |
-
alpha_down = 1 - sigma_down
|
| 368 |
-
renoise_coeff = (sigmas[i+1]**2 - sigma_down**2*alpha_ip1**2/alpha_down**2)**0.5
|
| 369 |
-
|
| 370 |
-
if callback is not None:
|
| 371 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 372 |
-
d = to_d(x, sigmas[i], denoised)
|
| 373 |
-
if sigma_down == 0:
|
| 374 |
-
# Euler method
|
| 375 |
-
dt = sigma_down - sigmas[i]
|
| 376 |
-
x = x + d * dt
|
| 377 |
-
else:
|
| 378 |
-
# DPM-Solver-2
|
| 379 |
-
sigma_mid = sigmas[i].log().lerp(sigma_down.log(), 0.5).exp()
|
| 380 |
-
dt_1 = sigma_mid - sigmas[i]
|
| 381 |
-
dt_2 = sigma_down - sigmas[i]
|
| 382 |
-
x_2 = x + d * dt_1
|
| 383 |
-
denoised_2 = model(x_2, sigma_mid * s_in, **extra_args)
|
| 384 |
-
d_2 = to_d(x_2, sigma_mid, denoised_2)
|
| 385 |
-
x = x + d_2 * dt_2
|
| 386 |
-
x = (alpha_ip1/alpha_down) * x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * renoise_coeff
|
| 387 |
-
return x
|
| 388 |
-
|
| 389 |
-
def linear_multistep_coeff(order, t, i, j):
|
| 390 |
-
if order - 1 > i:
|
| 391 |
-
raise ValueError(f'Order {order} too high for step {i}')
|
| 392 |
-
def fn(tau):
|
| 393 |
-
prod = 1.
|
| 394 |
-
for k in range(order):
|
| 395 |
-
if j == k:
|
| 396 |
-
continue
|
| 397 |
-
prod *= (tau - t[i - k]) / (t[i - j] - t[i - k])
|
| 398 |
-
return prod
|
| 399 |
-
return integrate.quad(fn, t[i], t[i + 1], epsrel=1e-4)[0]
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
@torch.no_grad()
|
| 403 |
-
def sample_lms(model, x, sigmas, extra_args=None, callback=None, disable=None, order=4):
|
| 404 |
-
extra_args = {} if extra_args is None else extra_args
|
| 405 |
-
s_in = x.new_ones([x.shape[0]])
|
| 406 |
-
sigmas_cpu = sigmas.detach().cpu().numpy()
|
| 407 |
-
ds = []
|
| 408 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 409 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 410 |
-
d = to_d(x, sigmas[i], denoised)
|
| 411 |
-
ds.append(d)
|
| 412 |
-
if len(ds) > order:
|
| 413 |
-
ds.pop(0)
|
| 414 |
-
if callback is not None:
|
| 415 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 416 |
-
if sigmas[i + 1] == 0:
|
| 417 |
-
# Denoising step
|
| 418 |
-
x = denoised
|
| 419 |
-
else:
|
| 420 |
-
cur_order = min(i + 1, order)
|
| 421 |
-
coeffs = [linear_multistep_coeff(cur_order, sigmas_cpu, i, j) for j in range(cur_order)]
|
| 422 |
-
x = x + sum(coeff * d for coeff, d in zip(coeffs, reversed(ds)))
|
| 423 |
-
return x
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
class PIDStepSizeController:
|
| 427 |
-
"""A PID controller for ODE adaptive step size control."""
|
| 428 |
-
def __init__(self, h, pcoeff, icoeff, dcoeff, order=1, accept_safety=0.81, eps=1e-8):
|
| 429 |
-
self.h = h
|
| 430 |
-
self.b1 = (pcoeff + icoeff + dcoeff) / order
|
| 431 |
-
self.b2 = -(pcoeff + 2 * dcoeff) / order
|
| 432 |
-
self.b3 = dcoeff / order
|
| 433 |
-
self.accept_safety = accept_safety
|
| 434 |
-
self.eps = eps
|
| 435 |
-
self.errs = []
|
| 436 |
-
|
| 437 |
-
def limiter(self, x):
|
| 438 |
-
return 1 + math.atan(x - 1)
|
| 439 |
-
|
| 440 |
-
def propose_step(self, error):
|
| 441 |
-
inv_error = 1 / (float(error) + self.eps)
|
| 442 |
-
if not self.errs:
|
| 443 |
-
self.errs = [inv_error, inv_error, inv_error]
|
| 444 |
-
self.errs[0] = inv_error
|
| 445 |
-
factor = self.errs[0] ** self.b1 * self.errs[1] ** self.b2 * self.errs[2] ** self.b3
|
| 446 |
-
factor = self.limiter(factor)
|
| 447 |
-
accept = factor >= self.accept_safety
|
| 448 |
-
if accept:
|
| 449 |
-
self.errs[2] = self.errs[1]
|
| 450 |
-
self.errs[1] = self.errs[0]
|
| 451 |
-
self.h *= factor
|
| 452 |
-
return accept
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
class DPMSolver(nn.Module):
|
| 456 |
-
"""DPM-Solver. See https://arxiv.org/abs/2206.00927."""
|
| 457 |
-
|
| 458 |
-
def __init__(self, model, extra_args=None, eps_callback=None, info_callback=None):
|
| 459 |
-
super().__init__()
|
| 460 |
-
self.model = model
|
| 461 |
-
self.extra_args = {} if extra_args is None else extra_args
|
| 462 |
-
self.eps_callback = eps_callback
|
| 463 |
-
self.info_callback = info_callback
|
| 464 |
-
|
| 465 |
-
def t(self, sigma):
|
| 466 |
-
return -sigma.log()
|
| 467 |
-
|
| 468 |
-
def sigma(self, t):
|
| 469 |
-
return t.neg().exp()
|
| 470 |
-
|
| 471 |
-
def eps(self, eps_cache, key, x, t, *args, **kwargs):
|
| 472 |
-
if key in eps_cache:
|
| 473 |
-
return eps_cache[key], eps_cache
|
| 474 |
-
sigma = self.sigma(t) * x.new_ones([x.shape[0]])
|
| 475 |
-
eps = (x - self.model(x, sigma, *args, **self.extra_args, **kwargs)) / self.sigma(t)
|
| 476 |
-
if self.eps_callback is not None:
|
| 477 |
-
self.eps_callback()
|
| 478 |
-
return eps, {key: eps, **eps_cache}
|
| 479 |
-
|
| 480 |
-
def dpm_solver_1_step(self, x, t, t_next, eps_cache=None):
|
| 481 |
-
eps_cache = {} if eps_cache is None else eps_cache
|
| 482 |
-
h = t_next - t
|
| 483 |
-
eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
|
| 484 |
-
x_1 = x - self.sigma(t_next) * h.expm1() * eps
|
| 485 |
-
return x_1, eps_cache
|
| 486 |
-
|
| 487 |
-
def dpm_solver_2_step(self, x, t, t_next, r1=1 / 2, eps_cache=None):
|
| 488 |
-
eps_cache = {} if eps_cache is None else eps_cache
|
| 489 |
-
h = t_next - t
|
| 490 |
-
eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
|
| 491 |
-
s1 = t + r1 * h
|
| 492 |
-
u1 = x - self.sigma(s1) * (r1 * h).expm1() * eps
|
| 493 |
-
eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', u1, s1)
|
| 494 |
-
x_2 = x - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / (2 * r1) * h.expm1() * (eps_r1 - eps)
|
| 495 |
-
return x_2, eps_cache
|
| 496 |
-
|
| 497 |
-
def dpm_solver_3_step(self, x, t, t_next, r1=1 / 3, r2=2 / 3, eps_cache=None):
|
| 498 |
-
eps_cache = {} if eps_cache is None else eps_cache
|
| 499 |
-
h = t_next - t
|
| 500 |
-
eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
|
| 501 |
-
s1 = t + r1 * h
|
| 502 |
-
s2 = t + r2 * h
|
| 503 |
-
u1 = x - self.sigma(s1) * (r1 * h).expm1() * eps
|
| 504 |
-
eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', u1, s1)
|
| 505 |
-
u2 = x - self.sigma(s2) * (r2 * h).expm1() * eps - self.sigma(s2) * (r2 / r1) * ((r2 * h).expm1() / (r2 * h) - 1) * (eps_r1 - eps)
|
| 506 |
-
eps_r2, eps_cache = self.eps(eps_cache, 'eps_r2', u2, s2)
|
| 507 |
-
x_3 = x - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / r2 * (h.expm1() / h - 1) * (eps_r2 - eps)
|
| 508 |
-
return x_3, eps_cache
|
| 509 |
-
|
| 510 |
-
def dpm_solver_fast(self, x, t_start, t_end, nfe, eta=0., s_noise=1., noise_sampler=None):
|
| 511 |
-
noise_sampler = default_noise_sampler(x, seed=self.extra_args.get("seed", None)) if noise_sampler is None else noise_sampler
|
| 512 |
-
if not t_end > t_start and eta:
|
| 513 |
-
raise ValueError('eta must be 0 for reverse sampling')
|
| 514 |
-
|
| 515 |
-
m = math.floor(nfe / 3) + 1
|
| 516 |
-
ts = torch.linspace(t_start, t_end, m + 1, device=x.device)
|
| 517 |
-
|
| 518 |
-
if nfe % 3 == 0:
|
| 519 |
-
orders = [3] * (m - 2) + [2, 1]
|
| 520 |
-
else:
|
| 521 |
-
orders = [3] * (m - 1) + [nfe % 3]
|
| 522 |
-
|
| 523 |
-
for i in range(len(orders)):
|
| 524 |
-
eps_cache = {}
|
| 525 |
-
t, t_next = ts[i], ts[i + 1]
|
| 526 |
-
if eta:
|
| 527 |
-
sd, su = get_ancestral_step(self.sigma(t), self.sigma(t_next), eta)
|
| 528 |
-
t_next_ = torch.minimum(t_end, self.t(sd))
|
| 529 |
-
su = (self.sigma(t_next) ** 2 - self.sigma(t_next_) ** 2) ** 0.5
|
| 530 |
-
else:
|
| 531 |
-
t_next_, su = t_next, 0.
|
| 532 |
-
|
| 533 |
-
eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
|
| 534 |
-
denoised = x - self.sigma(t) * eps
|
| 535 |
-
if self.info_callback is not None:
|
| 536 |
-
self.info_callback({'x': x, 'i': i, 't': ts[i], 't_up': t, 'denoised': denoised})
|
| 537 |
-
|
| 538 |
-
if orders[i] == 1:
|
| 539 |
-
x, eps_cache = self.dpm_solver_1_step(x, t, t_next_, eps_cache=eps_cache)
|
| 540 |
-
elif orders[i] == 2:
|
| 541 |
-
x, eps_cache = self.dpm_solver_2_step(x, t, t_next_, eps_cache=eps_cache)
|
| 542 |
-
else:
|
| 543 |
-
x, eps_cache = self.dpm_solver_3_step(x, t, t_next_, eps_cache=eps_cache)
|
| 544 |
-
|
| 545 |
-
x = x + su * s_noise * noise_sampler(self.sigma(t), self.sigma(t_next))
|
| 546 |
-
|
| 547 |
-
return x
|
| 548 |
-
|
| 549 |
-
def dpm_solver_adaptive(self, x, t_start, t_end, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None):
|
| 550 |
-
noise_sampler = default_noise_sampler(x, seed=self.extra_args.get("seed", None)) if noise_sampler is None else noise_sampler
|
| 551 |
-
if order not in {2, 3}:
|
| 552 |
-
raise ValueError('order should be 2 or 3')
|
| 553 |
-
forward = t_end > t_start
|
| 554 |
-
if not forward and eta:
|
| 555 |
-
raise ValueError('eta must be 0 for reverse sampling')
|
| 556 |
-
h_init = abs(h_init) * (1 if forward else -1)
|
| 557 |
-
atol = torch.tensor(atol)
|
| 558 |
-
rtol = torch.tensor(rtol)
|
| 559 |
-
s = t_start
|
| 560 |
-
x_prev = x
|
| 561 |
-
accept = True
|
| 562 |
-
pid = PIDStepSizeController(h_init, pcoeff, icoeff, dcoeff, 1.5 if eta else order, accept_safety)
|
| 563 |
-
info = {'steps': 0, 'nfe': 0, 'n_accept': 0, 'n_reject': 0}
|
| 564 |
-
|
| 565 |
-
while s < t_end - 1e-5 if forward else s > t_end + 1e-5:
|
| 566 |
-
eps_cache = {}
|
| 567 |
-
t = torch.minimum(t_end, s + pid.h) if forward else torch.maximum(t_end, s + pid.h)
|
| 568 |
-
if eta:
|
| 569 |
-
sd, su = get_ancestral_step(self.sigma(s), self.sigma(t), eta)
|
| 570 |
-
t_ = torch.minimum(t_end, self.t(sd))
|
| 571 |
-
su = (self.sigma(t) ** 2 - self.sigma(t_) ** 2) ** 0.5
|
| 572 |
-
else:
|
| 573 |
-
t_, su = t, 0.
|
| 574 |
-
|
| 575 |
-
eps, eps_cache = self.eps(eps_cache, 'eps', x, s)
|
| 576 |
-
denoised = x - self.sigma(s) * eps
|
| 577 |
-
|
| 578 |
-
if order == 2:
|
| 579 |
-
x_low, eps_cache = self.dpm_solver_1_step(x, s, t_, eps_cache=eps_cache)
|
| 580 |
-
x_high, eps_cache = self.dpm_solver_2_step(x, s, t_, eps_cache=eps_cache)
|
| 581 |
-
else:
|
| 582 |
-
x_low, eps_cache = self.dpm_solver_2_step(x, s, t_, r1=1 / 3, eps_cache=eps_cache)
|
| 583 |
-
x_high, eps_cache = self.dpm_solver_3_step(x, s, t_, eps_cache=eps_cache)
|
| 584 |
-
delta = torch.maximum(atol, rtol * torch.maximum(x_low.abs(), x_prev.abs()))
|
| 585 |
-
error = torch.linalg.norm((x_low - x_high) / delta) / x.numel() ** 0.5
|
| 586 |
-
accept = pid.propose_step(error)
|
| 587 |
-
if accept:
|
| 588 |
-
x_prev = x_low
|
| 589 |
-
x = x_high + su * s_noise * noise_sampler(self.sigma(s), self.sigma(t))
|
| 590 |
-
s = t
|
| 591 |
-
info['n_accept'] += 1
|
| 592 |
-
else:
|
| 593 |
-
info['n_reject'] += 1
|
| 594 |
-
info['nfe'] += order
|
| 595 |
-
info['steps'] += 1
|
| 596 |
-
|
| 597 |
-
if self.info_callback is not None:
|
| 598 |
-
self.info_callback({'x': x, 'i': info['steps'] - 1, 't': s, 't_up': s, 'denoised': denoised, 'error': error, 'h': pid.h, **info})
|
| 599 |
-
|
| 600 |
-
return x, info
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
@torch.no_grad()
|
| 604 |
-
def sample_dpm_fast(model, x, sigma_min, sigma_max, n, extra_args=None, callback=None, disable=None, eta=0., s_noise=1., noise_sampler=None):
|
| 605 |
-
"""DPM-Solver-Fast (fixed step size). See https://arxiv.org/abs/2206.00927."""
|
| 606 |
-
if sigma_min <= 0 or sigma_max <= 0:
|
| 607 |
-
raise ValueError('sigma_min and sigma_max must not be 0')
|
| 608 |
-
with tqdm(total=n, disable=disable) as pbar:
|
| 609 |
-
dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update)
|
| 610 |
-
if callback is not None:
|
| 611 |
-
dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info})
|
| 612 |
-
return dpm_solver.dpm_solver_fast(x, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), n, eta, s_noise, noise_sampler)
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
@torch.no_grad()
|
| 616 |
-
def sample_dpm_adaptive(model, x, sigma_min, sigma_max, extra_args=None, callback=None, disable=None, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None, return_info=False):
|
| 617 |
-
"""DPM-Solver-12 and 23 (adaptive step size). See https://arxiv.org/abs/2206.00927."""
|
| 618 |
-
if sigma_min <= 0 or sigma_max <= 0:
|
| 619 |
-
raise ValueError('sigma_min and sigma_max must not be 0')
|
| 620 |
-
with tqdm(disable=disable) as pbar:
|
| 621 |
-
dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update)
|
| 622 |
-
if callback is not None:
|
| 623 |
-
dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info})
|
| 624 |
-
x, info = dpm_solver.dpm_solver_adaptive(x, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), order, rtol, atol, h_init, pcoeff, icoeff, dcoeff, accept_safety, eta, s_noise, noise_sampler)
|
| 625 |
-
if return_info:
|
| 626 |
-
return x, info
|
| 627 |
-
return x
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
@torch.no_grad()
|
| 631 |
-
def sample_dpmpp_2s_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 632 |
-
if isinstance(model.inner_model.inner_model.model_sampling, comfy.model_sampling.CONST):
|
| 633 |
-
return sample_dpmpp_2s_ancestral_RF(model, x, sigmas, extra_args, callback, disable, eta, s_noise, noise_sampler)
|
| 634 |
-
|
| 635 |
-
"""Ancestral sampling with DPM-Solver++(2S) second-order steps."""
|
| 636 |
-
extra_args = {} if extra_args is None else extra_args
|
| 637 |
-
seed = extra_args.get("seed", None)
|
| 638 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 639 |
-
s_in = x.new_ones([x.shape[0]])
|
| 640 |
-
sigma_fn = lambda t: t.neg().exp()
|
| 641 |
-
t_fn = lambda sigma: sigma.log().neg()
|
| 642 |
-
|
| 643 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 644 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 645 |
-
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
| 646 |
-
if callback is not None:
|
| 647 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 648 |
-
if sigma_down == 0:
|
| 649 |
-
# Euler method
|
| 650 |
-
d = to_d(x, sigmas[i], denoised)
|
| 651 |
-
dt = sigma_down - sigmas[i]
|
| 652 |
-
x = x + d * dt
|
| 653 |
-
else:
|
| 654 |
-
# DPM-Solver++(2S)
|
| 655 |
-
t, t_next = t_fn(sigmas[i]), t_fn(sigma_down)
|
| 656 |
-
r = 1 / 2
|
| 657 |
-
h = t_next - t
|
| 658 |
-
s = t + r * h
|
| 659 |
-
x_2 = (sigma_fn(s) / sigma_fn(t)) * x - (-h * r).expm1() * denoised
|
| 660 |
-
denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args)
|
| 661 |
-
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_2
|
| 662 |
-
# Noise addition
|
| 663 |
-
if sigmas[i + 1] > 0:
|
| 664 |
-
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
| 665 |
-
return x
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
@torch.no_grad()
|
| 669 |
-
def sample_dpmpp_2s_ancestral_RF(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 670 |
-
"""Ancestral sampling with DPM-Solver++(2S) second-order steps."""
|
| 671 |
-
extra_args = {} if extra_args is None else extra_args
|
| 672 |
-
seed = extra_args.get("seed", None)
|
| 673 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 674 |
-
s_in = x.new_ones([x.shape[0]])
|
| 675 |
-
sigma_fn = lambda lbda: (lbda.exp() + 1) ** -1
|
| 676 |
-
lambda_fn = lambda sigma: ((1-sigma)/sigma).log()
|
| 677 |
-
|
| 678 |
-
# logged_x = x.unsqueeze(0)
|
| 679 |
-
|
| 680 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 681 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 682 |
-
downstep_ratio = 1 + (sigmas[i+1]/sigmas[i] - 1) * eta
|
| 683 |
-
sigma_down = sigmas[i+1] * downstep_ratio
|
| 684 |
-
alpha_ip1 = 1 - sigmas[i+1]
|
| 685 |
-
alpha_down = 1 - sigma_down
|
| 686 |
-
renoise_coeff = (sigmas[i+1]**2 - sigma_down**2*alpha_ip1**2/alpha_down**2)**0.5
|
| 687 |
-
# sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
| 688 |
-
if callback is not None:
|
| 689 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 690 |
-
if sigmas[i + 1] == 0:
|
| 691 |
-
# Euler method
|
| 692 |
-
d = to_d(x, sigmas[i], denoised)
|
| 693 |
-
dt = sigma_down - sigmas[i]
|
| 694 |
-
x = x + d * dt
|
| 695 |
-
else:
|
| 696 |
-
# DPM-Solver++(2S)
|
| 697 |
-
if sigmas[i] == 1.0:
|
| 698 |
-
sigma_s = 0.9999
|
| 699 |
-
else:
|
| 700 |
-
t_i, t_down = lambda_fn(sigmas[i]), lambda_fn(sigma_down)
|
| 701 |
-
r = 1 / 2
|
| 702 |
-
h = t_down - t_i
|
| 703 |
-
s = t_i + r * h
|
| 704 |
-
sigma_s = sigma_fn(s)
|
| 705 |
-
# sigma_s = sigmas[i+1]
|
| 706 |
-
sigma_s_i_ratio = sigma_s / sigmas[i]
|
| 707 |
-
u = sigma_s_i_ratio * x + (1 - sigma_s_i_ratio) * denoised
|
| 708 |
-
D_i = model(u, sigma_s * s_in, **extra_args)
|
| 709 |
-
sigma_down_i_ratio = sigma_down / sigmas[i]
|
| 710 |
-
x = sigma_down_i_ratio * x + (1 - sigma_down_i_ratio) * D_i
|
| 711 |
-
# print("sigma_i", sigmas[i], "sigma_ip1", sigmas[i+1],"sigma_down", sigma_down, "sigma_down_i_ratio", sigma_down_i_ratio, "sigma_s_i_ratio", sigma_s_i_ratio, "renoise_coeff", renoise_coeff)
|
| 712 |
-
# Noise addition
|
| 713 |
-
if sigmas[i + 1] > 0 and eta > 0:
|
| 714 |
-
x = (alpha_ip1/alpha_down) * x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * renoise_coeff
|
| 715 |
-
# logged_x = torch.cat((logged_x, x.unsqueeze(0)), dim=0)
|
| 716 |
-
return x
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
@torch.no_grad()
|
| 720 |
-
def sample_dpmpp_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2):
|
| 721 |
-
"""DPM-Solver++ (stochastic)."""
|
| 722 |
-
if len(sigmas) <= 1:
|
| 723 |
-
return x
|
| 724 |
-
|
| 725 |
-
extra_args = {} if extra_args is None else extra_args
|
| 726 |
-
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
| 727 |
-
seed = extra_args.get("seed", None)
|
| 728 |
-
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
| 729 |
-
s_in = x.new_ones([x.shape[0]])
|
| 730 |
-
|
| 731 |
-
model_sampling = model.inner_model.model_patcher.get_model_object('model_sampling')
|
| 732 |
-
sigma_fn = partial(half_log_snr_to_sigma, model_sampling=model_sampling)
|
| 733 |
-
lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
|
| 734 |
-
sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
|
| 735 |
-
|
| 736 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 737 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 738 |
-
if callback is not None:
|
| 739 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 740 |
-
if sigmas[i + 1] == 0:
|
| 741 |
-
# Denoising step
|
| 742 |
-
x = denoised
|
| 743 |
-
else:
|
| 744 |
-
# DPM-Solver++
|
| 745 |
-
lambda_s, lambda_t = lambda_fn(sigmas[i]), lambda_fn(sigmas[i + 1])
|
| 746 |
-
h = lambda_t - lambda_s
|
| 747 |
-
lambda_s_1 = lambda_s + r * h
|
| 748 |
-
fac = 1 / (2 * r)
|
| 749 |
-
|
| 750 |
-
sigma_s_1 = sigma_fn(lambda_s_1)
|
| 751 |
-
|
| 752 |
-
alpha_s = sigmas[i] * lambda_s.exp()
|
| 753 |
-
alpha_s_1 = sigma_s_1 * lambda_s_1.exp()
|
| 754 |
-
alpha_t = sigmas[i + 1] * lambda_t.exp()
|
| 755 |
-
|
| 756 |
-
# Step 1
|
| 757 |
-
sd, su = get_ancestral_step(lambda_s.neg().exp(), lambda_s_1.neg().exp(), eta)
|
| 758 |
-
lambda_s_1_ = sd.log().neg()
|
| 759 |
-
h_ = lambda_s_1_ - lambda_s
|
| 760 |
-
x_2 = (alpha_s_1 / alpha_s) * (-h_).exp() * x - alpha_s_1 * (-h_).expm1() * denoised
|
| 761 |
-
if eta > 0 and s_noise > 0:
|
| 762 |
-
x_2 = x_2 + alpha_s_1 * noise_sampler(sigmas[i], sigma_s_1) * s_noise * su
|
| 763 |
-
denoised_2 = model(x_2, sigma_s_1 * s_in, **extra_args)
|
| 764 |
-
|
| 765 |
-
# Step 2
|
| 766 |
-
sd, su = get_ancestral_step(lambda_s.neg().exp(), lambda_t.neg().exp(), eta)
|
| 767 |
-
lambda_t_ = sd.log().neg()
|
| 768 |
-
h_ = lambda_t_ - lambda_s
|
| 769 |
-
denoised_d = (1 - fac) * denoised + fac * denoised_2
|
| 770 |
-
x = (alpha_t / alpha_s) * (-h_).exp() * x - alpha_t * (-h_).expm1() * denoised_d
|
| 771 |
-
if eta > 0 and s_noise > 0:
|
| 772 |
-
x = x + alpha_t * noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * su
|
| 773 |
-
return x
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
@torch.no_grad()
|
| 777 |
-
def sample_dpmpp_2m(model, x, sigmas, extra_args=None, callback=None, disable=None):
|
| 778 |
-
"""DPM-Solver++(2M)."""
|
| 779 |
-
extra_args = {} if extra_args is None else extra_args
|
| 780 |
-
s_in = x.new_ones([x.shape[0]])
|
| 781 |
-
sigma_fn = lambda t: t.neg().exp()
|
| 782 |
-
t_fn = lambda sigma: sigma.log().neg()
|
| 783 |
-
old_denoised = None
|
| 784 |
-
|
| 785 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 786 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 787 |
-
if callback is not None:
|
| 788 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 789 |
-
t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
|
| 790 |
-
h = t_next - t
|
| 791 |
-
if old_denoised is None or sigmas[i + 1] == 0:
|
| 792 |
-
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised
|
| 793 |
-
else:
|
| 794 |
-
h_last = t - t_fn(sigmas[i - 1])
|
| 795 |
-
r = h_last / h
|
| 796 |
-
denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised
|
| 797 |
-
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_d
|
| 798 |
-
old_denoised = denoised
|
| 799 |
-
return x
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
@torch.no_grad()
|
| 803 |
-
def sample_dpmpp_2m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'):
|
| 804 |
-
"""DPM-Solver++(2M) SDE."""
|
| 805 |
-
if len(sigmas) <= 1:
|
| 806 |
-
return x
|
| 807 |
-
|
| 808 |
-
if solver_type not in {'heun', 'midpoint'}:
|
| 809 |
-
raise ValueError('solver_type must be \'heun\' or \'midpoint\'')
|
| 810 |
-
|
| 811 |
-
extra_args = {} if extra_args is None else extra_args
|
| 812 |
-
seed = extra_args.get("seed", None)
|
| 813 |
-
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
| 814 |
-
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
| 815 |
-
s_in = x.new_ones([x.shape[0]])
|
| 816 |
-
|
| 817 |
-
model_sampling = model.inner_model.model_patcher.get_model_object('model_sampling')
|
| 818 |
-
lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
|
| 819 |
-
sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
|
| 820 |
-
|
| 821 |
-
old_denoised = None
|
| 822 |
-
h, h_last = None, None
|
| 823 |
-
|
| 824 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 825 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 826 |
-
if callback is not None:
|
| 827 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 828 |
-
if sigmas[i + 1] == 0:
|
| 829 |
-
# Denoising step
|
| 830 |
-
x = denoised
|
| 831 |
-
else:
|
| 832 |
-
# DPM-Solver++(2M) SDE
|
| 833 |
-
lambda_s, lambda_t = lambda_fn(sigmas[i]), lambda_fn(sigmas[i + 1])
|
| 834 |
-
h = lambda_t - lambda_s
|
| 835 |
-
h_eta = h * (eta + 1)
|
| 836 |
-
|
| 837 |
-
alpha_t = sigmas[i + 1] * lambda_t.exp()
|
| 838 |
-
|
| 839 |
-
x = sigmas[i + 1] / sigmas[i] * (-h * eta).exp() * x + alpha_t * (-h_eta).expm1().neg() * denoised
|
| 840 |
-
|
| 841 |
-
if old_denoised is not None:
|
| 842 |
-
r = h_last / h
|
| 843 |
-
if solver_type == 'heun':
|
| 844 |
-
x = x + alpha_t * ((-h_eta).expm1().neg() / (-h_eta) + 1) * (1 / r) * (denoised - old_denoised)
|
| 845 |
-
elif solver_type == 'midpoint':
|
| 846 |
-
x = x + 0.5 * alpha_t * (-h_eta).expm1().neg() * (1 / r) * (denoised - old_denoised)
|
| 847 |
-
|
| 848 |
-
if eta > 0 and s_noise > 0:
|
| 849 |
-
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * h * eta).expm1().neg().sqrt() * s_noise
|
| 850 |
-
|
| 851 |
-
old_denoised = denoised
|
| 852 |
-
h_last = h
|
| 853 |
-
return x
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
@torch.no_grad()
|
| 857 |
-
def sample_dpmpp_3m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 858 |
-
"""DPM-Solver++(3M) SDE."""
|
| 859 |
-
|
| 860 |
-
if len(sigmas) <= 1:
|
| 861 |
-
return x
|
| 862 |
-
|
| 863 |
-
extra_args = {} if extra_args is None else extra_args
|
| 864 |
-
seed = extra_args.get("seed", None)
|
| 865 |
-
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
| 866 |
-
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
| 867 |
-
s_in = x.new_ones([x.shape[0]])
|
| 868 |
-
|
| 869 |
-
model_sampling = model.inner_model.model_patcher.get_model_object('model_sampling')
|
| 870 |
-
lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
|
| 871 |
-
sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
|
| 872 |
-
|
| 873 |
-
denoised_1, denoised_2 = None, None
|
| 874 |
-
h, h_1, h_2 = None, None, None
|
| 875 |
-
|
| 876 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 877 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 878 |
-
if callback is not None:
|
| 879 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 880 |
-
if sigmas[i + 1] == 0:
|
| 881 |
-
# Denoising step
|
| 882 |
-
x = denoised
|
| 883 |
-
else:
|
| 884 |
-
lambda_s, lambda_t = lambda_fn(sigmas[i]), lambda_fn(sigmas[i + 1])
|
| 885 |
-
h = lambda_t - lambda_s
|
| 886 |
-
h_eta = h * (eta + 1)
|
| 887 |
-
|
| 888 |
-
alpha_t = sigmas[i + 1] * lambda_t.exp()
|
| 889 |
-
|
| 890 |
-
x = sigmas[i + 1] / sigmas[i] * (-h * eta).exp() * x + alpha_t * (-h_eta).expm1().neg() * denoised
|
| 891 |
-
|
| 892 |
-
if h_2 is not None:
|
| 893 |
-
# DPM-Solver++(3M) SDE
|
| 894 |
-
r0 = h_1 / h
|
| 895 |
-
r1 = h_2 / h
|
| 896 |
-
d1_0 = (denoised - denoised_1) / r0
|
| 897 |
-
d1_1 = (denoised_1 - denoised_2) / r1
|
| 898 |
-
d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)
|
| 899 |
-
d2 = (d1_0 - d1_1) / (r0 + r1)
|
| 900 |
-
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
| 901 |
-
phi_3 = phi_2 / h_eta - 0.5
|
| 902 |
-
x = x + (alpha_t * phi_2) * d1 - (alpha_t * phi_3) * d2
|
| 903 |
-
elif h_1 is not None:
|
| 904 |
-
# DPM-Solver++(2M) SDE
|
| 905 |
-
r = h_1 / h
|
| 906 |
-
d = (denoised - denoised_1) / r
|
| 907 |
-
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
| 908 |
-
x = x + (alpha_t * phi_2) * d
|
| 909 |
-
|
| 910 |
-
if eta > 0 and s_noise > 0:
|
| 911 |
-
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * h * eta).expm1().neg().sqrt() * s_noise
|
| 912 |
-
|
| 913 |
-
denoised_1, denoised_2 = denoised, denoised_1
|
| 914 |
-
h_1, h_2 = h, h_1
|
| 915 |
-
return x
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
@torch.no_grad()
|
| 919 |
-
def sample_dpmpp_3m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 920 |
-
if len(sigmas) <= 1:
|
| 921 |
-
return x
|
| 922 |
-
extra_args = {} if extra_args is None else extra_args
|
| 923 |
-
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
| 924 |
-
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
| 925 |
-
return sample_dpmpp_3m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler)
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
@torch.no_grad()
|
| 929 |
-
def sample_dpmpp_2m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'):
|
| 930 |
-
if len(sigmas) <= 1:
|
| 931 |
-
return x
|
| 932 |
-
extra_args = {} if extra_args is None else extra_args
|
| 933 |
-
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
| 934 |
-
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
| 935 |
-
return sample_dpmpp_2m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, solver_type=solver_type)
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
@torch.no_grad()
|
| 939 |
-
def sample_dpmpp_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2):
|
| 940 |
-
if len(sigmas) <= 1:
|
| 941 |
-
return x
|
| 942 |
-
extra_args = {} if extra_args is None else extra_args
|
| 943 |
-
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
| 944 |
-
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
| 945 |
-
return sample_dpmpp_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, r=r)
|
| 946 |
-
|
| 947 |
-
|
| 948 |
-
def DDPMSampler_step(x, sigma, sigma_prev, noise, noise_sampler):
|
| 949 |
-
alpha_cumprod = 1 / ((sigma * sigma) + 1)
|
| 950 |
-
alpha_cumprod_prev = 1 / ((sigma_prev * sigma_prev) + 1)
|
| 951 |
-
alpha = (alpha_cumprod / alpha_cumprod_prev)
|
| 952 |
-
|
| 953 |
-
mu = (1.0 / alpha).sqrt() * (x - (1 - alpha) * noise / (1 - alpha_cumprod).sqrt())
|
| 954 |
-
if sigma_prev > 0:
|
| 955 |
-
mu += ((1 - alpha) * (1. - alpha_cumprod_prev) / (1. - alpha_cumprod)).sqrt() * noise_sampler(sigma, sigma_prev)
|
| 956 |
-
return mu
|
| 957 |
-
|
| 958 |
-
def generic_step_sampler(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None, step_function=None):
|
| 959 |
-
extra_args = {} if extra_args is None else extra_args
|
| 960 |
-
seed = extra_args.get("seed", None)
|
| 961 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 962 |
-
s_in = x.new_ones([x.shape[0]])
|
| 963 |
-
|
| 964 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 965 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 966 |
-
if callback is not None:
|
| 967 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 968 |
-
x = step_function(x / torch.sqrt(1.0 + sigmas[i] ** 2.0), sigmas[i], sigmas[i + 1], (x - denoised) / sigmas[i], noise_sampler)
|
| 969 |
-
if sigmas[i + 1] != 0:
|
| 970 |
-
x *= torch.sqrt(1.0 + sigmas[i + 1] ** 2.0)
|
| 971 |
-
return x
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
@torch.no_grad()
|
| 975 |
-
def sample_ddpm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None):
|
| 976 |
-
return generic_step_sampler(model, x, sigmas, extra_args, callback, disable, noise_sampler, DDPMSampler_step)
|
| 977 |
-
|
| 978 |
-
@torch.no_grad()
|
| 979 |
-
def sample_lcm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None):
|
| 980 |
-
extra_args = {} if extra_args is None else extra_args
|
| 981 |
-
seed = extra_args.get("seed", None)
|
| 982 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 983 |
-
s_in = x.new_ones([x.shape[0]])
|
| 984 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 985 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 986 |
-
if callback is not None:
|
| 987 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 988 |
-
|
| 989 |
-
x = denoised
|
| 990 |
-
if sigmas[i + 1] > 0:
|
| 991 |
-
x = model.inner_model.inner_model.model_sampling.noise_scaling(sigmas[i + 1], noise_sampler(sigmas[i], sigmas[i + 1]), x)
|
| 992 |
-
return x
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
@torch.no_grad()
|
| 997 |
-
def sample_heunpp2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
|
| 998 |
-
# From MIT licensed: https://github.com/Carzit/sd-webui-samplers-scheduler/
|
| 999 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1000 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1001 |
-
s_end = sigmas[-1]
|
| 1002 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1003 |
-
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
| 1004 |
-
eps = torch.randn_like(x) * s_noise
|
| 1005 |
-
sigma_hat = sigmas[i] * (gamma + 1)
|
| 1006 |
-
if gamma > 0:
|
| 1007 |
-
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
| 1008 |
-
denoised = model(x, sigma_hat * s_in, **extra_args)
|
| 1009 |
-
d = to_d(x, sigma_hat, denoised)
|
| 1010 |
-
if callback is not None:
|
| 1011 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
| 1012 |
-
dt = sigmas[i + 1] - sigma_hat
|
| 1013 |
-
if sigmas[i + 1] == s_end:
|
| 1014 |
-
# Euler method
|
| 1015 |
-
x = x + d * dt
|
| 1016 |
-
elif sigmas[i + 2] == s_end:
|
| 1017 |
-
|
| 1018 |
-
# Heun's method
|
| 1019 |
-
x_2 = x + d * dt
|
| 1020 |
-
denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
|
| 1021 |
-
d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
|
| 1022 |
-
|
| 1023 |
-
w = 2 * sigmas[0]
|
| 1024 |
-
w2 = sigmas[i+1]/w
|
| 1025 |
-
w1 = 1 - w2
|
| 1026 |
-
|
| 1027 |
-
d_prime = d * w1 + d_2 * w2
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
x = x + d_prime * dt
|
| 1031 |
-
|
| 1032 |
-
else:
|
| 1033 |
-
# Heun++
|
| 1034 |
-
x_2 = x + d * dt
|
| 1035 |
-
denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
|
| 1036 |
-
d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
|
| 1037 |
-
dt_2 = sigmas[i + 2] - sigmas[i + 1]
|
| 1038 |
-
|
| 1039 |
-
x_3 = x_2 + d_2 * dt_2
|
| 1040 |
-
denoised_3 = model(x_3, sigmas[i + 2] * s_in, **extra_args)
|
| 1041 |
-
d_3 = to_d(x_3, sigmas[i + 2], denoised_3)
|
| 1042 |
-
|
| 1043 |
-
w = 3 * sigmas[0]
|
| 1044 |
-
w2 = sigmas[i + 1] / w
|
| 1045 |
-
w3 = sigmas[i + 2] / w
|
| 1046 |
-
w1 = 1 - w2 - w3
|
| 1047 |
-
|
| 1048 |
-
d_prime = w1 * d + w2 * d_2 + w3 * d_3
|
| 1049 |
-
x = x + d_prime * dt
|
| 1050 |
-
return x
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
#From https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py
|
| 1054 |
-
#under Apache 2 license
|
| 1055 |
-
def sample_ipndm(model, x, sigmas, extra_args=None, callback=None, disable=None, max_order=4):
|
| 1056 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1057 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1058 |
-
|
| 1059 |
-
x_next = x
|
| 1060 |
-
|
| 1061 |
-
buffer_model = []
|
| 1062 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1063 |
-
t_cur = sigmas[i]
|
| 1064 |
-
t_next = sigmas[i + 1]
|
| 1065 |
-
|
| 1066 |
-
x_cur = x_next
|
| 1067 |
-
|
| 1068 |
-
denoised = model(x_cur, t_cur * s_in, **extra_args)
|
| 1069 |
-
if callback is not None:
|
| 1070 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1071 |
-
|
| 1072 |
-
d_cur = (x_cur - denoised) / t_cur
|
| 1073 |
-
|
| 1074 |
-
order = min(max_order, i+1)
|
| 1075 |
-
if t_next == 0: # Denoising step
|
| 1076 |
-
x_next = denoised
|
| 1077 |
-
elif order == 1: # First Euler step.
|
| 1078 |
-
x_next = x_cur + (t_next - t_cur) * d_cur
|
| 1079 |
-
elif order == 2: # Use one history point.
|
| 1080 |
-
x_next = x_cur + (t_next - t_cur) * (3 * d_cur - buffer_model[-1]) / 2
|
| 1081 |
-
elif order == 3: # Use two history points.
|
| 1082 |
-
x_next = x_cur + (t_next - t_cur) * (23 * d_cur - 16 * buffer_model[-1] + 5 * buffer_model[-2]) / 12
|
| 1083 |
-
elif order == 4: # Use three history points.
|
| 1084 |
-
x_next = x_cur + (t_next - t_cur) * (55 * d_cur - 59 * buffer_model[-1] + 37 * buffer_model[-2] - 9 * buffer_model[-3]) / 24
|
| 1085 |
-
|
| 1086 |
-
if len(buffer_model) == max_order - 1:
|
| 1087 |
-
for k in range(max_order - 2):
|
| 1088 |
-
buffer_model[k] = buffer_model[k+1]
|
| 1089 |
-
buffer_model[-1] = d_cur
|
| 1090 |
-
else:
|
| 1091 |
-
buffer_model.append(d_cur)
|
| 1092 |
-
|
| 1093 |
-
return x_next
|
| 1094 |
-
|
| 1095 |
-
|
| 1096 |
-
#From https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py
|
| 1097 |
-
#under Apache 2 license
|
| 1098 |
-
def sample_ipndm_v(model, x, sigmas, extra_args=None, callback=None, disable=None, max_order=4):
|
| 1099 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1100 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1101 |
-
|
| 1102 |
-
x_next = x
|
| 1103 |
-
t_steps = sigmas
|
| 1104 |
-
|
| 1105 |
-
buffer_model = []
|
| 1106 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1107 |
-
t_cur = sigmas[i]
|
| 1108 |
-
t_next = sigmas[i + 1]
|
| 1109 |
-
|
| 1110 |
-
x_cur = x_next
|
| 1111 |
-
|
| 1112 |
-
denoised = model(x_cur, t_cur * s_in, **extra_args)
|
| 1113 |
-
if callback is not None:
|
| 1114 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1115 |
-
|
| 1116 |
-
d_cur = (x_cur - denoised) / t_cur
|
| 1117 |
-
|
| 1118 |
-
order = min(max_order, i+1)
|
| 1119 |
-
if t_next == 0: # Denoising step
|
| 1120 |
-
x_next = denoised
|
| 1121 |
-
elif order == 1: # First Euler step.
|
| 1122 |
-
x_next = x_cur + (t_next - t_cur) * d_cur
|
| 1123 |
-
elif order == 2: # Use one history point.
|
| 1124 |
-
h_n = (t_next - t_cur)
|
| 1125 |
-
h_n_1 = (t_cur - t_steps[i-1])
|
| 1126 |
-
coeff1 = (2 + (h_n / h_n_1)) / 2
|
| 1127 |
-
coeff2 = -(h_n / h_n_1) / 2
|
| 1128 |
-
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1])
|
| 1129 |
-
elif order == 3: # Use two history points.
|
| 1130 |
-
h_n = (t_next - t_cur)
|
| 1131 |
-
h_n_1 = (t_cur - t_steps[i-1])
|
| 1132 |
-
h_n_2 = (t_steps[i-1] - t_steps[i-2])
|
| 1133 |
-
temp = (1 - h_n / (3 * (h_n + h_n_1)) * (h_n * (h_n + h_n_1)) / (h_n_1 * (h_n_1 + h_n_2))) / 2
|
| 1134 |
-
coeff1 = (2 + (h_n / h_n_1)) / 2 + temp
|
| 1135 |
-
coeff2 = -(h_n / h_n_1) / 2 - (1 + h_n_1 / h_n_2) * temp
|
| 1136 |
-
coeff3 = temp * h_n_1 / h_n_2
|
| 1137 |
-
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1] + coeff3 * buffer_model[-2])
|
| 1138 |
-
elif order == 4: # Use three history points.
|
| 1139 |
-
h_n = (t_next - t_cur)
|
| 1140 |
-
h_n_1 = (t_cur - t_steps[i-1])
|
| 1141 |
-
h_n_2 = (t_steps[i-1] - t_steps[i-2])
|
| 1142 |
-
h_n_3 = (t_steps[i-2] - t_steps[i-3])
|
| 1143 |
-
temp1 = (1 - h_n / (3 * (h_n + h_n_1)) * (h_n * (h_n + h_n_1)) / (h_n_1 * (h_n_1 + h_n_2))) / 2
|
| 1144 |
-
temp2 = ((1 - h_n / (3 * (h_n + h_n_1))) / 2 + (1 - h_n / (2 * (h_n + h_n_1))) * h_n / (6 * (h_n + h_n_1 + h_n_2))) \
|
| 1145 |
-
* (h_n * (h_n + h_n_1) * (h_n + h_n_1 + h_n_2)) / (h_n_1 * (h_n_1 + h_n_2) * (h_n_1 + h_n_2 + h_n_3))
|
| 1146 |
-
coeff1 = (2 + (h_n / h_n_1)) / 2 + temp1 + temp2
|
| 1147 |
-
coeff2 = -(h_n / h_n_1) / 2 - (1 + h_n_1 / h_n_2) * temp1 - (1 + (h_n_1 / h_n_2) + (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3)))) * temp2
|
| 1148 |
-
coeff3 = temp1 * h_n_1 / h_n_2 + ((h_n_1 / h_n_2) + (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3))) * (1 + h_n_2 / h_n_3)) * temp2
|
| 1149 |
-
coeff4 = -temp2 * (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3))) * h_n_1 / h_n_2
|
| 1150 |
-
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1] + coeff3 * buffer_model[-2] + coeff4 * buffer_model[-3])
|
| 1151 |
-
|
| 1152 |
-
if len(buffer_model) == max_order - 1:
|
| 1153 |
-
for k in range(max_order - 2):
|
| 1154 |
-
buffer_model[k] = buffer_model[k+1]
|
| 1155 |
-
buffer_model[-1] = d_cur.detach()
|
| 1156 |
-
else:
|
| 1157 |
-
buffer_model.append(d_cur.detach())
|
| 1158 |
-
|
| 1159 |
-
return x_next
|
| 1160 |
-
|
| 1161 |
-
|
| 1162 |
-
#From https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py
|
| 1163 |
-
#under Apache 2 license
|
| 1164 |
-
@torch.no_grad()
|
| 1165 |
-
def sample_deis(model, x, sigmas, extra_args=None, callback=None, disable=None, max_order=3, deis_mode='tab'):
|
| 1166 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1167 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1168 |
-
|
| 1169 |
-
x_next = x
|
| 1170 |
-
t_steps = sigmas
|
| 1171 |
-
|
| 1172 |
-
coeff_list = deis.get_deis_coeff_list(t_steps, max_order, deis_mode=deis_mode)
|
| 1173 |
-
|
| 1174 |
-
buffer_model = []
|
| 1175 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1176 |
-
t_cur = sigmas[i]
|
| 1177 |
-
t_next = sigmas[i + 1]
|
| 1178 |
-
|
| 1179 |
-
x_cur = x_next
|
| 1180 |
-
|
| 1181 |
-
denoised = model(x_cur, t_cur * s_in, **extra_args)
|
| 1182 |
-
if callback is not None:
|
| 1183 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1184 |
-
|
| 1185 |
-
d_cur = (x_cur - denoised) / t_cur
|
| 1186 |
-
|
| 1187 |
-
order = min(max_order, i+1)
|
| 1188 |
-
if t_next <= 0:
|
| 1189 |
-
order = 1
|
| 1190 |
-
|
| 1191 |
-
if order == 1: # First Euler step.
|
| 1192 |
-
x_next = x_cur + (t_next - t_cur) * d_cur
|
| 1193 |
-
elif order == 2: # Use one history point.
|
| 1194 |
-
coeff_cur, coeff_prev1 = coeff_list[i]
|
| 1195 |
-
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1]
|
| 1196 |
-
elif order == 3: # Use two history points.
|
| 1197 |
-
coeff_cur, coeff_prev1, coeff_prev2 = coeff_list[i]
|
| 1198 |
-
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1] + coeff_prev2 * buffer_model[-2]
|
| 1199 |
-
elif order == 4: # Use three history points.
|
| 1200 |
-
coeff_cur, coeff_prev1, coeff_prev2, coeff_prev3 = coeff_list[i]
|
| 1201 |
-
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1] + coeff_prev2 * buffer_model[-2] + coeff_prev3 * buffer_model[-3]
|
| 1202 |
-
|
| 1203 |
-
if len(buffer_model) == max_order - 1:
|
| 1204 |
-
for k in range(max_order - 2):
|
| 1205 |
-
buffer_model[k] = buffer_model[k+1]
|
| 1206 |
-
buffer_model[-1] = d_cur.detach()
|
| 1207 |
-
else:
|
| 1208 |
-
buffer_model.append(d_cur.detach())
|
| 1209 |
-
|
| 1210 |
-
return x_next
|
| 1211 |
-
|
| 1212 |
-
|
| 1213 |
-
@torch.no_grad()
|
| 1214 |
-
def sample_euler_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None):
|
| 1215 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1216 |
-
|
| 1217 |
-
temp = [0]
|
| 1218 |
-
def post_cfg_function(args):
|
| 1219 |
-
temp[0] = args["uncond_denoised"]
|
| 1220 |
-
return args["denoised"]
|
| 1221 |
-
|
| 1222 |
-
model_options = extra_args.get("model_options", {}).copy()
|
| 1223 |
-
extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
|
| 1224 |
-
|
| 1225 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1226 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1227 |
-
sigma_hat = sigmas[i]
|
| 1228 |
-
denoised = model(x, sigma_hat * s_in, **extra_args)
|
| 1229 |
-
d = to_d(x, sigma_hat, temp[0])
|
| 1230 |
-
if callback is not None:
|
| 1231 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
| 1232 |
-
# Euler method
|
| 1233 |
-
x = denoised + d * sigmas[i + 1]
|
| 1234 |
-
return x
|
| 1235 |
-
|
| 1236 |
-
@torch.no_grad()
|
| 1237 |
-
def sample_euler_ancestral_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 1238 |
-
"""Ancestral sampling with Euler method steps."""
|
| 1239 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1240 |
-
seed = extra_args.get("seed", None)
|
| 1241 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 1242 |
-
|
| 1243 |
-
temp = [0]
|
| 1244 |
-
def post_cfg_function(args):
|
| 1245 |
-
temp[0] = args["uncond_denoised"]
|
| 1246 |
-
return args["denoised"]
|
| 1247 |
-
|
| 1248 |
-
model_options = extra_args.get("model_options", {}).copy()
|
| 1249 |
-
extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
|
| 1250 |
-
|
| 1251 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1252 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1253 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1254 |
-
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
| 1255 |
-
if callback is not None:
|
| 1256 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1257 |
-
d = to_d(x, sigmas[i], temp[0])
|
| 1258 |
-
# Euler method
|
| 1259 |
-
x = denoised + d * sigma_down
|
| 1260 |
-
if sigmas[i + 1] > 0:
|
| 1261 |
-
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
| 1262 |
-
return x
|
| 1263 |
-
@torch.no_grad()
|
| 1264 |
-
def sample_dpmpp_2s_ancestral_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 1265 |
-
"""Ancestral sampling with DPM-Solver++(2S) second-order steps."""
|
| 1266 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1267 |
-
seed = extra_args.get("seed", None)
|
| 1268 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 1269 |
-
|
| 1270 |
-
temp = [0]
|
| 1271 |
-
def post_cfg_function(args):
|
| 1272 |
-
temp[0] = args["uncond_denoised"]
|
| 1273 |
-
return args["denoised"]
|
| 1274 |
-
|
| 1275 |
-
model_options = extra_args.get("model_options", {}).copy()
|
| 1276 |
-
extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
|
| 1277 |
-
|
| 1278 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1279 |
-
sigma_fn = lambda t: t.neg().exp()
|
| 1280 |
-
t_fn = lambda sigma: sigma.log().neg()
|
| 1281 |
-
|
| 1282 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1283 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1284 |
-
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
| 1285 |
-
if callback is not None:
|
| 1286 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1287 |
-
if sigma_down == 0:
|
| 1288 |
-
# Euler method
|
| 1289 |
-
d = to_d(x, sigmas[i], temp[0])
|
| 1290 |
-
x = denoised + d * sigma_down
|
| 1291 |
-
else:
|
| 1292 |
-
# DPM-Solver++(2S)
|
| 1293 |
-
t, t_next = t_fn(sigmas[i]), t_fn(sigma_down)
|
| 1294 |
-
# r = torch.sinh(1 + (2 - eta) * (t_next - t) / (t - t_fn(sigma_up))) works only on non-cfgpp, weird
|
| 1295 |
-
r = 1 / 2
|
| 1296 |
-
h = t_next - t
|
| 1297 |
-
s = t + r * h
|
| 1298 |
-
x_2 = (sigma_fn(s) / sigma_fn(t)) * (x + (denoised - temp[0])) - (-h * r).expm1() * denoised
|
| 1299 |
-
denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args)
|
| 1300 |
-
x = (sigma_fn(t_next) / sigma_fn(t)) * (x + (denoised - temp[0])) - (-h).expm1() * denoised_2
|
| 1301 |
-
# Noise addition
|
| 1302 |
-
if sigmas[i + 1] > 0:
|
| 1303 |
-
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
| 1304 |
-
return x
|
| 1305 |
-
|
| 1306 |
-
@torch.no_grad()
|
| 1307 |
-
def sample_dpmpp_2m_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None):
|
| 1308 |
-
"""DPM-Solver++(2M)."""
|
| 1309 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1310 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1311 |
-
t_fn = lambda sigma: sigma.log().neg()
|
| 1312 |
-
|
| 1313 |
-
old_uncond_denoised = None
|
| 1314 |
-
uncond_denoised = None
|
| 1315 |
-
def post_cfg_function(args):
|
| 1316 |
-
nonlocal uncond_denoised
|
| 1317 |
-
uncond_denoised = args["uncond_denoised"]
|
| 1318 |
-
return args["denoised"]
|
| 1319 |
-
|
| 1320 |
-
model_options = extra_args.get("model_options", {}).copy()
|
| 1321 |
-
extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
|
| 1322 |
-
|
| 1323 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1324 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1325 |
-
if callback is not None:
|
| 1326 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1327 |
-
t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
|
| 1328 |
-
h = t_next - t
|
| 1329 |
-
if old_uncond_denoised is None or sigmas[i + 1] == 0:
|
| 1330 |
-
denoised_mix = -torch.exp(-h) * uncond_denoised
|
| 1331 |
-
else:
|
| 1332 |
-
h_last = t - t_fn(sigmas[i - 1])
|
| 1333 |
-
r = h_last / h
|
| 1334 |
-
denoised_mix = -torch.exp(-h) * uncond_denoised - torch.expm1(-h) * (1 / (2 * r)) * (denoised - old_uncond_denoised)
|
| 1335 |
-
x = denoised + denoised_mix + torch.exp(-h) * x
|
| 1336 |
-
old_uncond_denoised = uncond_denoised
|
| 1337 |
-
return x
|
| 1338 |
-
|
| 1339 |
-
@torch.no_grad()
|
| 1340 |
-
def res_multistep(model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1., noise_sampler=None, eta=1., cfg_pp=False):
|
| 1341 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1342 |
-
seed = extra_args.get("seed", None)
|
| 1343 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 1344 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1345 |
-
sigma_fn = lambda t: t.neg().exp()
|
| 1346 |
-
t_fn = lambda sigma: sigma.log().neg()
|
| 1347 |
-
phi1_fn = lambda t: torch.expm1(t) / t
|
| 1348 |
-
phi2_fn = lambda t: (phi1_fn(t) - 1.0) / t
|
| 1349 |
-
|
| 1350 |
-
old_sigma_down = None
|
| 1351 |
-
old_denoised = None
|
| 1352 |
-
uncond_denoised = None
|
| 1353 |
-
def post_cfg_function(args):
|
| 1354 |
-
nonlocal uncond_denoised
|
| 1355 |
-
uncond_denoised = args["uncond_denoised"]
|
| 1356 |
-
return args["denoised"]
|
| 1357 |
-
|
| 1358 |
-
if cfg_pp:
|
| 1359 |
-
model_options = extra_args.get("model_options", {}).copy()
|
| 1360 |
-
extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
|
| 1361 |
-
|
| 1362 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1363 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1364 |
-
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
| 1365 |
-
if callback is not None:
|
| 1366 |
-
callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
|
| 1367 |
-
if sigma_down == 0 or old_denoised is None:
|
| 1368 |
-
# Euler method
|
| 1369 |
-
if cfg_pp:
|
| 1370 |
-
d = to_d(x, sigmas[i], uncond_denoised)
|
| 1371 |
-
x = denoised + d * sigma_down
|
| 1372 |
-
else:
|
| 1373 |
-
d = to_d(x, sigmas[i], denoised)
|
| 1374 |
-
dt = sigma_down - sigmas[i]
|
| 1375 |
-
x = x + d * dt
|
| 1376 |
-
else:
|
| 1377 |
-
# Second order multistep method in https://arxiv.org/pdf/2308.02157
|
| 1378 |
-
t, t_old, t_next, t_prev = t_fn(sigmas[i]), t_fn(old_sigma_down), t_fn(sigma_down), t_fn(sigmas[i - 1])
|
| 1379 |
-
h = t_next - t
|
| 1380 |
-
c2 = (t_prev - t_old) / h
|
| 1381 |
-
|
| 1382 |
-
phi1_val, phi2_val = phi1_fn(-h), phi2_fn(-h)
|
| 1383 |
-
b1 = torch.nan_to_num(phi1_val - phi2_val / c2, nan=0.0)
|
| 1384 |
-
b2 = torch.nan_to_num(phi2_val / c2, nan=0.0)
|
| 1385 |
-
|
| 1386 |
-
if cfg_pp:
|
| 1387 |
-
x = x + (denoised - uncond_denoised)
|
| 1388 |
-
x = sigma_fn(h) * x + h * (b1 * uncond_denoised + b2 * old_denoised)
|
| 1389 |
-
else:
|
| 1390 |
-
x = sigma_fn(h) * x + h * (b1 * denoised + b2 * old_denoised)
|
| 1391 |
-
|
| 1392 |
-
# Noise addition
|
| 1393 |
-
if sigmas[i + 1] > 0:
|
| 1394 |
-
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
| 1395 |
-
|
| 1396 |
-
if cfg_pp:
|
| 1397 |
-
old_denoised = uncond_denoised
|
| 1398 |
-
else:
|
| 1399 |
-
old_denoised = denoised
|
| 1400 |
-
old_sigma_down = sigma_down
|
| 1401 |
-
return x
|
| 1402 |
-
|
| 1403 |
-
@torch.no_grad()
|
| 1404 |
-
def sample_res_multistep(model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1., noise_sampler=None):
|
| 1405 |
-
return res_multistep(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, s_noise=s_noise, noise_sampler=noise_sampler, eta=0., cfg_pp=False)
|
| 1406 |
-
|
| 1407 |
-
@torch.no_grad()
|
| 1408 |
-
def sample_res_multistep_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1., noise_sampler=None):
|
| 1409 |
-
return res_multistep(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, s_noise=s_noise, noise_sampler=noise_sampler, eta=0., cfg_pp=True)
|
| 1410 |
-
|
| 1411 |
-
@torch.no_grad()
|
| 1412 |
-
def sample_res_multistep_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 1413 |
-
return res_multistep(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, s_noise=s_noise, noise_sampler=noise_sampler, eta=eta, cfg_pp=False)
|
| 1414 |
-
|
| 1415 |
-
@torch.no_grad()
|
| 1416 |
-
def sample_res_multistep_ancestral_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
| 1417 |
-
return res_multistep(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, s_noise=s_noise, noise_sampler=noise_sampler, eta=eta, cfg_pp=True)
|
| 1418 |
-
|
| 1419 |
-
|
| 1420 |
-
@torch.no_grad()
|
| 1421 |
-
def sample_gradient_estimation(model, x, sigmas, extra_args=None, callback=None, disable=None, ge_gamma=2., cfg_pp=False):
|
| 1422 |
-
"""Gradient-estimation sampler. Paper: https://openreview.net/pdf?id=o2ND9v0CeK"""
|
| 1423 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1424 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1425 |
-
old_d = None
|
| 1426 |
-
|
| 1427 |
-
uncond_denoised = None
|
| 1428 |
-
def post_cfg_function(args):
|
| 1429 |
-
nonlocal uncond_denoised
|
| 1430 |
-
uncond_denoised = args["uncond_denoised"]
|
| 1431 |
-
return args["denoised"]
|
| 1432 |
-
|
| 1433 |
-
if cfg_pp:
|
| 1434 |
-
model_options = extra_args.get("model_options", {}).copy()
|
| 1435 |
-
extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
|
| 1436 |
-
|
| 1437 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1438 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1439 |
-
if cfg_pp:
|
| 1440 |
-
d = to_d(x, sigmas[i], uncond_denoised)
|
| 1441 |
-
else:
|
| 1442 |
-
d = to_d(x, sigmas[i], denoised)
|
| 1443 |
-
if callback is not None:
|
| 1444 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1445 |
-
dt = sigmas[i + 1] - sigmas[i]
|
| 1446 |
-
if sigmas[i + 1] == 0:
|
| 1447 |
-
# Denoising step
|
| 1448 |
-
x = denoised
|
| 1449 |
-
else:
|
| 1450 |
-
# Euler method
|
| 1451 |
-
if cfg_pp:
|
| 1452 |
-
x = denoised + d * sigmas[i + 1]
|
| 1453 |
-
else:
|
| 1454 |
-
x = x + d * dt
|
| 1455 |
-
|
| 1456 |
-
if i >= 1:
|
| 1457 |
-
# Gradient estimation
|
| 1458 |
-
d_bar = (ge_gamma - 1) * (d - old_d)
|
| 1459 |
-
x = x + d_bar * dt
|
| 1460 |
-
old_d = d
|
| 1461 |
-
return x
|
| 1462 |
-
|
| 1463 |
-
|
| 1464 |
-
@torch.no_grad()
|
| 1465 |
-
def sample_gradient_estimation_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None, ge_gamma=2.):
|
| 1466 |
-
return sample_gradient_estimation(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, ge_gamma=ge_gamma, cfg_pp=True)
|
| 1467 |
-
|
| 1468 |
-
|
| 1469 |
-
@torch.no_grad()
|
| 1470 |
-
def sample_er_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1.0, noise_sampler=None, noise_scaler=None, max_stage=3):
|
| 1471 |
-
"""Extended Reverse-Time SDE solver (VP ER-SDE-Solver-3). arXiv: https://arxiv.org/abs/2309.06169.
|
| 1472 |
-
Code reference: https://github.com/QinpengCui/ER-SDE-Solver/blob/main/er_sde_solver.py.
|
| 1473 |
-
"""
|
| 1474 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1475 |
-
seed = extra_args.get("seed", None)
|
| 1476 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 1477 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1478 |
-
|
| 1479 |
-
def default_er_sde_noise_scaler(x):
|
| 1480 |
-
return x * ((x ** 0.3).exp() + 10.0)
|
| 1481 |
-
|
| 1482 |
-
noise_scaler = default_er_sde_noise_scaler if noise_scaler is None else noise_scaler
|
| 1483 |
-
num_integration_points = 200.0
|
| 1484 |
-
point_indice = torch.arange(0, num_integration_points, dtype=torch.float32, device=x.device)
|
| 1485 |
-
|
| 1486 |
-
model_sampling = model.inner_model.model_patcher.get_model_object("model_sampling")
|
| 1487 |
-
sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
|
| 1488 |
-
half_log_snrs = sigma_to_half_log_snr(sigmas, model_sampling)
|
| 1489 |
-
er_lambdas = half_log_snrs.neg().exp() # er_lambda_t = sigma_t / alpha_t
|
| 1490 |
-
|
| 1491 |
-
old_denoised = None
|
| 1492 |
-
old_denoised_d = None
|
| 1493 |
-
|
| 1494 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1495 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1496 |
-
if callback is not None:
|
| 1497 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1498 |
-
stage_used = min(max_stage, i + 1)
|
| 1499 |
-
if sigmas[i + 1] == 0:
|
| 1500 |
-
x = denoised
|
| 1501 |
-
else:
|
| 1502 |
-
er_lambda_s, er_lambda_t = er_lambdas[i], er_lambdas[i + 1]
|
| 1503 |
-
alpha_s = sigmas[i] / er_lambda_s
|
| 1504 |
-
alpha_t = sigmas[i + 1] / er_lambda_t
|
| 1505 |
-
r_alpha = alpha_t / alpha_s
|
| 1506 |
-
r = noise_scaler(er_lambda_t) / noise_scaler(er_lambda_s)
|
| 1507 |
-
|
| 1508 |
-
# Stage 1 Euler
|
| 1509 |
-
x = r_alpha * r * x + alpha_t * (1 - r) * denoised
|
| 1510 |
-
|
| 1511 |
-
if stage_used >= 2:
|
| 1512 |
-
dt = er_lambda_t - er_lambda_s
|
| 1513 |
-
lambda_step_size = -dt / num_integration_points
|
| 1514 |
-
lambda_pos = er_lambda_t + point_indice * lambda_step_size
|
| 1515 |
-
scaled_pos = noise_scaler(lambda_pos)
|
| 1516 |
-
|
| 1517 |
-
# Stage 2
|
| 1518 |
-
s = torch.sum(1 / scaled_pos) * lambda_step_size
|
| 1519 |
-
denoised_d = (denoised - old_denoised) / (er_lambda_s - er_lambdas[i - 1])
|
| 1520 |
-
x = x + alpha_t * (dt + s * noise_scaler(er_lambda_t)) * denoised_d
|
| 1521 |
-
|
| 1522 |
-
if stage_used >= 3:
|
| 1523 |
-
# Stage 3
|
| 1524 |
-
s_u = torch.sum((lambda_pos - er_lambda_s) / scaled_pos) * lambda_step_size
|
| 1525 |
-
denoised_u = (denoised_d - old_denoised_d) / ((er_lambda_s - er_lambdas[i - 2]) / 2)
|
| 1526 |
-
x = x + alpha_t * ((dt ** 2) / 2 + s_u * noise_scaler(er_lambda_t)) * denoised_u
|
| 1527 |
-
old_denoised_d = denoised_d
|
| 1528 |
-
|
| 1529 |
-
if s_noise > 0:
|
| 1530 |
-
x = x + alpha_t * noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * (er_lambda_t ** 2 - er_lambda_s ** 2 * r ** 2).sqrt().nan_to_num(nan=0.0)
|
| 1531 |
-
old_denoised = denoised
|
| 1532 |
-
return x
|
| 1533 |
-
|
| 1534 |
-
|
| 1535 |
-
@torch.no_grad()
|
| 1536 |
-
def sample_seeds_2(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=0.5):
|
| 1537 |
-
"""SEEDS-2 - Stochastic Explicit Exponential Derivative-free Solvers (VP Data Prediction) stage 2.
|
| 1538 |
-
arXiv: https://arxiv.org/abs/2305.14267
|
| 1539 |
-
"""
|
| 1540 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1541 |
-
seed = extra_args.get("seed", None)
|
| 1542 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 1543 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1544 |
-
|
| 1545 |
-
inject_noise = eta > 0 and s_noise > 0
|
| 1546 |
-
|
| 1547 |
-
model_sampling = model.inner_model.model_patcher.get_model_object('model_sampling')
|
| 1548 |
-
sigma_fn = partial(half_log_snr_to_sigma, model_sampling=model_sampling)
|
| 1549 |
-
lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
|
| 1550 |
-
sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
|
| 1551 |
-
|
| 1552 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1553 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1554 |
-
if callback is not None:
|
| 1555 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1556 |
-
if sigmas[i + 1] == 0:
|
| 1557 |
-
x = denoised
|
| 1558 |
-
else:
|
| 1559 |
-
lambda_s, lambda_t = lambda_fn(sigmas[i]), lambda_fn(sigmas[i + 1])
|
| 1560 |
-
h = lambda_t - lambda_s
|
| 1561 |
-
h_eta = h * (eta + 1)
|
| 1562 |
-
lambda_s_1 = lambda_s + r * h
|
| 1563 |
-
fac = 1 / (2 * r)
|
| 1564 |
-
sigma_s_1 = sigma_fn(lambda_s_1)
|
| 1565 |
-
|
| 1566 |
-
# alpha_t = sigma_t * exp(log(alpha_t / sigma_t)) = sigma_t * exp(lambda_t)
|
| 1567 |
-
alpha_s_1 = sigma_s_1 * lambda_s_1.exp()
|
| 1568 |
-
alpha_t = sigmas[i + 1] * lambda_t.exp()
|
| 1569 |
-
|
| 1570 |
-
coeff_1, coeff_2 = (-r * h_eta).expm1(), (-h_eta).expm1()
|
| 1571 |
-
if inject_noise:
|
| 1572 |
-
# 0 < r < 1
|
| 1573 |
-
noise_coeff_1 = (-2 * r * h * eta).expm1().neg().sqrt()
|
| 1574 |
-
noise_coeff_2 = (-r * h * eta).exp() * (-2 * (1 - r) * h * eta).expm1().neg().sqrt()
|
| 1575 |
-
noise_1, noise_2 = noise_sampler(sigmas[i], sigma_s_1), noise_sampler(sigma_s_1, sigmas[i + 1])
|
| 1576 |
-
|
| 1577 |
-
# Step 1
|
| 1578 |
-
x_2 = sigma_s_1 / sigmas[i] * (-r * h * eta).exp() * x - alpha_s_1 * coeff_1 * denoised
|
| 1579 |
-
if inject_noise:
|
| 1580 |
-
x_2 = x_2 + sigma_s_1 * (noise_coeff_1 * noise_1) * s_noise
|
| 1581 |
-
denoised_2 = model(x_2, sigma_s_1 * s_in, **extra_args)
|
| 1582 |
-
|
| 1583 |
-
# Step 2
|
| 1584 |
-
denoised_d = (1 - fac) * denoised + fac * denoised_2
|
| 1585 |
-
x = sigmas[i + 1] / sigmas[i] * (-h * eta).exp() * x - alpha_t * coeff_2 * denoised_d
|
| 1586 |
-
if inject_noise:
|
| 1587 |
-
x = x + sigmas[i + 1] * (noise_coeff_2 * noise_1 + noise_coeff_1 * noise_2) * s_noise
|
| 1588 |
-
return x
|
| 1589 |
-
|
| 1590 |
-
|
| 1591 |
-
@torch.no_grad()
|
| 1592 |
-
def sample_seeds_3(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r_1=1./3, r_2=2./3):
|
| 1593 |
-
"""SEEDS-3 - Stochastic Explicit Exponential Derivative-free Solvers (VP Data Prediction) stage 3.
|
| 1594 |
-
arXiv: https://arxiv.org/abs/2305.14267
|
| 1595 |
-
"""
|
| 1596 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1597 |
-
seed = extra_args.get("seed", None)
|
| 1598 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 1599 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1600 |
-
|
| 1601 |
-
inject_noise = eta > 0 and s_noise > 0
|
| 1602 |
-
|
| 1603 |
-
model_sampling = model.inner_model.model_patcher.get_model_object('model_sampling')
|
| 1604 |
-
sigma_fn = partial(half_log_snr_to_sigma, model_sampling=model_sampling)
|
| 1605 |
-
lambda_fn = partial(sigma_to_half_log_snr, model_sampling=model_sampling)
|
| 1606 |
-
sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
|
| 1607 |
-
|
| 1608 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1609 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1610 |
-
if callback is not None:
|
| 1611 |
-
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 1612 |
-
if sigmas[i + 1] == 0:
|
| 1613 |
-
x = denoised
|
| 1614 |
-
else:
|
| 1615 |
-
lambda_s, lambda_t = lambda_fn(sigmas[i]), lambda_fn(sigmas[i + 1])
|
| 1616 |
-
h = lambda_t - lambda_s
|
| 1617 |
-
h_eta = h * (eta + 1)
|
| 1618 |
-
lambda_s_1 = lambda_s + r_1 * h
|
| 1619 |
-
lambda_s_2 = lambda_s + r_2 * h
|
| 1620 |
-
sigma_s_1, sigma_s_2 = sigma_fn(lambda_s_1), sigma_fn(lambda_s_2)
|
| 1621 |
-
|
| 1622 |
-
# alpha_t = sigma_t * exp(log(alpha_t / sigma_t)) = sigma_t * exp(lambda_t)
|
| 1623 |
-
alpha_s_1 = sigma_s_1 * lambda_s_1.exp()
|
| 1624 |
-
alpha_s_2 = sigma_s_2 * lambda_s_2.exp()
|
| 1625 |
-
alpha_t = sigmas[i + 1] * lambda_t.exp()
|
| 1626 |
-
|
| 1627 |
-
coeff_1, coeff_2, coeff_3 = (-r_1 * h_eta).expm1(), (-r_2 * h_eta).expm1(), (-h_eta).expm1()
|
| 1628 |
-
if inject_noise:
|
| 1629 |
-
# 0 < r_1 < r_2 < 1
|
| 1630 |
-
noise_coeff_1 = (-2 * r_1 * h * eta).expm1().neg().sqrt()
|
| 1631 |
-
noise_coeff_2 = (-r_1 * h * eta).exp() * (-2 * (r_2 - r_1) * h * eta).expm1().neg().sqrt()
|
| 1632 |
-
noise_coeff_3 = (-r_2 * h * eta).exp() * (-2 * (1 - r_2) * h * eta).expm1().neg().sqrt()
|
| 1633 |
-
noise_1, noise_2, noise_3 = noise_sampler(sigmas[i], sigma_s_1), noise_sampler(sigma_s_1, sigma_s_2), noise_sampler(sigma_s_2, sigmas[i + 1])
|
| 1634 |
-
|
| 1635 |
-
# Step 1
|
| 1636 |
-
x_2 = sigma_s_1 / sigmas[i] * (-r_1 * h * eta).exp() * x - alpha_s_1 * coeff_1 * denoised
|
| 1637 |
-
if inject_noise:
|
| 1638 |
-
x_2 = x_2 + sigma_s_1 * (noise_coeff_1 * noise_1) * s_noise
|
| 1639 |
-
denoised_2 = model(x_2, sigma_s_1 * s_in, **extra_args)
|
| 1640 |
-
|
| 1641 |
-
# Step 2
|
| 1642 |
-
x_3 = sigma_s_2 / sigmas[i] * (-r_2 * h * eta).exp() * x - alpha_s_2 * coeff_2 * denoised + (r_2 / r_1) * alpha_s_2 * (coeff_2 / (r_2 * h_eta) + 1) * (denoised_2 - denoised)
|
| 1643 |
-
if inject_noise:
|
| 1644 |
-
x_3 = x_3 + sigma_s_2 * (noise_coeff_2 * noise_1 + noise_coeff_1 * noise_2) * s_noise
|
| 1645 |
-
denoised_3 = model(x_3, sigma_s_2 * s_in, **extra_args)
|
| 1646 |
-
|
| 1647 |
-
# Step 3
|
| 1648 |
-
x = sigmas[i + 1] / sigmas[i] * (-h * eta).exp() * x - alpha_t * coeff_3 * denoised + (1. / r_2) * alpha_t * (coeff_3 / h_eta + 1) * (denoised_3 - denoised)
|
| 1649 |
-
if inject_noise:
|
| 1650 |
-
x = x + sigmas[i + 1] * (noise_coeff_3 * noise_1 + noise_coeff_2 * noise_2 + noise_coeff_1 * noise_3) * s_noise
|
| 1651 |
-
return x
|
| 1652 |
-
|
| 1653 |
-
|
| 1654 |
-
@torch.no_grad()
|
| 1655 |
-
def sample_sa_solver(model, x, sigmas, extra_args=None, callback=None, disable=False, tau_func=None, s_noise=1.0, noise_sampler=None, predictor_order=3, corrector_order=4, use_pece=False, simple_order_2=False):
|
| 1656 |
-
"""Stochastic Adams Solver with predictor-corrector method (NeurIPS 2023)."""
|
| 1657 |
-
if len(sigmas) <= 1:
|
| 1658 |
-
return x
|
| 1659 |
-
extra_args = {} if extra_args is None else extra_args
|
| 1660 |
-
seed = extra_args.get("seed", None)
|
| 1661 |
-
noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler
|
| 1662 |
-
s_in = x.new_ones([x.shape[0]])
|
| 1663 |
-
|
| 1664 |
-
model_sampling = model.inner_model.model_patcher.get_model_object("model_sampling")
|
| 1665 |
-
sigmas = offset_first_sigma_for_snr(sigmas, model_sampling)
|
| 1666 |
-
lambdas = sigma_to_half_log_snr(sigmas, model_sampling=model_sampling)
|
| 1667 |
-
|
| 1668 |
-
if tau_func is None:
|
| 1669 |
-
# Use default interval for stochastic sampling
|
| 1670 |
-
start_sigma = model_sampling.percent_to_sigma(0.2)
|
| 1671 |
-
end_sigma = model_sampling.percent_to_sigma(0.8)
|
| 1672 |
-
tau_func = sa_solver.get_tau_interval_func(start_sigma, end_sigma, eta=1.0)
|
| 1673 |
-
|
| 1674 |
-
max_used_order = max(predictor_order, corrector_order)
|
| 1675 |
-
x_pred = x # x: current state, x_pred: predicted next state
|
| 1676 |
-
|
| 1677 |
-
h = 0.0
|
| 1678 |
-
tau_t = 0.0
|
| 1679 |
-
noise = 0.0
|
| 1680 |
-
pred_list = []
|
| 1681 |
-
|
| 1682 |
-
# Lower order near the end to improve stability
|
| 1683 |
-
lower_order_to_end = sigmas[-1].item() == 0
|
| 1684 |
-
|
| 1685 |
-
for i in trange(len(sigmas) - 1, disable=disable):
|
| 1686 |
-
# Evaluation
|
| 1687 |
-
denoised = model(x_pred, sigmas[i] * s_in, **extra_args)
|
| 1688 |
-
if callback is not None:
|
| 1689 |
-
callback({"x": x_pred, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised})
|
| 1690 |
-
pred_list.append(denoised)
|
| 1691 |
-
pred_list = pred_list[-max_used_order:]
|
| 1692 |
-
|
| 1693 |
-
predictor_order_used = min(predictor_order, len(pred_list))
|
| 1694 |
-
if i == 0 or (sigmas[i + 1] == 0 and not use_pece):
|
| 1695 |
-
corrector_order_used = 0
|
| 1696 |
-
else:
|
| 1697 |
-
corrector_order_used = min(corrector_order, len(pred_list))
|
| 1698 |
-
|
| 1699 |
-
if lower_order_to_end:
|
| 1700 |
-
predictor_order_used = min(predictor_order_used, len(sigmas) - 2 - i)
|
| 1701 |
-
corrector_order_used = min(corrector_order_used, len(sigmas) - 1 - i)
|
| 1702 |
-
|
| 1703 |
-
# Corrector
|
| 1704 |
-
if corrector_order_used == 0:
|
| 1705 |
-
# Update by the predicted state
|
| 1706 |
-
x = x_pred
|
| 1707 |
-
else:
|
| 1708 |
-
curr_lambdas = lambdas[i - corrector_order_used + 1:i + 1]
|
| 1709 |
-
b_coeffs = sa_solver.compute_stochastic_adams_b_coeffs(
|
| 1710 |
-
sigmas[i],
|
| 1711 |
-
curr_lambdas,
|
| 1712 |
-
lambdas[i - 1],
|
| 1713 |
-
lambdas[i],
|
| 1714 |
-
tau_t,
|
| 1715 |
-
simple_order_2,
|
| 1716 |
-
is_corrector_step=True,
|
| 1717 |
-
)
|
| 1718 |
-
pred_mat = torch.stack(pred_list[-corrector_order_used:], dim=1) # (B, K, ...)
|
| 1719 |
-
corr_res = torch.tensordot(pred_mat, b_coeffs, dims=([1], [0])) # (B, ...)
|
| 1720 |
-
x = sigmas[i] / sigmas[i - 1] * (-(tau_t ** 2) * h).exp() * x + corr_res
|
| 1721 |
-
|
| 1722 |
-
if tau_t > 0 and s_noise > 0:
|
| 1723 |
-
# The noise from the previous predictor step
|
| 1724 |
-
x = x + noise
|
| 1725 |
-
|
| 1726 |
-
if use_pece:
|
| 1727 |
-
# Evaluate the corrected state
|
| 1728 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 1729 |
-
pred_list[-1] = denoised
|
| 1730 |
-
|
| 1731 |
-
# Predictor
|
| 1732 |
-
if sigmas[i + 1] == 0:
|
| 1733 |
-
# Denoising step
|
| 1734 |
-
x = denoised
|
| 1735 |
-
else:
|
| 1736 |
-
tau_t = tau_func(sigmas[i + 1])
|
| 1737 |
-
curr_lambdas = lambdas[i - predictor_order_used + 1:i + 1]
|
| 1738 |
-
b_coeffs = sa_solver.compute_stochastic_adams_b_coeffs(
|
| 1739 |
-
sigmas[i + 1],
|
| 1740 |
-
curr_lambdas,
|
| 1741 |
-
lambdas[i],
|
| 1742 |
-
lambdas[i + 1],
|
| 1743 |
-
tau_t,
|
| 1744 |
-
simple_order_2,
|
| 1745 |
-
is_corrector_step=False,
|
| 1746 |
-
)
|
| 1747 |
-
pred_mat = torch.stack(pred_list[-predictor_order_used:], dim=1) # (B, K, ...)
|
| 1748 |
-
pred_res = torch.tensordot(pred_mat, b_coeffs, dims=([1], [0])) # (B, ...)
|
| 1749 |
-
h = lambdas[i + 1] - lambdas[i]
|
| 1750 |
-
x_pred = sigmas[i + 1] / sigmas[i] * (-(tau_t ** 2) * h).exp() * x + pred_res
|
| 1751 |
-
|
| 1752 |
-
if tau_t > 0 and s_noise > 0:
|
| 1753 |
-
noise = noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * tau_t ** 2 * h).expm1().neg().sqrt() * s_noise
|
| 1754 |
-
x_pred = x_pred + noise
|
| 1755 |
-
return x
|
| 1756 |
-
|
| 1757 |
-
|
| 1758 |
-
@torch.no_grad()
|
| 1759 |
-
def sample_sa_solver_pece(model, x, sigmas, extra_args=None, callback=None, disable=False, tau_func=None, s_noise=1.0, noise_sampler=None, predictor_order=3, corrector_order=4, simple_order_2=False):
|
| 1760 |
-
"""Stochastic Adams Solver with PECE (Predict–Evaluate–Correct–Evaluate) mode (NeurIPS 2023)."""
|
| 1761 |
-
return sample_sa_solver(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, tau_func=tau_func, s_noise=s_noise, noise_sampler=noise_sampler, predictor_order=predictor_order, corrector_order=corrector_order, use_pece=True, simple_order_2=simple_order_2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/k_diffusion/utils.py
DELETED
|
@@ -1,313 +0,0 @@
|
|
| 1 |
-
from contextlib import contextmanager
|
| 2 |
-
import hashlib
|
| 3 |
-
import math
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import shutil
|
| 6 |
-
import urllib
|
| 7 |
-
import warnings
|
| 8 |
-
|
| 9 |
-
from PIL import Image
|
| 10 |
-
import torch
|
| 11 |
-
from torch import nn, optim
|
| 12 |
-
from torch.utils import data
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def hf_datasets_augs_helper(examples, transform, image_key, mode='RGB'):
|
| 16 |
-
"""Apply passed in transforms for HuggingFace Datasets."""
|
| 17 |
-
images = [transform(image.convert(mode)) for image in examples[image_key]]
|
| 18 |
-
return {image_key: images}
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def append_dims(x, target_dims):
|
| 22 |
-
"""Appends dimensions to the end of a tensor until it has target_dims dimensions."""
|
| 23 |
-
dims_to_append = target_dims - x.ndim
|
| 24 |
-
if dims_to_append < 0:
|
| 25 |
-
raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')
|
| 26 |
-
expanded = x[(...,) + (None,) * dims_to_append]
|
| 27 |
-
# MPS will get inf values if it tries to index into the new axes, but detaching fixes this.
|
| 28 |
-
# https://github.com/pytorch/pytorch/issues/84364
|
| 29 |
-
return expanded.detach().clone() if expanded.device.type == 'mps' else expanded
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
def n_params(module):
|
| 33 |
-
"""Returns the number of trainable parameters in a module."""
|
| 34 |
-
return sum(p.numel() for p in module.parameters())
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def download_file(path, url, digest=None):
|
| 38 |
-
"""Downloads a file if it does not exist, optionally checking its SHA-256 hash."""
|
| 39 |
-
path = Path(path)
|
| 40 |
-
path.parent.mkdir(parents=True, exist_ok=True)
|
| 41 |
-
if not path.exists():
|
| 42 |
-
with urllib.request.urlopen(url) as response, open(path, 'wb') as f:
|
| 43 |
-
shutil.copyfileobj(response, f)
|
| 44 |
-
if digest is not None:
|
| 45 |
-
file_digest = hashlib.sha256(open(path, 'rb').read()).hexdigest()
|
| 46 |
-
if digest != file_digest:
|
| 47 |
-
raise OSError(f'hash of {path} (url: {url}) failed to validate')
|
| 48 |
-
return path
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
@contextmanager
|
| 52 |
-
def train_mode(model, mode=True):
|
| 53 |
-
"""A context manager that places a model into training mode and restores
|
| 54 |
-
the previous mode on exit."""
|
| 55 |
-
modes = [module.training for module in model.modules()]
|
| 56 |
-
try:
|
| 57 |
-
yield model.train(mode)
|
| 58 |
-
finally:
|
| 59 |
-
for i, module in enumerate(model.modules()):
|
| 60 |
-
module.training = modes[i]
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def eval_mode(model):
|
| 64 |
-
"""A context manager that places a model into evaluation mode and restores
|
| 65 |
-
the previous mode on exit."""
|
| 66 |
-
return train_mode(model, False)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
@torch.no_grad()
|
| 70 |
-
def ema_update(model, averaged_model, decay):
|
| 71 |
-
"""Incorporates updated model parameters into an exponential moving averaged
|
| 72 |
-
version of a model. It should be called after each optimizer step."""
|
| 73 |
-
model_params = dict(model.named_parameters())
|
| 74 |
-
averaged_params = dict(averaged_model.named_parameters())
|
| 75 |
-
assert model_params.keys() == averaged_params.keys()
|
| 76 |
-
|
| 77 |
-
for name, param in model_params.items():
|
| 78 |
-
averaged_params[name].mul_(decay).add_(param, alpha=1 - decay)
|
| 79 |
-
|
| 80 |
-
model_buffers = dict(model.named_buffers())
|
| 81 |
-
averaged_buffers = dict(averaged_model.named_buffers())
|
| 82 |
-
assert model_buffers.keys() == averaged_buffers.keys()
|
| 83 |
-
|
| 84 |
-
for name, buf in model_buffers.items():
|
| 85 |
-
averaged_buffers[name].copy_(buf)
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
class EMAWarmup:
|
| 89 |
-
"""Implements an EMA warmup using an inverse decay schedule.
|
| 90 |
-
If inv_gamma=1 and power=1, implements a simple average. inv_gamma=1, power=2/3 are
|
| 91 |
-
good values for models you plan to train for a million or more steps (reaches decay
|
| 92 |
-
factor 0.999 at 31.6K steps, 0.9999 at 1M steps), inv_gamma=1, power=3/4 for models
|
| 93 |
-
you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 at
|
| 94 |
-
215.4k steps).
|
| 95 |
-
Args:
|
| 96 |
-
inv_gamma (float): Inverse multiplicative factor of EMA warmup. Default: 1.
|
| 97 |
-
power (float): Exponential factor of EMA warmup. Default: 1.
|
| 98 |
-
min_value (float): The minimum EMA decay rate. Default: 0.
|
| 99 |
-
max_value (float): The maximum EMA decay rate. Default: 1.
|
| 100 |
-
start_at (int): The epoch to start averaging at. Default: 0.
|
| 101 |
-
last_epoch (int): The index of last epoch. Default: 0.
|
| 102 |
-
"""
|
| 103 |
-
|
| 104 |
-
def __init__(self, inv_gamma=1., power=1., min_value=0., max_value=1., start_at=0,
|
| 105 |
-
last_epoch=0):
|
| 106 |
-
self.inv_gamma = inv_gamma
|
| 107 |
-
self.power = power
|
| 108 |
-
self.min_value = min_value
|
| 109 |
-
self.max_value = max_value
|
| 110 |
-
self.start_at = start_at
|
| 111 |
-
self.last_epoch = last_epoch
|
| 112 |
-
|
| 113 |
-
def state_dict(self):
|
| 114 |
-
"""Returns the state of the class as a :class:`dict`."""
|
| 115 |
-
return dict(self.__dict__.items())
|
| 116 |
-
|
| 117 |
-
def load_state_dict(self, state_dict):
|
| 118 |
-
"""Loads the class's state.
|
| 119 |
-
Args:
|
| 120 |
-
state_dict (dict): scaler state. Should be an object returned
|
| 121 |
-
from a call to :meth:`state_dict`.
|
| 122 |
-
"""
|
| 123 |
-
self.__dict__.update(state_dict)
|
| 124 |
-
|
| 125 |
-
def get_value(self):
|
| 126 |
-
"""Gets the current EMA decay rate."""
|
| 127 |
-
epoch = max(0, self.last_epoch - self.start_at)
|
| 128 |
-
value = 1 - (1 + epoch / self.inv_gamma) ** -self.power
|
| 129 |
-
return 0. if epoch < 0 else min(self.max_value, max(self.min_value, value))
|
| 130 |
-
|
| 131 |
-
def step(self):
|
| 132 |
-
"""Updates the step count."""
|
| 133 |
-
self.last_epoch += 1
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class InverseLR(optim.lr_scheduler._LRScheduler):
|
| 137 |
-
"""Implements an inverse decay learning rate schedule with an optional exponential
|
| 138 |
-
warmup. When last_epoch=-1, sets initial lr as lr.
|
| 139 |
-
inv_gamma is the number of steps/epochs required for the learning rate to decay to
|
| 140 |
-
(1 / 2)**power of its original value.
|
| 141 |
-
Args:
|
| 142 |
-
optimizer (Optimizer): Wrapped optimizer.
|
| 143 |
-
inv_gamma (float): Inverse multiplicative factor of learning rate decay. Default: 1.
|
| 144 |
-
power (float): Exponential factor of learning rate decay. Default: 1.
|
| 145 |
-
warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable)
|
| 146 |
-
Default: 0.
|
| 147 |
-
min_lr (float): The minimum learning rate. Default: 0.
|
| 148 |
-
last_epoch (int): The index of last epoch. Default: -1.
|
| 149 |
-
verbose (bool): If ``True``, prints a message to stdout for
|
| 150 |
-
each update. Default: ``False``.
|
| 151 |
-
"""
|
| 152 |
-
|
| 153 |
-
def __init__(self, optimizer, inv_gamma=1., power=1., warmup=0., min_lr=0.,
|
| 154 |
-
last_epoch=-1, verbose=False):
|
| 155 |
-
self.inv_gamma = inv_gamma
|
| 156 |
-
self.power = power
|
| 157 |
-
if not 0. <= warmup < 1:
|
| 158 |
-
raise ValueError('Invalid value for warmup')
|
| 159 |
-
self.warmup = warmup
|
| 160 |
-
self.min_lr = min_lr
|
| 161 |
-
super().__init__(optimizer, last_epoch, verbose)
|
| 162 |
-
|
| 163 |
-
def get_lr(self):
|
| 164 |
-
if not self._get_lr_called_within_step:
|
| 165 |
-
warnings.warn("To get the last learning rate computed by the scheduler, "
|
| 166 |
-
"please use `get_last_lr()`.")
|
| 167 |
-
|
| 168 |
-
return self._get_closed_form_lr()
|
| 169 |
-
|
| 170 |
-
def _get_closed_form_lr(self):
|
| 171 |
-
warmup = 1 - self.warmup ** (self.last_epoch + 1)
|
| 172 |
-
lr_mult = (1 + self.last_epoch / self.inv_gamma) ** -self.power
|
| 173 |
-
return [warmup * max(self.min_lr, base_lr * lr_mult)
|
| 174 |
-
for base_lr in self.base_lrs]
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
class ExponentialLR(optim.lr_scheduler._LRScheduler):
|
| 178 |
-
"""Implements an exponential learning rate schedule with an optional exponential
|
| 179 |
-
warmup. When last_epoch=-1, sets initial lr as lr. Decays the learning rate
|
| 180 |
-
continuously by decay (default 0.5) every num_steps steps.
|
| 181 |
-
Args:
|
| 182 |
-
optimizer (Optimizer): Wrapped optimizer.
|
| 183 |
-
num_steps (float): The number of steps to decay the learning rate by decay in.
|
| 184 |
-
decay (float): The factor by which to decay the learning rate every num_steps
|
| 185 |
-
steps. Default: 0.5.
|
| 186 |
-
warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable)
|
| 187 |
-
Default: 0.
|
| 188 |
-
min_lr (float): The minimum learning rate. Default: 0.
|
| 189 |
-
last_epoch (int): The index of last epoch. Default: -1.
|
| 190 |
-
verbose (bool): If ``True``, prints a message to stdout for
|
| 191 |
-
each update. Default: ``False``.
|
| 192 |
-
"""
|
| 193 |
-
|
| 194 |
-
def __init__(self, optimizer, num_steps, decay=0.5, warmup=0., min_lr=0.,
|
| 195 |
-
last_epoch=-1, verbose=False):
|
| 196 |
-
self.num_steps = num_steps
|
| 197 |
-
self.decay = decay
|
| 198 |
-
if not 0. <= warmup < 1:
|
| 199 |
-
raise ValueError('Invalid value for warmup')
|
| 200 |
-
self.warmup = warmup
|
| 201 |
-
self.min_lr = min_lr
|
| 202 |
-
super().__init__(optimizer, last_epoch, verbose)
|
| 203 |
-
|
| 204 |
-
def get_lr(self):
|
| 205 |
-
if not self._get_lr_called_within_step:
|
| 206 |
-
warnings.warn("To get the last learning rate computed by the scheduler, "
|
| 207 |
-
"please use `get_last_lr()`.")
|
| 208 |
-
|
| 209 |
-
return self._get_closed_form_lr()
|
| 210 |
-
|
| 211 |
-
def _get_closed_form_lr(self):
|
| 212 |
-
warmup = 1 - self.warmup ** (self.last_epoch + 1)
|
| 213 |
-
lr_mult = (self.decay ** (1 / self.num_steps)) ** self.last_epoch
|
| 214 |
-
return [warmup * max(self.min_lr, base_lr * lr_mult)
|
| 215 |
-
for base_lr in self.base_lrs]
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
def rand_log_normal(shape, loc=0., scale=1., device='cpu', dtype=torch.float32):
|
| 219 |
-
"""Draws samples from an lognormal distribution."""
|
| 220 |
-
return (torch.randn(shape, device=device, dtype=dtype) * scale + loc).exp()
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
def rand_log_logistic(shape, loc=0., scale=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32):
|
| 224 |
-
"""Draws samples from an optionally truncated log-logistic distribution."""
|
| 225 |
-
min_value = torch.as_tensor(min_value, device=device, dtype=torch.float64)
|
| 226 |
-
max_value = torch.as_tensor(max_value, device=device, dtype=torch.float64)
|
| 227 |
-
min_cdf = min_value.log().sub(loc).div(scale).sigmoid()
|
| 228 |
-
max_cdf = max_value.log().sub(loc).div(scale).sigmoid()
|
| 229 |
-
u = torch.rand(shape, device=device, dtype=torch.float64) * (max_cdf - min_cdf) + min_cdf
|
| 230 |
-
return u.logit().mul(scale).add(loc).exp().to(dtype)
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
def rand_log_uniform(shape, min_value, max_value, device='cpu', dtype=torch.float32):
|
| 234 |
-
"""Draws samples from an log-uniform distribution."""
|
| 235 |
-
min_value = math.log(min_value)
|
| 236 |
-
max_value = math.log(max_value)
|
| 237 |
-
return (torch.rand(shape, device=device, dtype=dtype) * (max_value - min_value) + min_value).exp()
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
def rand_v_diffusion(shape, sigma_data=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32):
|
| 241 |
-
"""Draws samples from a truncated v-diffusion training timestep distribution."""
|
| 242 |
-
min_cdf = math.atan(min_value / sigma_data) * 2 / math.pi
|
| 243 |
-
max_cdf = math.atan(max_value / sigma_data) * 2 / math.pi
|
| 244 |
-
u = torch.rand(shape, device=device, dtype=dtype) * (max_cdf - min_cdf) + min_cdf
|
| 245 |
-
return torch.tan(u * math.pi / 2) * sigma_data
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
def rand_split_log_normal(shape, loc, scale_1, scale_2, device='cpu', dtype=torch.float32):
|
| 249 |
-
"""Draws samples from a split lognormal distribution."""
|
| 250 |
-
n = torch.randn(shape, device=device, dtype=dtype).abs()
|
| 251 |
-
u = torch.rand(shape, device=device, dtype=dtype)
|
| 252 |
-
n_left = n * -scale_1 + loc
|
| 253 |
-
n_right = n * scale_2 + loc
|
| 254 |
-
ratio = scale_1 / (scale_1 + scale_2)
|
| 255 |
-
return torch.where(u < ratio, n_left, n_right).exp()
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
class FolderOfImages(data.Dataset):
|
| 259 |
-
"""Recursively finds all images in a directory. It does not support
|
| 260 |
-
classes/targets."""
|
| 261 |
-
|
| 262 |
-
IMG_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'}
|
| 263 |
-
|
| 264 |
-
def __init__(self, root, transform=None):
|
| 265 |
-
super().__init__()
|
| 266 |
-
self.root = Path(root)
|
| 267 |
-
self.transform = nn.Identity() if transform is None else transform
|
| 268 |
-
self.paths = sorted(path for path in self.root.rglob('*') if path.suffix.lower() in self.IMG_EXTENSIONS)
|
| 269 |
-
|
| 270 |
-
def __repr__(self):
|
| 271 |
-
return f'FolderOfImages(root="{self.root}", len: {len(self)})'
|
| 272 |
-
|
| 273 |
-
def __len__(self):
|
| 274 |
-
return len(self.paths)
|
| 275 |
-
|
| 276 |
-
def __getitem__(self, key):
|
| 277 |
-
path = self.paths[key]
|
| 278 |
-
with open(path, 'rb') as f:
|
| 279 |
-
image = Image.open(f).convert('RGB')
|
| 280 |
-
image = self.transform(image)
|
| 281 |
-
return image,
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
class CSVLogger:
|
| 285 |
-
def __init__(self, filename, columns):
|
| 286 |
-
self.filename = Path(filename)
|
| 287 |
-
self.columns = columns
|
| 288 |
-
if self.filename.exists():
|
| 289 |
-
self.file = open(self.filename, 'a')
|
| 290 |
-
else:
|
| 291 |
-
self.file = open(self.filename, 'w')
|
| 292 |
-
self.write(*self.columns)
|
| 293 |
-
|
| 294 |
-
def write(self, *args):
|
| 295 |
-
print(*args, sep=',', file=self.file, flush=True)
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
@contextmanager
|
| 299 |
-
def tf32_mode(cudnn=None, matmul=None):
|
| 300 |
-
"""A context manager that sets whether TF32 is allowed on cuDNN or matmul."""
|
| 301 |
-
cudnn_old = torch.backends.cudnn.allow_tf32
|
| 302 |
-
matmul_old = torch.backends.cuda.matmul.allow_tf32
|
| 303 |
-
try:
|
| 304 |
-
if cudnn is not None:
|
| 305 |
-
torch.backends.cudnn.allow_tf32 = cudnn
|
| 306 |
-
if matmul is not None:
|
| 307 |
-
torch.backends.cuda.matmul.allow_tf32 = matmul
|
| 308 |
-
yield
|
| 309 |
-
finally:
|
| 310 |
-
if cudnn is not None:
|
| 311 |
-
torch.backends.cudnn.allow_tf32 = cudnn_old
|
| 312 |
-
if matmul is not None:
|
| 313 |
-
torch.backends.cuda.matmul.allow_tf32 = matmul_old
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/latent_formats.py
DELETED
|
@@ -1,472 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
|
| 3 |
-
class LatentFormat:
|
| 4 |
-
scale_factor = 1.0
|
| 5 |
-
latent_channels = 4
|
| 6 |
-
latent_dimensions = 2
|
| 7 |
-
latent_rgb_factors = None
|
| 8 |
-
latent_rgb_factors_bias = None
|
| 9 |
-
taesd_decoder_name = None
|
| 10 |
-
|
| 11 |
-
def process_in(self, latent):
|
| 12 |
-
return latent * self.scale_factor
|
| 13 |
-
|
| 14 |
-
def process_out(self, latent):
|
| 15 |
-
return latent / self.scale_factor
|
| 16 |
-
|
| 17 |
-
class SD15(LatentFormat):
|
| 18 |
-
def __init__(self, scale_factor=0.18215):
|
| 19 |
-
self.scale_factor = scale_factor
|
| 20 |
-
self.latent_rgb_factors = [
|
| 21 |
-
# R G B
|
| 22 |
-
[ 0.3512, 0.2297, 0.3227],
|
| 23 |
-
[ 0.3250, 0.4974, 0.2350],
|
| 24 |
-
[-0.2829, 0.1762, 0.2721],
|
| 25 |
-
[-0.2120, -0.2616, -0.7177]
|
| 26 |
-
]
|
| 27 |
-
self.taesd_decoder_name = "taesd_decoder"
|
| 28 |
-
|
| 29 |
-
class SDXL(LatentFormat):
|
| 30 |
-
scale_factor = 0.13025
|
| 31 |
-
|
| 32 |
-
def __init__(self):
|
| 33 |
-
self.latent_rgb_factors = [
|
| 34 |
-
# R G B
|
| 35 |
-
[ 0.3651, 0.4232, 0.4341],
|
| 36 |
-
[-0.2533, -0.0042, 0.1068],
|
| 37 |
-
[ 0.1076, 0.1111, -0.0362],
|
| 38 |
-
[-0.3165, -0.2492, -0.2188]
|
| 39 |
-
]
|
| 40 |
-
self.latent_rgb_factors_bias = [ 0.1084, -0.0175, -0.0011]
|
| 41 |
-
|
| 42 |
-
self.taesd_decoder_name = "taesdxl_decoder"
|
| 43 |
-
|
| 44 |
-
class SDXL_Playground_2_5(LatentFormat):
|
| 45 |
-
def __init__(self):
|
| 46 |
-
self.scale_factor = 0.5
|
| 47 |
-
self.latents_mean = torch.tensor([-1.6574, 1.886, -1.383, 2.5155]).view(1, 4, 1, 1)
|
| 48 |
-
self.latents_std = torch.tensor([8.4927, 5.9022, 6.5498, 5.2299]).view(1, 4, 1, 1)
|
| 49 |
-
|
| 50 |
-
self.latent_rgb_factors = [
|
| 51 |
-
# R G B
|
| 52 |
-
[ 0.3920, 0.4054, 0.4549],
|
| 53 |
-
[-0.2634, -0.0196, 0.0653],
|
| 54 |
-
[ 0.0568, 0.1687, -0.0755],
|
| 55 |
-
[-0.3112, -0.2359, -0.2076]
|
| 56 |
-
]
|
| 57 |
-
self.taesd_decoder_name = "taesdxl_decoder"
|
| 58 |
-
|
| 59 |
-
def process_in(self, latent):
|
| 60 |
-
latents_mean = self.latents_mean.to(latent.device, latent.dtype)
|
| 61 |
-
latents_std = self.latents_std.to(latent.device, latent.dtype)
|
| 62 |
-
return (latent - latents_mean) * self.scale_factor / latents_std
|
| 63 |
-
|
| 64 |
-
def process_out(self, latent):
|
| 65 |
-
latents_mean = self.latents_mean.to(latent.device, latent.dtype)
|
| 66 |
-
latents_std = self.latents_std.to(latent.device, latent.dtype)
|
| 67 |
-
return latent * latents_std / self.scale_factor + latents_mean
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
class SD_X4(LatentFormat):
|
| 71 |
-
def __init__(self):
|
| 72 |
-
self.scale_factor = 0.08333
|
| 73 |
-
self.latent_rgb_factors = [
|
| 74 |
-
[-0.2340, -0.3863, -0.3257],
|
| 75 |
-
[ 0.0994, 0.0885, -0.0908],
|
| 76 |
-
[-0.2833, -0.2349, -0.3741],
|
| 77 |
-
[ 0.2523, -0.0055, -0.1651]
|
| 78 |
-
]
|
| 79 |
-
|
| 80 |
-
class SC_Prior(LatentFormat):
|
| 81 |
-
latent_channels = 16
|
| 82 |
-
def __init__(self):
|
| 83 |
-
self.scale_factor = 1.0
|
| 84 |
-
self.latent_rgb_factors = [
|
| 85 |
-
[-0.0326, -0.0204, -0.0127],
|
| 86 |
-
[-0.1592, -0.0427, 0.0216],
|
| 87 |
-
[ 0.0873, 0.0638, -0.0020],
|
| 88 |
-
[-0.0602, 0.0442, 0.1304],
|
| 89 |
-
[ 0.0800, -0.0313, -0.1796],
|
| 90 |
-
[-0.0810, -0.0638, -0.1581],
|
| 91 |
-
[ 0.1791, 0.1180, 0.0967],
|
| 92 |
-
[ 0.0740, 0.1416, 0.0432],
|
| 93 |
-
[-0.1745, -0.1888, -0.1373],
|
| 94 |
-
[ 0.2412, 0.1577, 0.0928],
|
| 95 |
-
[ 0.1908, 0.0998, 0.0682],
|
| 96 |
-
[ 0.0209, 0.0365, -0.0092],
|
| 97 |
-
[ 0.0448, -0.0650, -0.1728],
|
| 98 |
-
[-0.1658, -0.1045, -0.1308],
|
| 99 |
-
[ 0.0542, 0.1545, 0.1325],
|
| 100 |
-
[-0.0352, -0.1672, -0.2541]
|
| 101 |
-
]
|
| 102 |
-
|
| 103 |
-
class SC_B(LatentFormat):
|
| 104 |
-
def __init__(self):
|
| 105 |
-
self.scale_factor = 1.0 / 0.43
|
| 106 |
-
self.latent_rgb_factors = [
|
| 107 |
-
[ 0.1121, 0.2006, 0.1023],
|
| 108 |
-
[-0.2093, -0.0222, -0.0195],
|
| 109 |
-
[-0.3087, -0.1535, 0.0366],
|
| 110 |
-
[ 0.0290, -0.1574, -0.4078]
|
| 111 |
-
]
|
| 112 |
-
|
| 113 |
-
class SD3(LatentFormat):
|
| 114 |
-
latent_channels = 16
|
| 115 |
-
def __init__(self):
|
| 116 |
-
self.scale_factor = 1.5305
|
| 117 |
-
self.shift_factor = 0.0609
|
| 118 |
-
self.latent_rgb_factors = [
|
| 119 |
-
[-0.0922, -0.0175, 0.0749],
|
| 120 |
-
[ 0.0311, 0.0633, 0.0954],
|
| 121 |
-
[ 0.1994, 0.0927, 0.0458],
|
| 122 |
-
[ 0.0856, 0.0339, 0.0902],
|
| 123 |
-
[ 0.0587, 0.0272, -0.0496],
|
| 124 |
-
[-0.0006, 0.1104, 0.0309],
|
| 125 |
-
[ 0.0978, 0.0306, 0.0427],
|
| 126 |
-
[-0.0042, 0.1038, 0.1358],
|
| 127 |
-
[-0.0194, 0.0020, 0.0669],
|
| 128 |
-
[-0.0488, 0.0130, -0.0268],
|
| 129 |
-
[ 0.0922, 0.0988, 0.0951],
|
| 130 |
-
[-0.0278, 0.0524, -0.0542],
|
| 131 |
-
[ 0.0332, 0.0456, 0.0895],
|
| 132 |
-
[-0.0069, -0.0030, -0.0810],
|
| 133 |
-
[-0.0596, -0.0465, -0.0293],
|
| 134 |
-
[-0.1448, -0.1463, -0.1189]
|
| 135 |
-
]
|
| 136 |
-
self.latent_rgb_factors_bias = [0.2394, 0.2135, 0.1925]
|
| 137 |
-
self.taesd_decoder_name = "taesd3_decoder"
|
| 138 |
-
|
| 139 |
-
def process_in(self, latent):
|
| 140 |
-
return (latent - self.shift_factor) * self.scale_factor
|
| 141 |
-
|
| 142 |
-
def process_out(self, latent):
|
| 143 |
-
return (latent / self.scale_factor) + self.shift_factor
|
| 144 |
-
|
| 145 |
-
class StableAudio1(LatentFormat):
|
| 146 |
-
latent_channels = 64
|
| 147 |
-
latent_dimensions = 1
|
| 148 |
-
|
| 149 |
-
class Flux(SD3):
|
| 150 |
-
latent_channels = 16
|
| 151 |
-
def __init__(self):
|
| 152 |
-
self.scale_factor = 0.3611
|
| 153 |
-
self.shift_factor = 0.1159
|
| 154 |
-
self.latent_rgb_factors =[
|
| 155 |
-
[-0.0346, 0.0244, 0.0681],
|
| 156 |
-
[ 0.0034, 0.0210, 0.0687],
|
| 157 |
-
[ 0.0275, -0.0668, -0.0433],
|
| 158 |
-
[-0.0174, 0.0160, 0.0617],
|
| 159 |
-
[ 0.0859, 0.0721, 0.0329],
|
| 160 |
-
[ 0.0004, 0.0383, 0.0115],
|
| 161 |
-
[ 0.0405, 0.0861, 0.0915],
|
| 162 |
-
[-0.0236, -0.0185, -0.0259],
|
| 163 |
-
[-0.0245, 0.0250, 0.1180],
|
| 164 |
-
[ 0.1008, 0.0755, -0.0421],
|
| 165 |
-
[-0.0515, 0.0201, 0.0011],
|
| 166 |
-
[ 0.0428, -0.0012, -0.0036],
|
| 167 |
-
[ 0.0817, 0.0765, 0.0749],
|
| 168 |
-
[-0.1264, -0.0522, -0.1103],
|
| 169 |
-
[-0.0280, -0.0881, -0.0499],
|
| 170 |
-
[-0.1262, -0.0982, -0.0778]
|
| 171 |
-
]
|
| 172 |
-
self.latent_rgb_factors_bias = [-0.0329, -0.0718, -0.0851]
|
| 173 |
-
self.taesd_decoder_name = "taef1_decoder"
|
| 174 |
-
|
| 175 |
-
def process_in(self, latent):
|
| 176 |
-
return (latent - self.shift_factor) * self.scale_factor
|
| 177 |
-
|
| 178 |
-
def process_out(self, latent):
|
| 179 |
-
return (latent / self.scale_factor) + self.shift_factor
|
| 180 |
-
|
| 181 |
-
class Mochi(LatentFormat):
|
| 182 |
-
latent_channels = 12
|
| 183 |
-
latent_dimensions = 3
|
| 184 |
-
|
| 185 |
-
def __init__(self):
|
| 186 |
-
self.scale_factor = 1.0
|
| 187 |
-
self.latents_mean = torch.tensor([-0.06730895953510081, -0.038011381506090416, -0.07477820912866141,
|
| 188 |
-
-0.05565264470995561, 0.012767231469026969, -0.04703542746246419,
|
| 189 |
-
0.043896967884726704, -0.09346305707025976, -0.09918314763016893,
|
| 190 |
-
-0.008729793427399178, -0.011931556316503654, -0.0321993391887285]).view(1, self.latent_channels, 1, 1, 1)
|
| 191 |
-
self.latents_std = torch.tensor([0.9263795028493863, 0.9248894543193766, 0.9393059390890617,
|
| 192 |
-
0.959253732819592, 0.8244560132752793, 0.917259975397747,
|
| 193 |
-
0.9294154431013696, 1.3720942357788521, 0.881393668867029,
|
| 194 |
-
0.9168315692124348, 0.9185249279345552, 0.9274757570805041]).view(1, self.latent_channels, 1, 1, 1)
|
| 195 |
-
|
| 196 |
-
self.latent_rgb_factors =[
|
| 197 |
-
[-0.0069, -0.0045, 0.0018],
|
| 198 |
-
[ 0.0154, -0.0692, -0.0274],
|
| 199 |
-
[ 0.0333, 0.0019, 0.0206],
|
| 200 |
-
[-0.1390, 0.0628, 0.1678],
|
| 201 |
-
[-0.0725, 0.0134, -0.1898],
|
| 202 |
-
[ 0.0074, -0.0270, -0.0209],
|
| 203 |
-
[-0.0176, -0.0277, -0.0221],
|
| 204 |
-
[ 0.5294, 0.5204, 0.3852],
|
| 205 |
-
[-0.0326, -0.0446, -0.0143],
|
| 206 |
-
[-0.0659, 0.0153, -0.0153],
|
| 207 |
-
[ 0.0185, -0.0217, 0.0014],
|
| 208 |
-
[-0.0396, -0.0495, -0.0281]
|
| 209 |
-
]
|
| 210 |
-
self.latent_rgb_factors_bias = [-0.0940, -0.1418, -0.1453]
|
| 211 |
-
self.taesd_decoder_name = None #TODO
|
| 212 |
-
|
| 213 |
-
def process_in(self, latent):
|
| 214 |
-
latents_mean = self.latents_mean.to(latent.device, latent.dtype)
|
| 215 |
-
latents_std = self.latents_std.to(latent.device, latent.dtype)
|
| 216 |
-
return (latent - latents_mean) * self.scale_factor / latents_std
|
| 217 |
-
|
| 218 |
-
def process_out(self, latent):
|
| 219 |
-
latents_mean = self.latents_mean.to(latent.device, latent.dtype)
|
| 220 |
-
latents_std = self.latents_std.to(latent.device, latent.dtype)
|
| 221 |
-
return latent * latents_std / self.scale_factor + latents_mean
|
| 222 |
-
|
| 223 |
-
class LTXV(LatentFormat):
|
| 224 |
-
latent_channels = 128
|
| 225 |
-
latent_dimensions = 3
|
| 226 |
-
|
| 227 |
-
def __init__(self):
|
| 228 |
-
self.latent_rgb_factors = [
|
| 229 |
-
[ 1.1202e-02, -6.3815e-04, -1.0021e-02],
|
| 230 |
-
[ 8.6031e-02, 6.5813e-02, 9.5409e-04],
|
| 231 |
-
[-1.2576e-02, -7.5734e-03, -4.0528e-03],
|
| 232 |
-
[ 9.4063e-03, -2.1688e-03, 2.6093e-03],
|
| 233 |
-
[ 3.7636e-03, 1.2765e-02, 9.1548e-03],
|
| 234 |
-
[ 2.1024e-02, -5.2973e-03, 3.4373e-03],
|
| 235 |
-
[-8.8896e-03, -1.9703e-02, -1.8761e-02],
|
| 236 |
-
[-1.3160e-02, -1.0523e-02, 1.9709e-03],
|
| 237 |
-
[-1.5152e-03, -6.9891e-03, -7.5810e-03],
|
| 238 |
-
[-1.7247e-03, 4.6560e-04, -3.3839e-03],
|
| 239 |
-
[ 1.3617e-02, 4.7077e-03, -2.0045e-03],
|
| 240 |
-
[ 1.0256e-02, 7.7318e-03, 1.3948e-02],
|
| 241 |
-
[-1.6108e-02, -6.2151e-03, 1.1561e-03],
|
| 242 |
-
[ 7.3407e-03, 1.5628e-02, 4.4865e-04],
|
| 243 |
-
[ 9.5357e-04, -2.9518e-03, -1.4760e-02],
|
| 244 |
-
[ 1.9143e-02, 1.0868e-02, 1.2264e-02],
|
| 245 |
-
[ 4.4575e-03, 3.6682e-05, -6.8508e-03],
|
| 246 |
-
[-4.5681e-04, 3.2570e-03, 7.7929e-03],
|
| 247 |
-
[ 3.3902e-02, 3.3405e-02, 3.7454e-02],
|
| 248 |
-
[-2.3001e-02, -2.4877e-03, -3.1033e-03],
|
| 249 |
-
[ 5.0265e-02, 3.8841e-02, 3.3539e-02],
|
| 250 |
-
[-4.1018e-03, -1.1095e-03, 1.5859e-03],
|
| 251 |
-
[-1.2689e-01, -1.3107e-01, -2.1005e-01],
|
| 252 |
-
[ 2.6276e-02, 1.4189e-02, -3.5963e-03],
|
| 253 |
-
[-4.8679e-03, 8.8486e-03, 7.8029e-03],
|
| 254 |
-
[-1.6610e-03, -4.8597e-03, -5.2060e-03],
|
| 255 |
-
[-2.1010e-03, 2.3610e-03, 9.3796e-03],
|
| 256 |
-
[-2.2482e-02, -2.1305e-02, -1.5087e-02],
|
| 257 |
-
[-1.5753e-02, -1.0646e-02, -6.5083e-03],
|
| 258 |
-
[-4.6975e-03, 5.0288e-03, -6.7390e-03],
|
| 259 |
-
[ 1.1951e-02, 2.0712e-02, 1.6191e-02],
|
| 260 |
-
[-6.3704e-03, -8.4827e-03, -9.5483e-03],
|
| 261 |
-
[ 7.2610e-03, -9.9326e-03, -2.2978e-02],
|
| 262 |
-
[-9.1904e-04, 6.2882e-03, 9.5720e-03],
|
| 263 |
-
[-3.7178e-02, -3.7123e-02, -5.6713e-02],
|
| 264 |
-
[-1.3373e-01, -1.0720e-01, -5.3801e-02],
|
| 265 |
-
[-5.3702e-03, 8.1256e-03, 8.8397e-03],
|
| 266 |
-
[-1.5247e-01, -2.1437e-01, -2.1843e-01],
|
| 267 |
-
[ 3.1441e-02, 7.0335e-03, -9.7541e-03],
|
| 268 |
-
[ 2.1528e-03, -8.9817e-03, -2.1023e-02],
|
| 269 |
-
[ 3.8461e-03, -5.8957e-03, -1.5014e-02],
|
| 270 |
-
[-4.3470e-03, -1.2940e-02, -1.5972e-02],
|
| 271 |
-
[-5.4781e-03, -1.0842e-02, -3.0204e-03],
|
| 272 |
-
[-6.5347e-03, 3.0806e-03, -1.0163e-02],
|
| 273 |
-
[-5.0414e-03, -7.1503e-03, -8.9686e-04],
|
| 274 |
-
[-8.5851e-03, -2.4351e-03, 1.0674e-03],
|
| 275 |
-
[-9.0016e-03, -9.6493e-03, 1.5692e-03],
|
| 276 |
-
[ 5.0914e-03, 1.2099e-02, 1.9968e-02],
|
| 277 |
-
[ 1.3758e-02, 1.1669e-02, 8.1958e-03],
|
| 278 |
-
[-1.0518e-02, -1.1575e-02, -4.1307e-03],
|
| 279 |
-
[-2.8410e-02, -3.1266e-02, -2.2149e-02],
|
| 280 |
-
[ 2.9336e-03, 3.6511e-02, 1.8717e-02],
|
| 281 |
-
[-1.6703e-02, -1.6696e-02, -4.4529e-03],
|
| 282 |
-
[ 4.8818e-02, 4.0063e-02, 8.7410e-03],
|
| 283 |
-
[-1.5066e-02, -5.7328e-04, 2.9785e-03],
|
| 284 |
-
[-1.7613e-02, -8.1034e-03, 1.3086e-02],
|
| 285 |
-
[-9.2633e-03, 1.0803e-02, -6.3489e-03],
|
| 286 |
-
[ 3.0851e-03, 4.7750e-04, 1.2347e-02],
|
| 287 |
-
[-2.2785e-02, -2.3043e-02, -2.6005e-02],
|
| 288 |
-
[-2.4787e-02, -1.5389e-02, -2.2104e-02],
|
| 289 |
-
[-2.3572e-02, 1.0544e-03, 1.2361e-02],
|
| 290 |
-
[-7.8915e-03, -1.2271e-03, -6.0968e-03],
|
| 291 |
-
[-1.1478e-02, -1.2543e-03, 6.2679e-03],
|
| 292 |
-
[-5.4229e-02, 2.6644e-02, 6.3394e-03],
|
| 293 |
-
[ 4.4216e-03, -7.3338e-03, -1.0464e-02],
|
| 294 |
-
[-4.5013e-03, 1.6082e-03, 1.4420e-02],
|
| 295 |
-
[ 1.3673e-02, 8.8877e-03, 4.1253e-03],
|
| 296 |
-
[-1.0145e-02, 9.0072e-03, 1.5695e-02],
|
| 297 |
-
[-5.6234e-03, 1.1847e-03, 8.1261e-03],
|
| 298 |
-
[-3.7171e-03, -5.3538e-03, 1.2590e-03],
|
| 299 |
-
[ 2.9476e-02, 2.1424e-02, 3.0424e-02],
|
| 300 |
-
[-3.4925e-02, -2.4340e-02, -2.5316e-02],
|
| 301 |
-
[-3.4127e-02, -2.2406e-02, -1.0589e-02],
|
| 302 |
-
[-1.7342e-02, -1.3249e-02, -1.0719e-02],
|
| 303 |
-
[-2.1478e-03, -8.6051e-03, -2.9878e-03],
|
| 304 |
-
[ 1.2089e-03, -4.2391e-03, -6.8569e-03],
|
| 305 |
-
[ 9.0411e-04, -6.6886e-03, -6.7547e-05],
|
| 306 |
-
[ 1.6048e-02, -1.0057e-02, -2.8929e-02],
|
| 307 |
-
[ 1.2290e-03, 1.0163e-02, 1.8861e-02],
|
| 308 |
-
[ 1.7264e-02, 2.7257e-04, 1.3785e-02],
|
| 309 |
-
[-1.3482e-02, -3.6427e-03, 6.7481e-04],
|
| 310 |
-
[ 4.6782e-03, -5.2423e-03, 2.4467e-03],
|
| 311 |
-
[-5.9113e-03, -6.2244e-03, -1.8162e-03],
|
| 312 |
-
[ 1.5496e-02, 1.4582e-02, 1.9514e-03],
|
| 313 |
-
[ 7.4958e-03, 1.5886e-03, -8.2305e-03],
|
| 314 |
-
[ 1.9086e-02, 1.6360e-03, -3.9674e-03],
|
| 315 |
-
[-5.7021e-03, -2.7307e-03, -4.1066e-03],
|
| 316 |
-
[ 1.7450e-03, 1.4602e-02, 2.5794e-02],
|
| 317 |
-
[-8.2788e-04, 2.2902e-03, 4.5161e-03],
|
| 318 |
-
[ 1.1632e-02, 8.9193e-03, -7.2813e-03],
|
| 319 |
-
[ 7.5721e-03, 2.6784e-03, 1.1393e-02],
|
| 320 |
-
[ 5.1939e-03, 3.6903e-03, 1.4049e-02],
|
| 321 |
-
[-1.8383e-02, -2.2529e-02, -2.4477e-02],
|
| 322 |
-
[ 5.8842e-04, -5.7874e-03, -1.4770e-02],
|
| 323 |
-
[-1.6125e-02, -8.6101e-03, -1.4533e-02],
|
| 324 |
-
[ 2.0540e-02, 2.0729e-02, 6.4338e-03],
|
| 325 |
-
[ 3.3587e-03, -1.1226e-02, -1.6444e-02],
|
| 326 |
-
[-1.4742e-03, -1.0489e-02, 1.7097e-03],
|
| 327 |
-
[ 2.8130e-02, 2.3546e-02, 3.2791e-02],
|
| 328 |
-
[-1.8532e-02, -1.2842e-02, -8.7756e-03],
|
| 329 |
-
[-8.0533e-03, -1.0771e-02, -1.7536e-02],
|
| 330 |
-
[-3.9009e-03, 1.6150e-02, 3.3359e-02],
|
| 331 |
-
[-7.4554e-03, -1.4154e-02, -6.1910e-03],
|
| 332 |
-
[ 3.4734e-03, -1.1370e-02, -1.0581e-02],
|
| 333 |
-
[ 1.1476e-02, 3.9281e-03, 2.8231e-03],
|
| 334 |
-
[ 7.1639e-03, -1.4741e-03, -3.8066e-03],
|
| 335 |
-
[ 2.2250e-03, -8.7552e-03, -9.5719e-03],
|
| 336 |
-
[ 2.4146e-02, 2.1696e-02, 2.8056e-02],
|
| 337 |
-
[-5.4365e-03, -2.4291e-02, -1.7802e-02],
|
| 338 |
-
[ 7.4263e-03, 1.0510e-02, 1.2705e-02],
|
| 339 |
-
[ 6.2669e-03, 6.2658e-03, 1.9211e-02],
|
| 340 |
-
[ 1.6378e-02, 9.4933e-03, 6.6971e-03],
|
| 341 |
-
[ 1.7173e-02, 2.3601e-02, 2.3296e-02],
|
| 342 |
-
[-1.4568e-02, -9.8279e-03, -1.1556e-02],
|
| 343 |
-
[ 1.4431e-02, 1.4430e-02, 6.6362e-03],
|
| 344 |
-
[-6.8230e-03, 1.8863e-02, 1.4555e-02],
|
| 345 |
-
[ 6.1156e-03, 3.4700e-03, -2.6662e-03],
|
| 346 |
-
[-2.6983e-03, -5.9402e-03, -9.2276e-03],
|
| 347 |
-
[ 1.0235e-02, 7.4173e-03, -7.6243e-03],
|
| 348 |
-
[-1.3255e-02, 1.9322e-02, -9.2153e-04],
|
| 349 |
-
[ 2.4222e-03, -4.8039e-03, -1.5759e-02],
|
| 350 |
-
[ 2.6244e-02, 2.5951e-02, 2.0249e-02],
|
| 351 |
-
[ 1.5711e-02, 1.8498e-02, 2.7407e-03],
|
| 352 |
-
[-2.1714e-03, 4.7214e-03, -2.2443e-02],
|
| 353 |
-
[-7.4747e-03, 7.4166e-03, 1.4430e-02],
|
| 354 |
-
[-8.3906e-03, -7.9776e-03, 9.7927e-03],
|
| 355 |
-
[ 3.8321e-02, 9.6622e-03, -1.9268e-02],
|
| 356 |
-
[-1.4605e-02, -6.7032e-03, 3.9675e-03]
|
| 357 |
-
]
|
| 358 |
-
|
| 359 |
-
self.latent_rgb_factors_bias = [-0.0571, -0.1657, -0.2512]
|
| 360 |
-
|
| 361 |
-
class HunyuanVideo(LatentFormat):
|
| 362 |
-
latent_channels = 16
|
| 363 |
-
latent_dimensions = 3
|
| 364 |
-
scale_factor = 0.476986
|
| 365 |
-
latent_rgb_factors = [
|
| 366 |
-
[-0.0395, -0.0331, 0.0445],
|
| 367 |
-
[ 0.0696, 0.0795, 0.0518],
|
| 368 |
-
[ 0.0135, -0.0945, -0.0282],
|
| 369 |
-
[ 0.0108, -0.0250, -0.0765],
|
| 370 |
-
[-0.0209, 0.0032, 0.0224],
|
| 371 |
-
[-0.0804, -0.0254, -0.0639],
|
| 372 |
-
[-0.0991, 0.0271, -0.0669],
|
| 373 |
-
[-0.0646, -0.0422, -0.0400],
|
| 374 |
-
[-0.0696, -0.0595, -0.0894],
|
| 375 |
-
[-0.0799, -0.0208, -0.0375],
|
| 376 |
-
[ 0.1166, 0.1627, 0.0962],
|
| 377 |
-
[ 0.1165, 0.0432, 0.0407],
|
| 378 |
-
[-0.2315, -0.1920, -0.1355],
|
| 379 |
-
[-0.0270, 0.0401, -0.0821],
|
| 380 |
-
[-0.0616, -0.0997, -0.0727],
|
| 381 |
-
[ 0.0249, -0.0469, -0.1703]
|
| 382 |
-
]
|
| 383 |
-
|
| 384 |
-
latent_rgb_factors_bias = [ 0.0259, -0.0192, -0.0761]
|
| 385 |
-
|
| 386 |
-
class Cosmos1CV8x8x8(LatentFormat):
|
| 387 |
-
latent_channels = 16
|
| 388 |
-
latent_dimensions = 3
|
| 389 |
-
|
| 390 |
-
latent_rgb_factors = [
|
| 391 |
-
[ 0.1817, 0.2284, 0.2423],
|
| 392 |
-
[-0.0586, -0.0862, -0.3108],
|
| 393 |
-
[-0.4703, -0.4255, -0.3995],
|
| 394 |
-
[ 0.0803, 0.1963, 0.1001],
|
| 395 |
-
[-0.0820, -0.1050, 0.0400],
|
| 396 |
-
[ 0.2511, 0.3098, 0.2787],
|
| 397 |
-
[-0.1830, -0.2117, -0.0040],
|
| 398 |
-
[-0.0621, -0.2187, -0.0939],
|
| 399 |
-
[ 0.3619, 0.1082, 0.1455],
|
| 400 |
-
[ 0.3164, 0.3922, 0.2575],
|
| 401 |
-
[ 0.1152, 0.0231, -0.0462],
|
| 402 |
-
[-0.1434, -0.3609, -0.3665],
|
| 403 |
-
[ 0.0635, 0.1471, 0.1680],
|
| 404 |
-
[-0.3635, -0.1963, -0.3248],
|
| 405 |
-
[-0.1865, 0.0365, 0.2346],
|
| 406 |
-
[ 0.0447, 0.0994, 0.0881]
|
| 407 |
-
]
|
| 408 |
-
|
| 409 |
-
latent_rgb_factors_bias = [-0.1223, -0.1889, -0.1976]
|
| 410 |
-
|
| 411 |
-
class Wan21(LatentFormat):
|
| 412 |
-
latent_channels = 16
|
| 413 |
-
latent_dimensions = 3
|
| 414 |
-
|
| 415 |
-
latent_rgb_factors = [
|
| 416 |
-
[-0.1299, -0.1692, 0.2932],
|
| 417 |
-
[ 0.0671, 0.0406, 0.0442],
|
| 418 |
-
[ 0.3568, 0.2548, 0.1747],
|
| 419 |
-
[ 0.0372, 0.2344, 0.1420],
|
| 420 |
-
[ 0.0313, 0.0189, -0.0328],
|
| 421 |
-
[ 0.0296, -0.0956, -0.0665],
|
| 422 |
-
[-0.3477, -0.4059, -0.2925],
|
| 423 |
-
[ 0.0166, 0.1902, 0.1975],
|
| 424 |
-
[-0.0412, 0.0267, -0.1364],
|
| 425 |
-
[-0.1293, 0.0740, 0.1636],
|
| 426 |
-
[ 0.0680, 0.3019, 0.1128],
|
| 427 |
-
[ 0.0032, 0.0581, 0.0639],
|
| 428 |
-
[-0.1251, 0.0927, 0.1699],
|
| 429 |
-
[ 0.0060, -0.0633, 0.0005],
|
| 430 |
-
[ 0.3477, 0.2275, 0.2950],
|
| 431 |
-
[ 0.1984, 0.0913, 0.1861]
|
| 432 |
-
]
|
| 433 |
-
|
| 434 |
-
latent_rgb_factors_bias = [-0.1835, -0.0868, -0.3360]
|
| 435 |
-
|
| 436 |
-
def __init__(self):
|
| 437 |
-
self.scale_factor = 1.0
|
| 438 |
-
self.latents_mean = torch.tensor([
|
| 439 |
-
-0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508,
|
| 440 |
-
0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921
|
| 441 |
-
]).view(1, self.latent_channels, 1, 1, 1)
|
| 442 |
-
self.latents_std = torch.tensor([
|
| 443 |
-
2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743,
|
| 444 |
-
3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160
|
| 445 |
-
]).view(1, self.latent_channels, 1, 1, 1)
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
self.taesd_decoder_name = None #TODO
|
| 449 |
-
|
| 450 |
-
def process_in(self, latent):
|
| 451 |
-
latents_mean = self.latents_mean.to(latent.device, latent.dtype)
|
| 452 |
-
latents_std = self.latents_std.to(latent.device, latent.dtype)
|
| 453 |
-
return (latent - latents_mean) * self.scale_factor / latents_std
|
| 454 |
-
|
| 455 |
-
def process_out(self, latent):
|
| 456 |
-
latents_mean = self.latents_mean.to(latent.device, latent.dtype)
|
| 457 |
-
latents_std = self.latents_std.to(latent.device, latent.dtype)
|
| 458 |
-
return latent * latents_std / self.scale_factor + latents_mean
|
| 459 |
-
|
| 460 |
-
class Hunyuan3Dv2(LatentFormat):
|
| 461 |
-
latent_channels = 64
|
| 462 |
-
latent_dimensions = 1
|
| 463 |
-
scale_factor = 0.9990943042622529
|
| 464 |
-
|
| 465 |
-
class Hunyuan3Dv2mini(LatentFormat):
|
| 466 |
-
latent_channels = 64
|
| 467 |
-
latent_dimensions = 1
|
| 468 |
-
scale_factor = 1.0188137142395404
|
| 469 |
-
|
| 470 |
-
class ACEAudio(LatentFormat):
|
| 471 |
-
latent_channels = 8
|
| 472 |
-
latent_dimensions = 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ention.py
DELETED
|
@@ -1,761 +0,0 @@
|
|
| 1 |
-
# Original from: https://github.com/ace-step/ACE-Step/blob/main/models/attention.py
|
| 2 |
-
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 3 |
-
#
|
| 4 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
-
# you may not use this file except in compliance with the License.
|
| 6 |
-
# You may obtain a copy of the License at
|
| 7 |
-
#
|
| 8 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
-
#
|
| 10 |
-
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
-
# See the License for the specific language governing permissions and
|
| 14 |
-
# limitations under the License.
|
| 15 |
-
from typing import Tuple, Union, Optional
|
| 16 |
-
|
| 17 |
-
import torch
|
| 18 |
-
import torch.nn.functional as F
|
| 19 |
-
from torch import nn
|
| 20 |
-
|
| 21 |
-
import comfy.model_management
|
| 22 |
-
from comfy.ldm.modules.attention import optimized_attention
|
| 23 |
-
|
| 24 |
-
class Attention(nn.Module):
|
| 25 |
-
def __init__(
|
| 26 |
-
self,
|
| 27 |
-
query_dim: int,
|
| 28 |
-
cross_attention_dim: Optional[int] = None,
|
| 29 |
-
heads: int = 8,
|
| 30 |
-
kv_heads: Optional[int] = None,
|
| 31 |
-
dim_head: int = 64,
|
| 32 |
-
dropout: float = 0.0,
|
| 33 |
-
bias: bool = False,
|
| 34 |
-
qk_norm: Optional[str] = None,
|
| 35 |
-
added_kv_proj_dim: Optional[int] = None,
|
| 36 |
-
added_proj_bias: Optional[bool] = True,
|
| 37 |
-
out_bias: bool = True,
|
| 38 |
-
scale_qk: bool = True,
|
| 39 |
-
only_cross_attention: bool = False,
|
| 40 |
-
eps: float = 1e-5,
|
| 41 |
-
rescale_output_factor: float = 1.0,
|
| 42 |
-
residual_connection: bool = False,
|
| 43 |
-
processor=None,
|
| 44 |
-
out_dim: int = None,
|
| 45 |
-
out_context_dim: int = None,
|
| 46 |
-
context_pre_only=None,
|
| 47 |
-
pre_only=False,
|
| 48 |
-
elementwise_affine: bool = True,
|
| 49 |
-
is_causal: bool = False,
|
| 50 |
-
dtype=None, device=None, operations=None
|
| 51 |
-
):
|
| 52 |
-
super().__init__()
|
| 53 |
-
|
| 54 |
-
self.inner_dim = out_dim if out_dim is not None else dim_head * heads
|
| 55 |
-
self.inner_kv_dim = self.inner_dim if kv_heads is None else dim_head * kv_heads
|
| 56 |
-
self.query_dim = query_dim
|
| 57 |
-
self.use_bias = bias
|
| 58 |
-
self.is_cross_attention = cross_attention_dim is not None
|
| 59 |
-
self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
|
| 60 |
-
self.rescale_output_factor = rescale_output_factor
|
| 61 |
-
self.residual_connection = residual_connection
|
| 62 |
-
self.dropout = dropout
|
| 63 |
-
self.fused_projections = False
|
| 64 |
-
self.out_dim = out_dim if out_dim is not None else query_dim
|
| 65 |
-
self.out_context_dim = out_context_dim if out_context_dim is not None else query_dim
|
| 66 |
-
self.context_pre_only = context_pre_only
|
| 67 |
-
self.pre_only = pre_only
|
| 68 |
-
self.is_causal = is_causal
|
| 69 |
-
|
| 70 |
-
self.scale_qk = scale_qk
|
| 71 |
-
self.scale = dim_head**-0.5 if self.scale_qk else 1.0
|
| 72 |
-
|
| 73 |
-
self.heads = out_dim // dim_head if out_dim is not None else heads
|
| 74 |
-
# for slice_size > 0 the attention score computation
|
| 75 |
-
# is split across the batch axis to save memory
|
| 76 |
-
# You can set slice_size with `set_attention_slice`
|
| 77 |
-
self.sliceable_head_dim = heads
|
| 78 |
-
|
| 79 |
-
self.added_kv_proj_dim = added_kv_proj_dim
|
| 80 |
-
self.only_cross_attention = only_cross_attention
|
| 81 |
-
|
| 82 |
-
if self.added_kv_proj_dim is None and self.only_cross_attention:
|
| 83 |
-
raise ValueError(
|
| 84 |
-
"`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
|
| 85 |
-
)
|
| 86 |
-
|
| 87 |
-
self.group_norm = None
|
| 88 |
-
self.spatial_norm = None
|
| 89 |
-
|
| 90 |
-
self.norm_q = None
|
| 91 |
-
self.norm_k = None
|
| 92 |
-
|
| 93 |
-
self.norm_cross = None
|
| 94 |
-
self.to_q = operations.Linear(query_dim, self.inner_dim, bias=bias, dtype=dtype, device=device)
|
| 95 |
-
|
| 96 |
-
if not self.only_cross_attention:
|
| 97 |
-
# only relevant for the `AddedKVProcessor` classes
|
| 98 |
-
self.to_k = operations.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias, dtype=dtype, device=device)
|
| 99 |
-
self.to_v = operations.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias, dtype=dtype, device=device)
|
| 100 |
-
else:
|
| 101 |
-
self.to_k = None
|
| 102 |
-
self.to_v = None
|
| 103 |
-
|
| 104 |
-
self.added_proj_bias = added_proj_bias
|
| 105 |
-
if self.added_kv_proj_dim is not None:
|
| 106 |
-
self.add_k_proj = operations.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias, dtype=dtype, device=device)
|
| 107 |
-
self.add_v_proj = operations.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias, dtype=dtype, device=device)
|
| 108 |
-
if self.context_pre_only is not None:
|
| 109 |
-
self.add_q_proj = operations.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias, dtype=dtype, device=device)
|
| 110 |
-
else:
|
| 111 |
-
self.add_q_proj = None
|
| 112 |
-
self.add_k_proj = None
|
| 113 |
-
self.add_v_proj = None
|
| 114 |
-
|
| 115 |
-
if not self.pre_only:
|
| 116 |
-
self.to_out = nn.ModuleList([])
|
| 117 |
-
self.to_out.append(operations.Linear(self.inner_dim, self.out_dim, bias=out_bias, dtype=dtype, device=device))
|
| 118 |
-
self.to_out.append(nn.Dropout(dropout))
|
| 119 |
-
else:
|
| 120 |
-
self.to_out = None
|
| 121 |
-
|
| 122 |
-
if self.context_pre_only is not None and not self.context_pre_only:
|
| 123 |
-
self.to_add_out = operations.Linear(self.inner_dim, self.out_context_dim, bias=out_bias, dtype=dtype, device=device)
|
| 124 |
-
else:
|
| 125 |
-
self.to_add_out = None
|
| 126 |
-
|
| 127 |
-
self.norm_added_q = None
|
| 128 |
-
self.norm_added_k = None
|
| 129 |
-
self.processor = processor
|
| 130 |
-
|
| 131 |
-
def forward(
|
| 132 |
-
self,
|
| 133 |
-
hidden_states: torch.Tensor,
|
| 134 |
-
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 135 |
-
attention_mask: Optional[torch.Tensor] = None,
|
| 136 |
-
**cross_attention_kwargs,
|
| 137 |
-
) -> torch.Tensor:
|
| 138 |
-
return self.processor(
|
| 139 |
-
self,
|
| 140 |
-
hidden_states,
|
| 141 |
-
encoder_hidden_states=encoder_hidden_states,
|
| 142 |
-
attention_mask=attention_mask,
|
| 143 |
-
**cross_attention_kwargs,
|
| 144 |
-
)
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
class CustomLiteLAProcessor2_0:
|
| 148 |
-
"""Attention processor used typically in processing the SD3-like self-attention projections. add rms norm for query and key and apply RoPE"""
|
| 149 |
-
|
| 150 |
-
def __init__(self):
|
| 151 |
-
self.kernel_func = nn.ReLU(inplace=False)
|
| 152 |
-
self.eps = 1e-15
|
| 153 |
-
self.pad_val = 1.0
|
| 154 |
-
|
| 155 |
-
def apply_rotary_emb(
|
| 156 |
-
self,
|
| 157 |
-
x: torch.Tensor,
|
| 158 |
-
freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
|
| 159 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 160 |
-
"""
|
| 161 |
-
Apply rotary embeddings to input tensors using the given frequency tensor. This function applies rotary embeddings
|
| 162 |
-
to the given query or key 'x' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are
|
| 163 |
-
reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting
|
| 164 |
-
tensors contain rotary embeddings and are returned as real tensors.
|
| 165 |
-
|
| 166 |
-
Args:
|
| 167 |
-
x (`torch.Tensor`):
|
| 168 |
-
Query or key tensor to apply rotary embeddings. [B, H, S, D] xk (torch.Tensor): Key tensor to apply
|
| 169 |
-
freqs_cis (`Tuple[torch.Tensor]`): Precomputed frequency tensor for complex exponentials. ([S, D], [S, D],)
|
| 170 |
-
|
| 171 |
-
Returns:
|
| 172 |
-
Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
|
| 173 |
-
"""
|
| 174 |
-
cos, sin = freqs_cis # [S, D]
|
| 175 |
-
cos = cos[None, None]
|
| 176 |
-
sin = sin[None, None]
|
| 177 |
-
cos, sin = cos.to(x.device), sin.to(x.device)
|
| 178 |
-
|
| 179 |
-
x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
|
| 180 |
-
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
|
| 181 |
-
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
|
| 182 |
-
|
| 183 |
-
return out
|
| 184 |
-
|
| 185 |
-
def __call__(
|
| 186 |
-
self,
|
| 187 |
-
attn: Attention,
|
| 188 |
-
hidden_states: torch.FloatTensor,
|
| 189 |
-
encoder_hidden_states: torch.FloatTensor = None,
|
| 190 |
-
attention_mask: Optional[torch.FloatTensor] = None,
|
| 191 |
-
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 192 |
-
rotary_freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]] = None,
|
| 193 |
-
rotary_freqs_cis_cross: Union[torch.Tensor, Tuple[torch.Tensor]] = None,
|
| 194 |
-
*args,
|
| 195 |
-
**kwargs,
|
| 196 |
-
) -> torch.FloatTensor:
|
| 197 |
-
hidden_states_len = hidden_states.shape[1]
|
| 198 |
-
|
| 199 |
-
input_ndim = hidden_states.ndim
|
| 200 |
-
if input_ndim == 4:
|
| 201 |
-
batch_size, channel, height, width = hidden_states.shape
|
| 202 |
-
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 203 |
-
if encoder_hidden_states is not None:
|
| 204 |
-
context_input_ndim = encoder_hidden_states.ndim
|
| 205 |
-
if context_input_ndim == 4:
|
| 206 |
-
batch_size, channel, height, width = encoder_hidden_states.shape
|
| 207 |
-
encoder_hidden_states = encoder_hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 208 |
-
|
| 209 |
-
batch_size = hidden_states.shape[0]
|
| 210 |
-
|
| 211 |
-
# `sample` projections.
|
| 212 |
-
dtype = hidden_states.dtype
|
| 213 |
-
query = attn.to_q(hidden_states)
|
| 214 |
-
key = attn.to_k(hidden_states)
|
| 215 |
-
value = attn.to_v(hidden_states)
|
| 216 |
-
|
| 217 |
-
# `context` projections.
|
| 218 |
-
has_encoder_hidden_state_proj = hasattr(attn, "add_q_proj") and hasattr(attn, "add_k_proj") and hasattr(attn, "add_v_proj")
|
| 219 |
-
if encoder_hidden_states is not None and has_encoder_hidden_state_proj:
|
| 220 |
-
encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
|
| 221 |
-
encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
|
| 222 |
-
encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
|
| 223 |
-
|
| 224 |
-
# attention
|
| 225 |
-
if not attn.is_cross_attention:
|
| 226 |
-
query = torch.cat([query, encoder_hidden_states_query_proj], dim=1)
|
| 227 |
-
key = torch.cat([key, encoder_hidden_states_key_proj], dim=1)
|
| 228 |
-
value = torch.cat([value, encoder_hidden_states_value_proj], dim=1)
|
| 229 |
-
else:
|
| 230 |
-
query = hidden_states
|
| 231 |
-
key = encoder_hidden_states
|
| 232 |
-
value = encoder_hidden_states
|
| 233 |
-
|
| 234 |
-
inner_dim = key.shape[-1]
|
| 235 |
-
head_dim = inner_dim // attn.heads
|
| 236 |
-
|
| 237 |
-
query = query.transpose(-1, -2).reshape(batch_size, attn.heads, head_dim, -1)
|
| 238 |
-
key = key.transpose(-1, -2).reshape(batch_size, attn.heads, head_dim, -1).transpose(-1, -2)
|
| 239 |
-
value = value.transpose(-1, -2).reshape(batch_size, attn.heads, head_dim, -1)
|
| 240 |
-
|
| 241 |
-
# RoPE需要 [B, H, S, D] 输入
|
| 242 |
-
# 此时 query是 [B, H, D, S], 需要转成 [B, H, S, D] 才能应用RoPE
|
| 243 |
-
query = query.permute(0, 1, 3, 2) # [B, H, S, D] (从 [B, H, D, S])
|
| 244 |
-
|
| 245 |
-
# Apply query and key normalization if needed
|
| 246 |
-
if attn.norm_q is not None:
|
| 247 |
-
query = attn.norm_q(query)
|
| 248 |
-
if attn.norm_k is not None:
|
| 249 |
-
key = attn.norm_k(key)
|
| 250 |
-
|
| 251 |
-
# Apply RoPE if needed
|
| 252 |
-
if rotary_freqs_cis is not None:
|
| 253 |
-
query = self.apply_rotary_emb(query, rotary_freqs_cis)
|
| 254 |
-
if not attn.is_cross_attention:
|
| 255 |
-
key = self.apply_rotary_emb(key, rotary_freqs_cis)
|
| 256 |
-
elif rotary_freqs_cis_cross is not None and has_encoder_hidden_state_proj:
|
| 257 |
-
key = self.apply_rotary_emb(key, rotary_freqs_cis_cross)
|
| 258 |
-
|
| 259 |
-
# 此时 query是 [B, H, S, D],需要还原成 [B, H, D, S]
|
| 260 |
-
query = query.permute(0, 1, 3, 2) # [B, H, D, S]
|
| 261 |
-
|
| 262 |
-
if attention_mask is not None:
|
| 263 |
-
# attention_mask: [B, S] -> [B, 1, S, 1]
|
| 264 |
-
attention_mask = attention_mask[:, None, :, None].to(key.dtype) # [B, 1, S, 1]
|
| 265 |
-
query = query * attention_mask.permute(0, 1, 3, 2) # [B, H, S, D] * [B, 1, S, 1]
|
| 266 |
-
if not attn.is_cross_attention:
|
| 267 |
-
key = key * attention_mask # key: [B, h, S, D] 与 mask [B, 1, S, 1] 相乘
|
| 268 |
-
value = value * attention_mask.permute(0, 1, 3, 2) # 如果 value 是 [B, h, D, S],那么需调整mask以匹配S维度
|
| 269 |
-
|
| 270 |
-
if attn.is_cross_attention and encoder_attention_mask is not None and has_encoder_hidden_state_proj:
|
| 271 |
-
encoder_attention_mask = encoder_attention_mask[:, None, :, None].to(key.dtype) # [B, 1, S_enc, 1]
|
| 272 |
-
# 此时 key: [B, h, S_enc, D], value: [B, h, D, S_enc]
|
| 273 |
-
key = key * encoder_attention_mask # [B, h, S_enc, D] * [B, 1, S_enc, 1]
|
| 274 |
-
value = value * encoder_attention_mask.permute(0, 1, 3, 2) # [B, h, D, S_enc] * [B, 1, 1, S_enc]
|
| 275 |
-
|
| 276 |
-
query = self.kernel_func(query)
|
| 277 |
-
key = self.kernel_func(key)
|
| 278 |
-
|
| 279 |
-
query, key, value = query.float(), key.float(), value.float()
|
| 280 |
-
|
| 281 |
-
value = F.pad(value, (0, 0, 0, 1), mode="constant", value=self.pad_val)
|
| 282 |
-
|
| 283 |
-
vk = torch.matmul(value, key)
|
| 284 |
-
|
| 285 |
-
hidden_states = torch.matmul(vk, query)
|
| 286 |
-
|
| 287 |
-
if hidden_states.dtype in [torch.float16, torch.bfloat16]:
|
| 288 |
-
hidden_states = hidden_states.float()
|
| 289 |
-
|
| 290 |
-
hidden_states = hidden_states[:, :, :-1] / (hidden_states[:, :, -1:] + self.eps)
|
| 291 |
-
|
| 292 |
-
hidden_states = hidden_states.view(batch_size, attn.heads * head_dim, -1).permute(0, 2, 1)
|
| 293 |
-
|
| 294 |
-
hidden_states = hidden_states.to(dtype)
|
| 295 |
-
if encoder_hidden_states is not None:
|
| 296 |
-
encoder_hidden_states = encoder_hidden_states.to(dtype)
|
| 297 |
-
|
| 298 |
-
# Split the attention outputs.
|
| 299 |
-
if encoder_hidden_states is not None and not attn.is_cross_attention and has_encoder_hidden_state_proj:
|
| 300 |
-
hidden_states, encoder_hidden_states = (
|
| 301 |
-
hidden_states[:, : hidden_states_len],
|
| 302 |
-
hidden_states[:, hidden_states_len:],
|
| 303 |
-
)
|
| 304 |
-
|
| 305 |
-
# linear proj
|
| 306 |
-
hidden_states = attn.to_out[0](hidden_states)
|
| 307 |
-
# dropout
|
| 308 |
-
hidden_states = attn.to_out[1](hidden_states)
|
| 309 |
-
if encoder_hidden_states is not None and not attn.context_pre_only and not attn.is_cross_attention and hasattr(attn, "to_add_out"):
|
| 310 |
-
encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
|
| 311 |
-
|
| 312 |
-
if input_ndim == 4:
|
| 313 |
-
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 314 |
-
if encoder_hidden_states is not None and context_input_ndim == 4:
|
| 315 |
-
encoder_hidden_states = encoder_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 316 |
-
|
| 317 |
-
if torch.get_autocast_gpu_dtype() == torch.float16:
|
| 318 |
-
hidden_states = hidden_states.clip(-65504, 65504)
|
| 319 |
-
if encoder_hidden_states is not None:
|
| 320 |
-
encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
|
| 321 |
-
|
| 322 |
-
return hidden_states, encoder_hidden_states
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
class CustomerAttnProcessor2_0:
|
| 326 |
-
r"""
|
| 327 |
-
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
| 328 |
-
"""
|
| 329 |
-
|
| 330 |
-
def apply_rotary_emb(
|
| 331 |
-
self,
|
| 332 |
-
x: torch.Tensor,
|
| 333 |
-
freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
|
| 334 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 335 |
-
"""
|
| 336 |
-
Apply rotary embeddings to input tensors using the given frequency tensor. This function applies rotary embeddings
|
| 337 |
-
to the given query or key 'x' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are
|
| 338 |
-
reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting
|
| 339 |
-
tensors contain rotary embeddings and are returned as real tensors.
|
| 340 |
-
|
| 341 |
-
Args:
|
| 342 |
-
x (`torch.Tensor`):
|
| 343 |
-
Query or key tensor to apply rotary embeddings. [B, H, S, D] xk (torch.Tensor): Key tensor to apply
|
| 344 |
-
freqs_cis (`Tuple[torch.Tensor]`): Precomputed frequency tensor for complex exponentials. ([S, D], [S, D],)
|
| 345 |
-
|
| 346 |
-
Returns:
|
| 347 |
-
Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
|
| 348 |
-
"""
|
| 349 |
-
cos, sin = freqs_cis # [S, D]
|
| 350 |
-
cos = cos[None, None]
|
| 351 |
-
sin = sin[None, None]
|
| 352 |
-
cos, sin = cos.to(x.device), sin.to(x.device)
|
| 353 |
-
|
| 354 |
-
x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
|
| 355 |
-
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
|
| 356 |
-
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
|
| 357 |
-
|
| 358 |
-
return out
|
| 359 |
-
|
| 360 |
-
def __call__(
|
| 361 |
-
self,
|
| 362 |
-
attn: Attention,
|
| 363 |
-
hidden_states: torch.FloatTensor,
|
| 364 |
-
encoder_hidden_states: torch.FloatTensor = None,
|
| 365 |
-
attention_mask: Optional[torch.FloatTensor] = None,
|
| 366 |
-
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 367 |
-
rotary_freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]] = None,
|
| 368 |
-
rotary_freqs_cis_cross: Union[torch.Tensor, Tuple[torch.Tensor]] = None,
|
| 369 |
-
*args,
|
| 370 |
-
**kwargs,
|
| 371 |
-
) -> torch.Tensor:
|
| 372 |
-
|
| 373 |
-
residual = hidden_states
|
| 374 |
-
input_ndim = hidden_states.ndim
|
| 375 |
-
|
| 376 |
-
if input_ndim == 4:
|
| 377 |
-
batch_size, channel, height, width = hidden_states.shape
|
| 378 |
-
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 379 |
-
|
| 380 |
-
batch_size, sequence_length, _ = (
|
| 381 |
-
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 382 |
-
)
|
| 383 |
-
|
| 384 |
-
has_encoder_hidden_state_proj = hasattr(attn, "add_q_proj") and hasattr(attn, "add_k_proj") and hasattr(attn, "add_v_proj")
|
| 385 |
-
|
| 386 |
-
if attn.group_norm is not None:
|
| 387 |
-
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 388 |
-
|
| 389 |
-
query = attn.to_q(hidden_states)
|
| 390 |
-
|
| 391 |
-
if encoder_hidden_states is None:
|
| 392 |
-
encoder_hidden_states = hidden_states
|
| 393 |
-
elif attn.norm_cross:
|
| 394 |
-
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 395 |
-
|
| 396 |
-
key = attn.to_k(encoder_hidden_states)
|
| 397 |
-
value = attn.to_v(encoder_hidden_states)
|
| 398 |
-
|
| 399 |
-
inner_dim = key.shape[-1]
|
| 400 |
-
head_dim = inner_dim // attn.heads
|
| 401 |
-
|
| 402 |
-
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 403 |
-
|
| 404 |
-
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 405 |
-
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 406 |
-
|
| 407 |
-
if attn.norm_q is not None:
|
| 408 |
-
query = attn.norm_q(query)
|
| 409 |
-
if attn.norm_k is not None:
|
| 410 |
-
key = attn.norm_k(key)
|
| 411 |
-
|
| 412 |
-
# Apply RoPE if needed
|
| 413 |
-
if rotary_freqs_cis is not None:
|
| 414 |
-
query = self.apply_rotary_emb(query, rotary_freqs_cis)
|
| 415 |
-
if not attn.is_cross_attention:
|
| 416 |
-
key = self.apply_rotary_emb(key, rotary_freqs_cis)
|
| 417 |
-
elif rotary_freqs_cis_cross is not None and has_encoder_hidden_state_proj:
|
| 418 |
-
key = self.apply_rotary_emb(key, rotary_freqs_cis_cross)
|
| 419 |
-
|
| 420 |
-
if attn.is_cross_attention and encoder_attention_mask is not None and has_encoder_hidden_state_proj:
|
| 421 |
-
# attention_mask: N x S1
|
| 422 |
-
# encoder_attention_mask: N x S2
|
| 423 |
-
# cross attention 整合attention_mask和encoder_attention_mask
|
| 424 |
-
combined_mask = attention_mask[:, :, None] * encoder_attention_mask[:, None, :]
|
| 425 |
-
attention_mask = torch.where(combined_mask == 1, 0.0, -torch.inf)
|
| 426 |
-
attention_mask = attention_mask[:, None, :, :].expand(-1, attn.heads, -1, -1).to(query.dtype)
|
| 427 |
-
|
| 428 |
-
elif not attn.is_cross_attention and attention_mask is not None:
|
| 429 |
-
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 430 |
-
# scaled_dot_product_attention expects attention_mask shape to be
|
| 431 |
-
# (batch, heads, source_length, target_length)
|
| 432 |
-
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
| 433 |
-
|
| 434 |
-
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 435 |
-
hidden_states = optimized_attention(
|
| 436 |
-
query, key, value, heads=query.shape[1], mask=attention_mask, skip_reshape=True,
|
| 437 |
-
).to(query.dtype)
|
| 438 |
-
|
| 439 |
-
# linear proj
|
| 440 |
-
hidden_states = attn.to_out[0](hidden_states)
|
| 441 |
-
# dropout
|
| 442 |
-
hidden_states = attn.to_out[1](hidden_states)
|
| 443 |
-
|
| 444 |
-
if input_ndim == 4:
|
| 445 |
-
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 446 |
-
|
| 447 |
-
if attn.residual_connection:
|
| 448 |
-
hidden_states = hidden_states + residual
|
| 449 |
-
|
| 450 |
-
hidden_states = hidden_states / attn.rescale_output_factor
|
| 451 |
-
|
| 452 |
-
return hidden_states
|
| 453 |
-
|
| 454 |
-
def val2list(x: list or tuple or any, repeat_time=1) -> list: # type: ignore
|
| 455 |
-
"""Repeat `val` for `repeat_time` times and return the list or val if list/tuple."""
|
| 456 |
-
if isinstance(x, (list, tuple)):
|
| 457 |
-
return list(x)
|
| 458 |
-
return [x for _ in range(repeat_time)]
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
def val2tuple(x: list or tuple or any, min_len: int = 1, idx_repeat: int = -1) -> tuple: # type: ignore
|
| 462 |
-
"""Return tuple with min_len by repeating element at idx_repeat."""
|
| 463 |
-
# convert to list first
|
| 464 |
-
x = val2list(x)
|
| 465 |
-
|
| 466 |
-
# repeat elements if necessary
|
| 467 |
-
if len(x) > 0:
|
| 468 |
-
x[idx_repeat:idx_repeat] = [x[idx_repeat] for _ in range(min_len - len(x))]
|
| 469 |
-
|
| 470 |
-
return tuple(x)
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
def t2i_modulate(x, shift, scale):
|
| 474 |
-
return x * (1 + scale) + shift
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
def get_same_padding(kernel_size: Union[int, Tuple[int, ...]]) -> Union[int, Tuple[int, ...]]:
|
| 478 |
-
if isinstance(kernel_size, tuple):
|
| 479 |
-
return tuple([get_same_padding(ks) for ks in kernel_size])
|
| 480 |
-
else:
|
| 481 |
-
assert kernel_size % 2 > 0, f"kernel size {kernel_size} should be odd number"
|
| 482 |
-
return kernel_size // 2
|
| 483 |
-
|
| 484 |
-
class ConvLayer(nn.Module):
|
| 485 |
-
def __init__(
|
| 486 |
-
self,
|
| 487 |
-
in_dim: int,
|
| 488 |
-
out_dim: int,
|
| 489 |
-
kernel_size=3,
|
| 490 |
-
stride=1,
|
| 491 |
-
dilation=1,
|
| 492 |
-
groups=1,
|
| 493 |
-
padding: Union[int, None] = None,
|
| 494 |
-
use_bias=False,
|
| 495 |
-
norm=None,
|
| 496 |
-
act=None,
|
| 497 |
-
dtype=None, device=None, operations=None
|
| 498 |
-
):
|
| 499 |
-
super().__init__()
|
| 500 |
-
if padding is None:
|
| 501 |
-
padding = get_same_padding(kernel_size)
|
| 502 |
-
padding *= dilation
|
| 503 |
-
|
| 504 |
-
self.in_dim = in_dim
|
| 505 |
-
self.out_dim = out_dim
|
| 506 |
-
self.kernel_size = kernel_size
|
| 507 |
-
self.stride = stride
|
| 508 |
-
self.dilation = dilation
|
| 509 |
-
self.groups = groups
|
| 510 |
-
self.padding = padding
|
| 511 |
-
self.use_bias = use_bias
|
| 512 |
-
|
| 513 |
-
self.conv = operations.Conv1d(
|
| 514 |
-
in_dim,
|
| 515 |
-
out_dim,
|
| 516 |
-
kernel_size=kernel_size,
|
| 517 |
-
stride=stride,
|
| 518 |
-
padding=padding,
|
| 519 |
-
dilation=dilation,
|
| 520 |
-
groups=groups,
|
| 521 |
-
bias=use_bias,
|
| 522 |
-
device=device,
|
| 523 |
-
dtype=dtype
|
| 524 |
-
)
|
| 525 |
-
if norm is not None:
|
| 526 |
-
self.norm = operations.RMSNorm(out_dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 527 |
-
else:
|
| 528 |
-
self.norm = None
|
| 529 |
-
if act is not None:
|
| 530 |
-
self.act = nn.SiLU(inplace=True)
|
| 531 |
-
else:
|
| 532 |
-
self.act = None
|
| 533 |
-
|
| 534 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 535 |
-
x = self.conv(x)
|
| 536 |
-
if self.norm:
|
| 537 |
-
x = self.norm(x)
|
| 538 |
-
if self.act:
|
| 539 |
-
x = self.act(x)
|
| 540 |
-
return x
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
class GLUMBConv(nn.Module):
|
| 544 |
-
def __init__(
|
| 545 |
-
self,
|
| 546 |
-
in_features: int,
|
| 547 |
-
hidden_features: int,
|
| 548 |
-
out_feature=None,
|
| 549 |
-
kernel_size=3,
|
| 550 |
-
stride=1,
|
| 551 |
-
padding: Union[int, None] = None,
|
| 552 |
-
use_bias=False,
|
| 553 |
-
norm=(None, None, None),
|
| 554 |
-
act=("silu", "silu", None),
|
| 555 |
-
dilation=1,
|
| 556 |
-
dtype=None, device=None, operations=None
|
| 557 |
-
):
|
| 558 |
-
out_feature = out_feature or in_features
|
| 559 |
-
super().__init__()
|
| 560 |
-
use_bias = val2tuple(use_bias, 3)
|
| 561 |
-
norm = val2tuple(norm, 3)
|
| 562 |
-
act = val2tuple(act, 3)
|
| 563 |
-
|
| 564 |
-
self.glu_act = nn.SiLU(inplace=False)
|
| 565 |
-
self.inverted_conv = ConvLayer(
|
| 566 |
-
in_features,
|
| 567 |
-
hidden_features * 2,
|
| 568 |
-
1,
|
| 569 |
-
use_bias=use_bias[0],
|
| 570 |
-
norm=norm[0],
|
| 571 |
-
act=act[0],
|
| 572 |
-
dtype=dtype,
|
| 573 |
-
device=device,
|
| 574 |
-
operations=operations,
|
| 575 |
-
)
|
| 576 |
-
self.depth_conv = ConvLayer(
|
| 577 |
-
hidden_features * 2,
|
| 578 |
-
hidden_features * 2,
|
| 579 |
-
kernel_size,
|
| 580 |
-
stride=stride,
|
| 581 |
-
groups=hidden_features * 2,
|
| 582 |
-
padding=padding,
|
| 583 |
-
use_bias=use_bias[1],
|
| 584 |
-
norm=norm[1],
|
| 585 |
-
act=None,
|
| 586 |
-
dilation=dilation,
|
| 587 |
-
dtype=dtype,
|
| 588 |
-
device=device,
|
| 589 |
-
operations=operations,
|
| 590 |
-
)
|
| 591 |
-
self.point_conv = ConvLayer(
|
| 592 |
-
hidden_features,
|
| 593 |
-
out_feature,
|
| 594 |
-
1,
|
| 595 |
-
use_bias=use_bias[2],
|
| 596 |
-
norm=norm[2],
|
| 597 |
-
act=act[2],
|
| 598 |
-
dtype=dtype,
|
| 599 |
-
device=device,
|
| 600 |
-
operations=operations,
|
| 601 |
-
)
|
| 602 |
-
|
| 603 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 604 |
-
x = x.transpose(1, 2)
|
| 605 |
-
x = self.inverted_conv(x)
|
| 606 |
-
x = self.depth_conv(x)
|
| 607 |
-
|
| 608 |
-
x, gate = torch.chunk(x, 2, dim=1)
|
| 609 |
-
gate = self.glu_act(gate)
|
| 610 |
-
x = x * gate
|
| 611 |
-
|
| 612 |
-
x = self.point_conv(x)
|
| 613 |
-
x = x.transpose(1, 2)
|
| 614 |
-
|
| 615 |
-
return x
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
class LinearTransformerBlock(nn.Module):
|
| 619 |
-
"""
|
| 620 |
-
A Sana block with global shared adaptive layer norm (adaLN-single) conditioning.
|
| 621 |
-
"""
|
| 622 |
-
def __init__(
|
| 623 |
-
self,
|
| 624 |
-
dim,
|
| 625 |
-
num_attention_heads,
|
| 626 |
-
attention_head_dim,
|
| 627 |
-
use_adaln_single=True,
|
| 628 |
-
cross_attention_dim=None,
|
| 629 |
-
added_kv_proj_dim=None,
|
| 630 |
-
context_pre_only=False,
|
| 631 |
-
mlp_ratio=4.0,
|
| 632 |
-
add_cross_attention=False,
|
| 633 |
-
add_cross_attention_dim=None,
|
| 634 |
-
qk_norm=None,
|
| 635 |
-
dtype=None, device=None, operations=None
|
| 636 |
-
):
|
| 637 |
-
super().__init__()
|
| 638 |
-
|
| 639 |
-
self.norm1 = operations.RMSNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 640 |
-
self.attn = Attention(
|
| 641 |
-
query_dim=dim,
|
| 642 |
-
cross_attention_dim=cross_attention_dim,
|
| 643 |
-
added_kv_proj_dim=added_kv_proj_dim,
|
| 644 |
-
dim_head=attention_head_dim,
|
| 645 |
-
heads=num_attention_heads,
|
| 646 |
-
out_dim=dim,
|
| 647 |
-
bias=True,
|
| 648 |
-
qk_norm=qk_norm,
|
| 649 |
-
processor=CustomLiteLAProcessor2_0(),
|
| 650 |
-
dtype=dtype,
|
| 651 |
-
device=device,
|
| 652 |
-
operations=operations,
|
| 653 |
-
)
|
| 654 |
-
|
| 655 |
-
self.add_cross_attention = add_cross_attention
|
| 656 |
-
self.context_pre_only = context_pre_only
|
| 657 |
-
|
| 658 |
-
if add_cross_attention and add_cross_attention_dim is not None:
|
| 659 |
-
self.cross_attn = Attention(
|
| 660 |
-
query_dim=dim,
|
| 661 |
-
cross_attention_dim=add_cross_attention_dim,
|
| 662 |
-
added_kv_proj_dim=add_cross_attention_dim,
|
| 663 |
-
dim_head=attention_head_dim,
|
| 664 |
-
heads=num_attention_heads,
|
| 665 |
-
out_dim=dim,
|
| 666 |
-
context_pre_only=context_pre_only,
|
| 667 |
-
bias=True,
|
| 668 |
-
qk_norm=qk_norm,
|
| 669 |
-
processor=CustomerAttnProcessor2_0(),
|
| 670 |
-
dtype=dtype,
|
| 671 |
-
device=device,
|
| 672 |
-
operations=operations,
|
| 673 |
-
)
|
| 674 |
-
|
| 675 |
-
self.norm2 = operations.RMSNorm(dim, 1e-06, elementwise_affine=False)
|
| 676 |
-
|
| 677 |
-
self.ff = GLUMBConv(
|
| 678 |
-
in_features=dim,
|
| 679 |
-
hidden_features=int(dim * mlp_ratio),
|
| 680 |
-
use_bias=(True, True, False),
|
| 681 |
-
norm=(None, None, None),
|
| 682 |
-
act=("silu", "silu", None),
|
| 683 |
-
dtype=dtype,
|
| 684 |
-
device=device,
|
| 685 |
-
operations=operations,
|
| 686 |
-
)
|
| 687 |
-
self.use_adaln_single = use_adaln_single
|
| 688 |
-
if use_adaln_single:
|
| 689 |
-
self.scale_shift_table = nn.Parameter(torch.empty(6, dim, dtype=dtype, device=device))
|
| 690 |
-
|
| 691 |
-
def forward(
|
| 692 |
-
self,
|
| 693 |
-
hidden_states: torch.FloatTensor,
|
| 694 |
-
encoder_hidden_states: torch.FloatTensor = None,
|
| 695 |
-
attention_mask: torch.FloatTensor = None,
|
| 696 |
-
encoder_attention_mask: torch.FloatTensor = None,
|
| 697 |
-
rotary_freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]] = None,
|
| 698 |
-
rotary_freqs_cis_cross: Union[torch.Tensor, Tuple[torch.Tensor]] = None,
|
| 699 |
-
temb: torch.FloatTensor = None,
|
| 700 |
-
):
|
| 701 |
-
|
| 702 |
-
N = hidden_states.shape[0]
|
| 703 |
-
|
| 704 |
-
# step 1: AdaLN single
|
| 705 |
-
if self.use_adaln_single:
|
| 706 |
-
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 707 |
-
comfy.model_management.cast_to(self.scale_shift_table[None], dtype=temb.dtype, device=temb.device) + temb.reshape(N, 6, -1)
|
| 708 |
-
).chunk(6, dim=1)
|
| 709 |
-
|
| 710 |
-
norm_hidden_states = self.norm1(hidden_states)
|
| 711 |
-
if self.use_adaln_single:
|
| 712 |
-
norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
|
| 713 |
-
|
| 714 |
-
# step 2: attention
|
| 715 |
-
if not self.add_cross_attention:
|
| 716 |
-
attn_output, encoder_hidden_states = self.attn(
|
| 717 |
-
hidden_states=norm_hidden_states,
|
| 718 |
-
attention_mask=attention_mask,
|
| 719 |
-
encoder_hidden_states=encoder_hidden_states,
|
| 720 |
-
encoder_attention_mask=encoder_attention_mask,
|
| 721 |
-
rotary_freqs_cis=rotary_freqs_cis,
|
| 722 |
-
rotary_freqs_cis_cross=rotary_freqs_cis_cross,
|
| 723 |
-
)
|
| 724 |
-
else:
|
| 725 |
-
attn_output, _ = self.attn(
|
| 726 |
-
hidden_states=norm_hidden_states,
|
| 727 |
-
attention_mask=attention_mask,
|
| 728 |
-
encoder_hidden_states=None,
|
| 729 |
-
encoder_attention_mask=None,
|
| 730 |
-
rotary_freqs_cis=rotary_freqs_cis,
|
| 731 |
-
rotary_freqs_cis_cross=None,
|
| 732 |
-
)
|
| 733 |
-
|
| 734 |
-
if self.use_adaln_single:
|
| 735 |
-
attn_output = gate_msa * attn_output
|
| 736 |
-
hidden_states = attn_output + hidden_states
|
| 737 |
-
|
| 738 |
-
if self.add_cross_attention:
|
| 739 |
-
attn_output = self.cross_attn(
|
| 740 |
-
hidden_states=hidden_states,
|
| 741 |
-
attention_mask=attention_mask,
|
| 742 |
-
encoder_hidden_states=encoder_hidden_states,
|
| 743 |
-
encoder_attention_mask=encoder_attention_mask,
|
| 744 |
-
rotary_freqs_cis=rotary_freqs_cis,
|
| 745 |
-
rotary_freqs_cis_cross=rotary_freqs_cis_cross,
|
| 746 |
-
)
|
| 747 |
-
hidden_states = attn_output + hidden_states
|
| 748 |
-
|
| 749 |
-
# step 3: add norm
|
| 750 |
-
norm_hidden_states = self.norm2(hidden_states)
|
| 751 |
-
if self.use_adaln_single:
|
| 752 |
-
norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
|
| 753 |
-
|
| 754 |
-
# step 4: feed forward
|
| 755 |
-
ff_output = self.ff(norm_hidden_states)
|
| 756 |
-
if self.use_adaln_single:
|
| 757 |
-
ff_output = gate_mlp * ff_output
|
| 758 |
-
|
| 759 |
-
hidden_states = hidden_states + ff_output
|
| 760 |
-
|
| 761 |
-
return hidden_states
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1,1067 +0,0 @@
|
|
| 1 |
-
# Original from: https://github.com/ace-step/ACE-Step/blob/main/models/lyrics_utils/lyric_encoder.py
|
| 2 |
-
from typing import Optional, Tuple, Union
|
| 3 |
-
import math
|
| 4 |
-
import torch
|
| 5 |
-
from torch import nn
|
| 6 |
-
|
| 7 |
-
import comfy.model_management
|
| 8 |
-
|
| 9 |
-
class ConvolutionModule(nn.Module):
|
| 10 |
-
"""ConvolutionModule in Conformer model."""
|
| 11 |
-
|
| 12 |
-
def __init__(self,
|
| 13 |
-
channels: int,
|
| 14 |
-
kernel_size: int = 15,
|
| 15 |
-
activation: nn.Module = nn.ReLU(),
|
| 16 |
-
norm: str = "batch_norm",
|
| 17 |
-
causal: bool = False,
|
| 18 |
-
bias: bool = True,
|
| 19 |
-
dtype=None, device=None, operations=None):
|
| 20 |
-
"""Construct an ConvolutionModule object.
|
| 21 |
-
Args:
|
| 22 |
-
channels (int): The number of channels of conv layers.
|
| 23 |
-
kernel_size (int): Kernel size of conv layers.
|
| 24 |
-
causal (int): Whether use causal convolution or not
|
| 25 |
-
"""
|
| 26 |
-
super().__init__()
|
| 27 |
-
|
| 28 |
-
self.pointwise_conv1 = operations.Conv1d(
|
| 29 |
-
channels,
|
| 30 |
-
2 * channels,
|
| 31 |
-
kernel_size=1,
|
| 32 |
-
stride=1,
|
| 33 |
-
padding=0,
|
| 34 |
-
bias=bias,
|
| 35 |
-
dtype=dtype, device=device
|
| 36 |
-
)
|
| 37 |
-
# self.lorder is used to distinguish if it's a causal convolution,
|
| 38 |
-
# if self.lorder > 0: it's a causal convolution, the input will be
|
| 39 |
-
# padded with self.lorder frames on the left in forward.
|
| 40 |
-
# else: it's a symmetrical convolution
|
| 41 |
-
if causal:
|
| 42 |
-
padding = 0
|
| 43 |
-
self.lorder = kernel_size - 1
|
| 44 |
-
else:
|
| 45 |
-
# kernel_size should be an odd number for none causal convolution
|
| 46 |
-
assert (kernel_size - 1) % 2 == 0
|
| 47 |
-
padding = (kernel_size - 1) // 2
|
| 48 |
-
self.lorder = 0
|
| 49 |
-
self.depthwise_conv = operations.Conv1d(
|
| 50 |
-
channels,
|
| 51 |
-
channels,
|
| 52 |
-
kernel_size,
|
| 53 |
-
stride=1,
|
| 54 |
-
padding=padding,
|
| 55 |
-
groups=channels,
|
| 56 |
-
bias=bias,
|
| 57 |
-
dtype=dtype, device=device
|
| 58 |
-
)
|
| 59 |
-
|
| 60 |
-
assert norm in ['batch_norm', 'layer_norm']
|
| 61 |
-
if norm == "batch_norm":
|
| 62 |
-
self.use_layer_norm = False
|
| 63 |
-
self.norm = nn.BatchNorm1d(channels)
|
| 64 |
-
else:
|
| 65 |
-
self.use_layer_norm = True
|
| 66 |
-
self.norm = operations.LayerNorm(channels, dtype=dtype, device=device)
|
| 67 |
-
|
| 68 |
-
self.pointwise_conv2 = operations.Conv1d(
|
| 69 |
-
channels,
|
| 70 |
-
channels,
|
| 71 |
-
kernel_size=1,
|
| 72 |
-
stride=1,
|
| 73 |
-
padding=0,
|
| 74 |
-
bias=bias,
|
| 75 |
-
dtype=dtype, device=device
|
| 76 |
-
)
|
| 77 |
-
self.activation = activation
|
| 78 |
-
|
| 79 |
-
def forward(
|
| 80 |
-
self,
|
| 81 |
-
x: torch.Tensor,
|
| 82 |
-
mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
|
| 83 |
-
cache: torch.Tensor = torch.zeros((0, 0, 0)),
|
| 84 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 85 |
-
"""Compute convolution module.
|
| 86 |
-
Args:
|
| 87 |
-
x (torch.Tensor): Input tensor (#batch, time, channels).
|
| 88 |
-
mask_pad (torch.Tensor): used for batch padding (#batch, 1, time),
|
| 89 |
-
(0, 0, 0) means fake mask.
|
| 90 |
-
cache (torch.Tensor): left context cache, it is only
|
| 91 |
-
used in causal convolution (#batch, channels, cache_t),
|
| 92 |
-
(0, 0, 0) meas fake cache.
|
| 93 |
-
Returns:
|
| 94 |
-
torch.Tensor: Output tensor (#batch, time, channels).
|
| 95 |
-
"""
|
| 96 |
-
# exchange the temporal dimension and the feature dimension
|
| 97 |
-
x = x.transpose(1, 2) # (#batch, channels, time)
|
| 98 |
-
|
| 99 |
-
# mask batch padding
|
| 100 |
-
if mask_pad.size(2) > 0: # time > 0
|
| 101 |
-
x.masked_fill_(~mask_pad, 0.0)
|
| 102 |
-
|
| 103 |
-
if self.lorder > 0:
|
| 104 |
-
if cache.size(2) == 0: # cache_t == 0
|
| 105 |
-
x = nn.functional.pad(x, (self.lorder, 0), 'constant', 0.0)
|
| 106 |
-
else:
|
| 107 |
-
assert cache.size(0) == x.size(0) # equal batch
|
| 108 |
-
assert cache.size(1) == x.size(1) # equal channel
|
| 109 |
-
x = torch.cat((cache, x), dim=2)
|
| 110 |
-
assert (x.size(2) > self.lorder)
|
| 111 |
-
new_cache = x[:, :, -self.lorder:]
|
| 112 |
-
else:
|
| 113 |
-
# It's better we just return None if no cache is required,
|
| 114 |
-
# However, for JIT export, here we just fake one tensor instead of
|
| 115 |
-
# None.
|
| 116 |
-
new_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
|
| 117 |
-
|
| 118 |
-
# GLU mechanism
|
| 119 |
-
x = self.pointwise_conv1(x) # (batch, 2*channel, dim)
|
| 120 |
-
x = nn.functional.glu(x, dim=1) # (batch, channel, dim)
|
| 121 |
-
|
| 122 |
-
# 1D Depthwise Conv
|
| 123 |
-
x = self.depthwise_conv(x)
|
| 124 |
-
if self.use_layer_norm:
|
| 125 |
-
x = x.transpose(1, 2)
|
| 126 |
-
x = self.activation(self.norm(x))
|
| 127 |
-
if self.use_layer_norm:
|
| 128 |
-
x = x.transpose(1, 2)
|
| 129 |
-
x = self.pointwise_conv2(x)
|
| 130 |
-
# mask batch padding
|
| 131 |
-
if mask_pad.size(2) > 0: # time > 0
|
| 132 |
-
x.masked_fill_(~mask_pad, 0.0)
|
| 133 |
-
|
| 134 |
-
return x.transpose(1, 2), new_cache
|
| 135 |
-
|
| 136 |
-
class PositionwiseFeedForward(torch.nn.Module):
|
| 137 |
-
"""Positionwise feed forward layer.
|
| 138 |
-
|
| 139 |
-
FeedForward are appied on each position of the sequence.
|
| 140 |
-
The output dim is same with the input dim.
|
| 141 |
-
|
| 142 |
-
Args:
|
| 143 |
-
idim (int): Input dimenstion.
|
| 144 |
-
hidden_units (int): The number of hidden units.
|
| 145 |
-
dropout_rate (float): Dropout rate.
|
| 146 |
-
activation (torch.nn.Module): Activation function
|
| 147 |
-
"""
|
| 148 |
-
|
| 149 |
-
def __init__(
|
| 150 |
-
self,
|
| 151 |
-
idim: int,
|
| 152 |
-
hidden_units: int,
|
| 153 |
-
dropout_rate: float,
|
| 154 |
-
activation: torch.nn.Module = torch.nn.ReLU(),
|
| 155 |
-
dtype=None, device=None, operations=None
|
| 156 |
-
):
|
| 157 |
-
"""Construct a PositionwiseFeedForward object."""
|
| 158 |
-
super(PositionwiseFeedForward, self).__init__()
|
| 159 |
-
self.w_1 = operations.Linear(idim, hidden_units, dtype=dtype, device=device)
|
| 160 |
-
self.activation = activation
|
| 161 |
-
self.dropout = torch.nn.Dropout(dropout_rate)
|
| 162 |
-
self.w_2 = operations.Linear(hidden_units, idim, dtype=dtype, device=device)
|
| 163 |
-
|
| 164 |
-
def forward(self, xs: torch.Tensor) -> torch.Tensor:
|
| 165 |
-
"""Forward function.
|
| 166 |
-
|
| 167 |
-
Args:
|
| 168 |
-
xs: input tensor (B, L, D)
|
| 169 |
-
Returns:
|
| 170 |
-
output tensor, (B, L, D)
|
| 171 |
-
"""
|
| 172 |
-
return self.w_2(self.dropout(self.activation(self.w_1(xs))))
|
| 173 |
-
|
| 174 |
-
class Swish(torch.nn.Module):
|
| 175 |
-
"""Construct an Swish object."""
|
| 176 |
-
|
| 177 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 178 |
-
"""Return Swish activation function."""
|
| 179 |
-
return x * torch.sigmoid(x)
|
| 180 |
-
|
| 181 |
-
class MultiHeadedAttention(nn.Module):
|
| 182 |
-
"""Multi-Head Attention layer.
|
| 183 |
-
|
| 184 |
-
Args:
|
| 185 |
-
n_head (int): The number of heads.
|
| 186 |
-
n_feat (int): The number of features.
|
| 187 |
-
dropout_rate (float): Dropout rate.
|
| 188 |
-
|
| 189 |
-
"""
|
| 190 |
-
|
| 191 |
-
def __init__(self,
|
| 192 |
-
n_head: int,
|
| 193 |
-
n_feat: int,
|
| 194 |
-
dropout_rate: float,
|
| 195 |
-
key_bias: bool = True,
|
| 196 |
-
dtype=None, device=None, operations=None):
|
| 197 |
-
"""Construct an MultiHeadedAttention object."""
|
| 198 |
-
super().__init__()
|
| 199 |
-
assert n_feat % n_head == 0
|
| 200 |
-
# We assume d_v always equals d_k
|
| 201 |
-
self.d_k = n_feat // n_head
|
| 202 |
-
self.h = n_head
|
| 203 |
-
self.linear_q = operations.Linear(n_feat, n_feat, dtype=dtype, device=device)
|
| 204 |
-
self.linear_k = operations.Linear(n_feat, n_feat, bias=key_bias, dtype=dtype, device=device)
|
| 205 |
-
self.linear_v = operations.Linear(n_feat, n_feat, dtype=dtype, device=device)
|
| 206 |
-
self.linear_out = operations.Linear(n_feat, n_feat, dtype=dtype, device=device)
|
| 207 |
-
self.dropout = nn.Dropout(p=dropout_rate)
|
| 208 |
-
|
| 209 |
-
def forward_qkv(
|
| 210 |
-
self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor
|
| 211 |
-
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 212 |
-
"""Transform query, key and value.
|
| 213 |
-
|
| 214 |
-
Args:
|
| 215 |
-
query (torch.Tensor): Query tensor (#batch, time1, size).
|
| 216 |
-
key (torch.Tensor): Key tensor (#batch, time2, size).
|
| 217 |
-
value (torch.Tensor): Value tensor (#batch, time2, size).
|
| 218 |
-
|
| 219 |
-
Returns:
|
| 220 |
-
torch.Tensor: Transformed query tensor, size
|
| 221 |
-
(#batch, n_head, time1, d_k).
|
| 222 |
-
torch.Tensor: Transformed key tensor, size
|
| 223 |
-
(#batch, n_head, time2, d_k).
|
| 224 |
-
torch.Tensor: Transformed value tensor, size
|
| 225 |
-
(#batch, n_head, time2, d_k).
|
| 226 |
-
|
| 227 |
-
"""
|
| 228 |
-
n_batch = query.size(0)
|
| 229 |
-
q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k)
|
| 230 |
-
k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k)
|
| 231 |
-
v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k)
|
| 232 |
-
q = q.transpose(1, 2) # (batch, head, time1, d_k)
|
| 233 |
-
k = k.transpose(1, 2) # (batch, head, time2, d_k)
|
| 234 |
-
v = v.transpose(1, 2) # (batch, head, time2, d_k)
|
| 235 |
-
return q, k, v
|
| 236 |
-
|
| 237 |
-
def forward_attention(
|
| 238 |
-
self,
|
| 239 |
-
value: torch.Tensor,
|
| 240 |
-
scores: torch.Tensor,
|
| 241 |
-
mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool)
|
| 242 |
-
) -> torch.Tensor:
|
| 243 |
-
"""Compute attention context vector.
|
| 244 |
-
|
| 245 |
-
Args:
|
| 246 |
-
value (torch.Tensor): Transformed value, size
|
| 247 |
-
(#batch, n_head, time2, d_k).
|
| 248 |
-
scores (torch.Tensor): Attention score, size
|
| 249 |
-
(#batch, n_head, time1, time2).
|
| 250 |
-
mask (torch.Tensor): Mask, size (#batch, 1, time2) or
|
| 251 |
-
(#batch, time1, time2), (0, 0, 0) means fake mask.
|
| 252 |
-
|
| 253 |
-
Returns:
|
| 254 |
-
torch.Tensor: Transformed value (#batch, time1, d_model)
|
| 255 |
-
weighted by the attention score (#batch, time1, time2).
|
| 256 |
-
|
| 257 |
-
"""
|
| 258 |
-
n_batch = value.size(0)
|
| 259 |
-
|
| 260 |
-
if mask is not None and mask.size(2) > 0: # time2 > 0
|
| 261 |
-
mask = mask.unsqueeze(1).eq(0) # (batch, 1, *, time2)
|
| 262 |
-
# For last chunk, time2 might be larger than scores.size(-1)
|
| 263 |
-
mask = mask[:, :, :, :scores.size(-1)] # (batch, 1, *, time2)
|
| 264 |
-
scores = scores.masked_fill(mask, -float('inf'))
|
| 265 |
-
attn = torch.softmax(scores, dim=-1).masked_fill(
|
| 266 |
-
mask, 0.0) # (batch, head, time1, time2)
|
| 267 |
-
|
| 268 |
-
else:
|
| 269 |
-
attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2)
|
| 270 |
-
|
| 271 |
-
p_attn = self.dropout(attn)
|
| 272 |
-
x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)
|
| 273 |
-
x = (x.transpose(1, 2).contiguous().view(n_batch, -1,
|
| 274 |
-
self.h * self.d_k)
|
| 275 |
-
) # (batch, time1, d_model)
|
| 276 |
-
|
| 277 |
-
return self.linear_out(x) # (batch, time1, d_model)
|
| 278 |
-
|
| 279 |
-
def forward(
|
| 280 |
-
self,
|
| 281 |
-
query: torch.Tensor,
|
| 282 |
-
key: torch.Tensor,
|
| 283 |
-
value: torch.Tensor,
|
| 284 |
-
mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
|
| 285 |
-
pos_emb: torch.Tensor = torch.empty(0),
|
| 286 |
-
cache: torch.Tensor = torch.zeros((0, 0, 0, 0))
|
| 287 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 288 |
-
"""Compute scaled dot product attention.
|
| 289 |
-
|
| 290 |
-
Args:
|
| 291 |
-
query (torch.Tensor): Query tensor (#batch, time1, size).
|
| 292 |
-
key (torch.Tensor): Key tensor (#batch, time2, size).
|
| 293 |
-
value (torch.Tensor): Value tensor (#batch, time2, size).
|
| 294 |
-
mask (torch.Tensor): Mask tensor (#batch, 1, time2) or
|
| 295 |
-
(#batch, time1, time2).
|
| 296 |
-
1.When applying cross attention between decoder and encoder,
|
| 297 |
-
the batch padding mask for input is in (#batch, 1, T) shape.
|
| 298 |
-
2.When applying self attention of encoder,
|
| 299 |
-
the mask is in (#batch, T, T) shape.
|
| 300 |
-
3.When applying self attention of decoder,
|
| 301 |
-
the mask is in (#batch, L, L) shape.
|
| 302 |
-
4.If the different position in decoder see different block
|
| 303 |
-
of the encoder, such as Mocha, the passed in mask could be
|
| 304 |
-
in (#batch, L, T) shape. But there is no such case in current
|
| 305 |
-
CosyVoice.
|
| 306 |
-
cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2),
|
| 307 |
-
where `cache_t == chunk_size * num_decoding_left_chunks`
|
| 308 |
-
and `head * d_k == size`
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
Returns:
|
| 312 |
-
torch.Tensor: Output tensor (#batch, time1, d_model).
|
| 313 |
-
torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2)
|
| 314 |
-
where `cache_t == chunk_size * num_decoding_left_chunks`
|
| 315 |
-
and `head * d_k == size`
|
| 316 |
-
|
| 317 |
-
"""
|
| 318 |
-
q, k, v = self.forward_qkv(query, key, value)
|
| 319 |
-
if cache.size(0) > 0:
|
| 320 |
-
key_cache, value_cache = torch.split(cache,
|
| 321 |
-
cache.size(-1) // 2,
|
| 322 |
-
dim=-1)
|
| 323 |
-
k = torch.cat([key_cache, k], dim=2)
|
| 324 |
-
v = torch.cat([value_cache, v], dim=2)
|
| 325 |
-
new_cache = torch.cat((k, v), dim=-1)
|
| 326 |
-
|
| 327 |
-
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
|
| 328 |
-
return self.forward_attention(v, scores, mask), new_cache
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
class RelPositionMultiHeadedAttention(MultiHeadedAttention):
|
| 332 |
-
"""Multi-Head Attention layer with relative position encoding.
|
| 333 |
-
Paper: https://arxiv.org/abs/1901.02860
|
| 334 |
-
Args:
|
| 335 |
-
n_head (int): The number of heads.
|
| 336 |
-
n_feat (int): The number of features.
|
| 337 |
-
dropout_rate (float): Dropout rate.
|
| 338 |
-
"""
|
| 339 |
-
|
| 340 |
-
def __init__(self,
|
| 341 |
-
n_head: int,
|
| 342 |
-
n_feat: int,
|
| 343 |
-
dropout_rate: float,
|
| 344 |
-
key_bias: bool = True,
|
| 345 |
-
dtype=None, device=None, operations=None):
|
| 346 |
-
"""Construct an RelPositionMultiHeadedAttention object."""
|
| 347 |
-
super().__init__(n_head, n_feat, dropout_rate, key_bias, dtype=dtype, device=device, operations=operations)
|
| 348 |
-
# linear transformation for positional encoding
|
| 349 |
-
self.linear_pos = operations.Linear(n_feat, n_feat, bias=False, dtype=dtype, device=device)
|
| 350 |
-
# these two learnable bias are used in matrix c and matrix d
|
| 351 |
-
# as described in https://arxiv.org/abs/1901.02860 Section 3.3
|
| 352 |
-
self.pos_bias_u = nn.Parameter(torch.empty(self.h, self.d_k, dtype=dtype, device=device))
|
| 353 |
-
self.pos_bias_v = nn.Parameter(torch.empty(self.h, self.d_k, dtype=dtype, device=device))
|
| 354 |
-
# torch.nn.init.xavier_uniform_(self.pos_bias_u)
|
| 355 |
-
# torch.nn.init.xavier_uniform_(self.pos_bias_v)
|
| 356 |
-
|
| 357 |
-
def rel_shift(self, x: torch.Tensor) -> torch.Tensor:
|
| 358 |
-
"""Compute relative positional encoding.
|
| 359 |
-
|
| 360 |
-
Args:
|
| 361 |
-
x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1).
|
| 362 |
-
time1 means the length of query vector.
|
| 363 |
-
|
| 364 |
-
Returns:
|
| 365 |
-
torch.Tensor: Output tensor.
|
| 366 |
-
|
| 367 |
-
"""
|
| 368 |
-
zero_pad = torch.zeros((x.size()[0], x.size()[1], x.size()[2], 1),
|
| 369 |
-
device=x.device,
|
| 370 |
-
dtype=x.dtype)
|
| 371 |
-
x_padded = torch.cat([zero_pad, x], dim=-1)
|
| 372 |
-
|
| 373 |
-
x_padded = x_padded.view(x.size()[0],
|
| 374 |
-
x.size()[1],
|
| 375 |
-
x.size(3) + 1, x.size(2))
|
| 376 |
-
x = x_padded[:, :, 1:].view_as(x)[
|
| 377 |
-
:, :, :, : x.size(-1) // 2 + 1
|
| 378 |
-
] # only keep the positions from 0 to time2
|
| 379 |
-
return x
|
| 380 |
-
|
| 381 |
-
def forward(
|
| 382 |
-
self,
|
| 383 |
-
query: torch.Tensor,
|
| 384 |
-
key: torch.Tensor,
|
| 385 |
-
value: torch.Tensor,
|
| 386 |
-
mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
|
| 387 |
-
pos_emb: torch.Tensor = torch.empty(0),
|
| 388 |
-
cache: torch.Tensor = torch.zeros((0, 0, 0, 0))
|
| 389 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 390 |
-
"""Compute 'Scaled Dot Product Attention' with rel. positional encoding.
|
| 391 |
-
Args:
|
| 392 |
-
query (torch.Tensor): Query tensor (#batch, time1, size).
|
| 393 |
-
key (torch.Tensor): Key tensor (#batch, time2, size).
|
| 394 |
-
value (torch.Tensor): Value tensor (#batch, time2, size).
|
| 395 |
-
mask (torch.Tensor): Mask tensor (#batch, 1, time2) or
|
| 396 |
-
(#batch, time1, time2), (0, 0, 0) means fake mask.
|
| 397 |
-
pos_emb (torch.Tensor): Positional embedding tensor
|
| 398 |
-
(#batch, time2, size).
|
| 399 |
-
cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2),
|
| 400 |
-
where `cache_t == chunk_size * num_decoding_left_chunks`
|
| 401 |
-
and `head * d_k == size`
|
| 402 |
-
Returns:
|
| 403 |
-
torch.Tensor: Output tensor (#batch, time1, d_model).
|
| 404 |
-
torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2)
|
| 405 |
-
where `cache_t == chunk_size * num_decoding_left_chunks`
|
| 406 |
-
and `head * d_k == size`
|
| 407 |
-
"""
|
| 408 |
-
q, k, v = self.forward_qkv(query, key, value)
|
| 409 |
-
q = q.transpose(1, 2) # (batch, time1, head, d_k)
|
| 410 |
-
|
| 411 |
-
if cache.size(0) > 0:
|
| 412 |
-
key_cache, value_cache = torch.split(cache,
|
| 413 |
-
cache.size(-1) // 2,
|
| 414 |
-
dim=-1)
|
| 415 |
-
k = torch.cat([key_cache, k], dim=2)
|
| 416 |
-
v = torch.cat([value_cache, v], dim=2)
|
| 417 |
-
# NOTE(xcsong): We do cache slicing in encoder.forward_chunk, since it's
|
| 418 |
-
# non-trivial to calculate `next_cache_start` here.
|
| 419 |
-
new_cache = torch.cat((k, v), dim=-1)
|
| 420 |
-
|
| 421 |
-
n_batch_pos = pos_emb.size(0)
|
| 422 |
-
p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)
|
| 423 |
-
p = p.transpose(1, 2) # (batch, head, time1, d_k)
|
| 424 |
-
|
| 425 |
-
# (batch, head, time1, d_k)
|
| 426 |
-
q_with_bias_u = (q + comfy.model_management.cast_to(self.pos_bias_u, dtype=q.dtype, device=q.device)).transpose(1, 2)
|
| 427 |
-
# (batch, head, time1, d_k)
|
| 428 |
-
q_with_bias_v = (q + comfy.model_management.cast_to(self.pos_bias_v, dtype=q.dtype, device=q.device)).transpose(1, 2)
|
| 429 |
-
|
| 430 |
-
# compute attention score
|
| 431 |
-
# first compute matrix a and matrix c
|
| 432 |
-
# as described in https://arxiv.org/abs/1901.02860 Section 3.3
|
| 433 |
-
# (batch, head, time1, time2)
|
| 434 |
-
matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))
|
| 435 |
-
|
| 436 |
-
# compute matrix b and matrix d
|
| 437 |
-
# (batch, head, time1, time2)
|
| 438 |
-
matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
|
| 439 |
-
# NOTE(Xiang Lyu): Keep rel_shift since espnet rel_pos_emb is used
|
| 440 |
-
if matrix_ac.shape != matrix_bd.shape:
|
| 441 |
-
matrix_bd = self.rel_shift(matrix_bd)
|
| 442 |
-
|
| 443 |
-
scores = (matrix_ac + matrix_bd) / math.sqrt(
|
| 444 |
-
self.d_k) # (batch, head, time1, time2)
|
| 445 |
-
|
| 446 |
-
return self.forward_attention(v, scores, mask), new_cache
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
def subsequent_mask(
|
| 451 |
-
size: int,
|
| 452 |
-
device: torch.device = torch.device("cpu"),
|
| 453 |
-
) -> torch.Tensor:
|
| 454 |
-
"""Create mask for subsequent steps (size, size).
|
| 455 |
-
|
| 456 |
-
This mask is used only in decoder which works in an auto-regressive mode.
|
| 457 |
-
This means the current step could only do attention with its left steps.
|
| 458 |
-
|
| 459 |
-
In encoder, fully attention is used when streaming is not necessary and
|
| 460 |
-
the sequence is not long. In this case, no attention mask is needed.
|
| 461 |
-
|
| 462 |
-
When streaming is need, chunk-based attention is used in encoder. See
|
| 463 |
-
subsequent_chunk_mask for the chunk-based attention mask.
|
| 464 |
-
|
| 465 |
-
Args:
|
| 466 |
-
size (int): size of mask
|
| 467 |
-
str device (str): "cpu" or "cuda" or torch.Tensor.device
|
| 468 |
-
dtype (torch.device): result dtype
|
| 469 |
-
|
| 470 |
-
Returns:
|
| 471 |
-
torch.Tensor: mask
|
| 472 |
-
|
| 473 |
-
Examples:
|
| 474 |
-
>>> subsequent_mask(3)
|
| 475 |
-
[[1, 0, 0],
|
| 476 |
-
[1, 1, 0],
|
| 477 |
-
[1, 1, 1]]
|
| 478 |
-
"""
|
| 479 |
-
arange = torch.arange(size, device=device)
|
| 480 |
-
mask = arange.expand(size, size)
|
| 481 |
-
arange = arange.unsqueeze(-1)
|
| 482 |
-
mask = mask <= arange
|
| 483 |
-
return mask
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
def subsequent_chunk_mask(
|
| 487 |
-
size: int,
|
| 488 |
-
chunk_size: int,
|
| 489 |
-
num_left_chunks: int = -1,
|
| 490 |
-
device: torch.device = torch.device("cpu"),
|
| 491 |
-
) -> torch.Tensor:
|
| 492 |
-
"""Create mask for subsequent steps (size, size) with chunk size,
|
| 493 |
-
this is for streaming encoder
|
| 494 |
-
|
| 495 |
-
Args:
|
| 496 |
-
size (int): size of mask
|
| 497 |
-
chunk_size (int): size of chunk
|
| 498 |
-
num_left_chunks (int): number of left chunks
|
| 499 |
-
<0: use full chunk
|
| 500 |
-
>=0: use num_left_chunks
|
| 501 |
-
device (torch.device): "cpu" or "cuda" or torch.Tensor.device
|
| 502 |
-
|
| 503 |
-
Returns:
|
| 504 |
-
torch.Tensor: mask
|
| 505 |
-
|
| 506 |
-
Examples:
|
| 507 |
-
>>> subsequent_chunk_mask(4, 2)
|
| 508 |
-
[[1, 1, 0, 0],
|
| 509 |
-
[1, 1, 0, 0],
|
| 510 |
-
[1, 1, 1, 1],
|
| 511 |
-
[1, 1, 1, 1]]
|
| 512 |
-
"""
|
| 513 |
-
ret = torch.zeros(size, size, device=device, dtype=torch.bool)
|
| 514 |
-
for i in range(size):
|
| 515 |
-
if num_left_chunks < 0:
|
| 516 |
-
start = 0
|
| 517 |
-
else:
|
| 518 |
-
start = max((i // chunk_size - num_left_chunks) * chunk_size, 0)
|
| 519 |
-
ending = min((i // chunk_size + 1) * chunk_size, size)
|
| 520 |
-
ret[i, start:ending] = True
|
| 521 |
-
return ret
|
| 522 |
-
|
| 523 |
-
def add_optional_chunk_mask(xs: torch.Tensor,
|
| 524 |
-
masks: torch.Tensor,
|
| 525 |
-
use_dynamic_chunk: bool,
|
| 526 |
-
use_dynamic_left_chunk: bool,
|
| 527 |
-
decoding_chunk_size: int,
|
| 528 |
-
static_chunk_size: int,
|
| 529 |
-
num_decoding_left_chunks: int,
|
| 530 |
-
enable_full_context: bool = True):
|
| 531 |
-
""" Apply optional mask for encoder.
|
| 532 |
-
|
| 533 |
-
Args:
|
| 534 |
-
xs (torch.Tensor): padded input, (B, L, D), L for max length
|
| 535 |
-
mask (torch.Tensor): mask for xs, (B, 1, L)
|
| 536 |
-
use_dynamic_chunk (bool): whether to use dynamic chunk or not
|
| 537 |
-
use_dynamic_left_chunk (bool): whether to use dynamic left chunk for
|
| 538 |
-
training.
|
| 539 |
-
decoding_chunk_size (int): decoding chunk size for dynamic chunk, it's
|
| 540 |
-
0: default for training, use random dynamic chunk.
|
| 541 |
-
<0: for decoding, use full chunk.
|
| 542 |
-
>0: for decoding, use fixed chunk size as set.
|
| 543 |
-
static_chunk_size (int): chunk size for static chunk training/decoding
|
| 544 |
-
if it's greater than 0, if use_dynamic_chunk is true,
|
| 545 |
-
this parameter will be ignored
|
| 546 |
-
num_decoding_left_chunks: number of left chunks, this is for decoding,
|
| 547 |
-
the chunk size is decoding_chunk_size.
|
| 548 |
-
>=0: use num_decoding_left_chunks
|
| 549 |
-
<0: use all left chunks
|
| 550 |
-
enable_full_context (bool):
|
| 551 |
-
True: chunk size is either [1, 25] or full context(max_len)
|
| 552 |
-
False: chunk size ~ U[1, 25]
|
| 553 |
-
|
| 554 |
-
Returns:
|
| 555 |
-
torch.Tensor: chunk mask of the input xs.
|
| 556 |
-
"""
|
| 557 |
-
# Whether to use chunk mask or not
|
| 558 |
-
if use_dynamic_chunk:
|
| 559 |
-
max_len = xs.size(1)
|
| 560 |
-
if decoding_chunk_size < 0:
|
| 561 |
-
chunk_size = max_len
|
| 562 |
-
num_left_chunks = -1
|
| 563 |
-
elif decoding_chunk_size > 0:
|
| 564 |
-
chunk_size = decoding_chunk_size
|
| 565 |
-
num_left_chunks = num_decoding_left_chunks
|
| 566 |
-
else:
|
| 567 |
-
# chunk size is either [1, 25] or full context(max_len).
|
| 568 |
-
# Since we use 4 times subsampling and allow up to 1s(100 frames)
|
| 569 |
-
# delay, the maximum frame is 100 / 4 = 25.
|
| 570 |
-
chunk_size = torch.randint(1, max_len, (1, )).item()
|
| 571 |
-
num_left_chunks = -1
|
| 572 |
-
if chunk_size > max_len // 2 and enable_full_context:
|
| 573 |
-
chunk_size = max_len
|
| 574 |
-
else:
|
| 575 |
-
chunk_size = chunk_size % 25 + 1
|
| 576 |
-
if use_dynamic_left_chunk:
|
| 577 |
-
max_left_chunks = (max_len - 1) // chunk_size
|
| 578 |
-
num_left_chunks = torch.randint(0, max_left_chunks,
|
| 579 |
-
(1, )).item()
|
| 580 |
-
chunk_masks = subsequent_chunk_mask(xs.size(1), chunk_size,
|
| 581 |
-
num_left_chunks,
|
| 582 |
-
xs.device) # (L, L)
|
| 583 |
-
chunk_masks = chunk_masks.unsqueeze(0) # (1, L, L)
|
| 584 |
-
chunk_masks = masks & chunk_masks # (B, L, L)
|
| 585 |
-
elif static_chunk_size > 0:
|
| 586 |
-
num_left_chunks = num_decoding_left_chunks
|
| 587 |
-
chunk_masks = subsequent_chunk_mask(xs.size(1), static_chunk_size,
|
| 588 |
-
num_left_chunks,
|
| 589 |
-
xs.device) # (L, L)
|
| 590 |
-
chunk_masks = chunk_masks.unsqueeze(0) # (1, L, L)
|
| 591 |
-
chunk_masks = masks & chunk_masks # (B, L, L)
|
| 592 |
-
else:
|
| 593 |
-
chunk_masks = masks
|
| 594 |
-
return chunk_masks
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
class ConformerEncoderLayer(nn.Module):
|
| 598 |
-
"""Encoder layer module.
|
| 599 |
-
Args:
|
| 600 |
-
size (int): Input dimension.
|
| 601 |
-
self_attn (torch.nn.Module): Self-attention module instance.
|
| 602 |
-
`MultiHeadedAttention` or `RelPositionMultiHeadedAttention`
|
| 603 |
-
instance can be used as the argument.
|
| 604 |
-
feed_forward (torch.nn.Module): Feed-forward module instance.
|
| 605 |
-
`PositionwiseFeedForward` instance can be used as the argument.
|
| 606 |
-
feed_forward_macaron (torch.nn.Module): Additional feed-forward module
|
| 607 |
-
instance.
|
| 608 |
-
`PositionwiseFeedForward` instance can be used as the argument.
|
| 609 |
-
conv_module (torch.nn.Module): Convolution module instance.
|
| 610 |
-
`ConvlutionModule` instance can be used as the argument.
|
| 611 |
-
dropout_rate (float): Dropout rate.
|
| 612 |
-
normalize_before (bool):
|
| 613 |
-
True: use layer_norm before each sub-block.
|
| 614 |
-
False: use layer_norm after each sub-block.
|
| 615 |
-
"""
|
| 616 |
-
|
| 617 |
-
def __init__(
|
| 618 |
-
self,
|
| 619 |
-
size: int,
|
| 620 |
-
self_attn: torch.nn.Module,
|
| 621 |
-
feed_forward: Optional[nn.Module] = None,
|
| 622 |
-
feed_forward_macaron: Optional[nn.Module] = None,
|
| 623 |
-
conv_module: Optional[nn.Module] = None,
|
| 624 |
-
dropout_rate: float = 0.1,
|
| 625 |
-
normalize_before: bool = True,
|
| 626 |
-
dtype=None, device=None, operations=None
|
| 627 |
-
):
|
| 628 |
-
"""Construct an EncoderLayer object."""
|
| 629 |
-
super().__init__()
|
| 630 |
-
self.self_attn = self_attn
|
| 631 |
-
self.feed_forward = feed_forward
|
| 632 |
-
self.feed_forward_macaron = feed_forward_macaron
|
| 633 |
-
self.conv_module = conv_module
|
| 634 |
-
self.norm_ff = operations.LayerNorm(size, eps=1e-5, dtype=dtype, device=device) # for the FNN module
|
| 635 |
-
self.norm_mha = operations.LayerNorm(size, eps=1e-5, dtype=dtype, device=device) # for the MHA module
|
| 636 |
-
if feed_forward_macaron is not None:
|
| 637 |
-
self.norm_ff_macaron = operations.LayerNorm(size, eps=1e-5, dtype=dtype, device=device)
|
| 638 |
-
self.ff_scale = 0.5
|
| 639 |
-
else:
|
| 640 |
-
self.ff_scale = 1.0
|
| 641 |
-
if self.conv_module is not None:
|
| 642 |
-
self.norm_conv = operations.LayerNorm(size, eps=1e-5, dtype=dtype, device=device) # for the CNN module
|
| 643 |
-
self.norm_final = operations.LayerNorm(
|
| 644 |
-
size, eps=1e-5, dtype=dtype, device=device) # for the final output of the block
|
| 645 |
-
self.dropout = nn.Dropout(dropout_rate)
|
| 646 |
-
self.size = size
|
| 647 |
-
self.normalize_before = normalize_before
|
| 648 |
-
|
| 649 |
-
def forward(
|
| 650 |
-
self,
|
| 651 |
-
x: torch.Tensor,
|
| 652 |
-
mask: torch.Tensor,
|
| 653 |
-
pos_emb: torch.Tensor,
|
| 654 |
-
mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
|
| 655 |
-
att_cache: torch.Tensor = torch.zeros((0, 0, 0, 0)),
|
| 656 |
-
cnn_cache: torch.Tensor = torch.zeros((0, 0, 0, 0)),
|
| 657 |
-
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 658 |
-
"""Compute encoded features.
|
| 659 |
-
|
| 660 |
-
Args:
|
| 661 |
-
x (torch.Tensor): (#batch, time, size)
|
| 662 |
-
mask (torch.Tensor): Mask tensor for the input (#batch, time,time),
|
| 663 |
-
(0, 0, 0) means fake mask.
|
| 664 |
-
pos_emb (torch.Tensor): positional encoding, must not be None
|
| 665 |
-
for ConformerEncoderLayer.
|
| 666 |
-
mask_pad (torch.Tensor): batch padding mask used for conv module.
|
| 667 |
-
(#batch, 1,time), (0, 0, 0) means fake mask.
|
| 668 |
-
att_cache (torch.Tensor): Cache tensor of the KEY & VALUE
|
| 669 |
-
(#batch=1, head, cache_t1, d_k * 2), head * d_k == size.
|
| 670 |
-
cnn_cache (torch.Tensor): Convolution cache in conformer layer
|
| 671 |
-
(#batch=1, size, cache_t2)
|
| 672 |
-
Returns:
|
| 673 |
-
torch.Tensor: Output tensor (#batch, time, size).
|
| 674 |
-
torch.Tensor: Mask tensor (#batch, time, time).
|
| 675 |
-
torch.Tensor: att_cache tensor,
|
| 676 |
-
(#batch=1, head, cache_t1 + time, d_k * 2).
|
| 677 |
-
torch.Tensor: cnn_cahce tensor (#batch, size, cache_t2).
|
| 678 |
-
"""
|
| 679 |
-
|
| 680 |
-
# whether to use macaron style
|
| 681 |
-
if self.feed_forward_macaron is not None:
|
| 682 |
-
residual = x
|
| 683 |
-
if self.normalize_before:
|
| 684 |
-
x = self.norm_ff_macaron(x)
|
| 685 |
-
x = residual + self.ff_scale * self.dropout(
|
| 686 |
-
self.feed_forward_macaron(x))
|
| 687 |
-
if not self.normalize_before:
|
| 688 |
-
x = self.norm_ff_macaron(x)
|
| 689 |
-
|
| 690 |
-
# multi-headed self-attention module
|
| 691 |
-
residual = x
|
| 692 |
-
if self.normalize_before:
|
| 693 |
-
x = self.norm_mha(x)
|
| 694 |
-
x_att, new_att_cache = self.self_attn(x, x, x, mask, pos_emb,
|
| 695 |
-
att_cache)
|
| 696 |
-
x = residual + self.dropout(x_att)
|
| 697 |
-
if not self.normalize_before:
|
| 698 |
-
x = self.norm_mha(x)
|
| 699 |
-
|
| 700 |
-
# convolution module
|
| 701 |
-
# Fake new cnn cache here, and then change it in conv_module
|
| 702 |
-
new_cnn_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
|
| 703 |
-
if self.conv_module is not None:
|
| 704 |
-
residual = x
|
| 705 |
-
if self.normalize_before:
|
| 706 |
-
x = self.norm_conv(x)
|
| 707 |
-
x, new_cnn_cache = self.conv_module(x, mask_pad, cnn_cache)
|
| 708 |
-
x = residual + self.dropout(x)
|
| 709 |
-
|
| 710 |
-
if not self.normalize_before:
|
| 711 |
-
x = self.norm_conv(x)
|
| 712 |
-
|
| 713 |
-
# feed forward module
|
| 714 |
-
residual = x
|
| 715 |
-
if self.normalize_before:
|
| 716 |
-
x = self.norm_ff(x)
|
| 717 |
-
|
| 718 |
-
x = residual + self.ff_scale * self.dropout(self.feed_forward(x))
|
| 719 |
-
if not self.normalize_before:
|
| 720 |
-
x = self.norm_ff(x)
|
| 721 |
-
|
| 722 |
-
if self.conv_module is not None:
|
| 723 |
-
x = self.norm_final(x)
|
| 724 |
-
|
| 725 |
-
return x, mask, new_att_cache, new_cnn_cache
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
class EspnetRelPositionalEncoding(torch.nn.Module):
|
| 730 |
-
"""Relative positional encoding module (new implementation).
|
| 731 |
-
|
| 732 |
-
Details can be found in https://github.com/espnet/espnet/pull/2816.
|
| 733 |
-
|
| 734 |
-
See : Appendix B in https://arxiv.org/abs/1901.02860
|
| 735 |
-
|
| 736 |
-
Args:
|
| 737 |
-
d_model (int): Embedding dimension.
|
| 738 |
-
dropout_rate (float): Dropout rate.
|
| 739 |
-
max_len (int): Maximum input length.
|
| 740 |
-
|
| 741 |
-
"""
|
| 742 |
-
|
| 743 |
-
def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000):
|
| 744 |
-
"""Construct an PositionalEncoding object."""
|
| 745 |
-
super(EspnetRelPositionalEncoding, self).__init__()
|
| 746 |
-
self.d_model = d_model
|
| 747 |
-
self.xscale = math.sqrt(self.d_model)
|
| 748 |
-
self.dropout = torch.nn.Dropout(p=dropout_rate)
|
| 749 |
-
self.pe = None
|
| 750 |
-
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
|
| 751 |
-
|
| 752 |
-
def extend_pe(self, x: torch.Tensor):
|
| 753 |
-
"""Reset the positional encodings."""
|
| 754 |
-
if self.pe is not None:
|
| 755 |
-
# self.pe contains both positive and negative parts
|
| 756 |
-
# the length of self.pe is 2 * input_len - 1
|
| 757 |
-
if self.pe.size(1) >= x.size(1) * 2 - 1:
|
| 758 |
-
if self.pe.dtype != x.dtype or self.pe.device != x.device:
|
| 759 |
-
self.pe = self.pe.to(dtype=x.dtype, device=x.device)
|
| 760 |
-
return
|
| 761 |
-
# Suppose `i` means to the position of query vecotr and `j` means the
|
| 762 |
-
# position of key vector. We use position relative positions when keys
|
| 763 |
-
# are to the left (i>j) and negative relative positions otherwise (i<j).
|
| 764 |
-
pe_positive = torch.zeros(x.size(1), self.d_model)
|
| 765 |
-
pe_negative = torch.zeros(x.size(1), self.d_model)
|
| 766 |
-
position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
|
| 767 |
-
div_term = torch.exp(
|
| 768 |
-
torch.arange(0, self.d_model, 2, dtype=torch.float32)
|
| 769 |
-
* -(math.log(10000.0) / self.d_model)
|
| 770 |
-
)
|
| 771 |
-
pe_positive[:, 0::2] = torch.sin(position * div_term)
|
| 772 |
-
pe_positive[:, 1::2] = torch.cos(position * div_term)
|
| 773 |
-
pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
|
| 774 |
-
pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
|
| 775 |
-
|
| 776 |
-
# Reserve the order of positive indices and concat both positive and
|
| 777 |
-
# negative indices. This is used to support the shifting trick
|
| 778 |
-
# as in https://arxiv.org/abs/1901.02860
|
| 779 |
-
pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
|
| 780 |
-
pe_negative = pe_negative[1:].unsqueeze(0)
|
| 781 |
-
pe = torch.cat([pe_positive, pe_negative], dim=1)
|
| 782 |
-
self.pe = pe.to(device=x.device, dtype=x.dtype)
|
| 783 |
-
|
| 784 |
-
def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) \
|
| 785 |
-
-> Tuple[torch.Tensor, torch.Tensor]:
|
| 786 |
-
"""Add positional encoding.
|
| 787 |
-
|
| 788 |
-
Args:
|
| 789 |
-
x (torch.Tensor): Input tensor (batch, time, `*`).
|
| 790 |
-
|
| 791 |
-
Returns:
|
| 792 |
-
torch.Tensor: Encoded tensor (batch, time, `*`).
|
| 793 |
-
|
| 794 |
-
"""
|
| 795 |
-
self.extend_pe(x)
|
| 796 |
-
x = x * self.xscale
|
| 797 |
-
pos_emb = self.position_encoding(size=x.size(1), offset=offset)
|
| 798 |
-
return self.dropout(x), self.dropout(pos_emb)
|
| 799 |
-
|
| 800 |
-
def position_encoding(self,
|
| 801 |
-
offset: Union[int, torch.Tensor],
|
| 802 |
-
size: int) -> torch.Tensor:
|
| 803 |
-
""" For getting encoding in a streaming fashion
|
| 804 |
-
|
| 805 |
-
Attention!!!!!
|
| 806 |
-
we apply dropout only once at the whole utterance level in a none
|
| 807 |
-
streaming way, but will call this function several times with
|
| 808 |
-
increasing input size in a streaming scenario, so the dropout will
|
| 809 |
-
be applied several times.
|
| 810 |
-
|
| 811 |
-
Args:
|
| 812 |
-
offset (int or torch.tensor): start offset
|
| 813 |
-
size (int): required size of position encoding
|
| 814 |
-
|
| 815 |
-
Returns:
|
| 816 |
-
torch.Tensor: Corresponding encoding
|
| 817 |
-
"""
|
| 818 |
-
pos_emb = self.pe[
|
| 819 |
-
:,
|
| 820 |
-
self.pe.size(1) // 2 - size + 1: self.pe.size(1) // 2 + size,
|
| 821 |
-
]
|
| 822 |
-
return pos_emb
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
class LinearEmbed(torch.nn.Module):
|
| 827 |
-
"""Linear transform the input without subsampling
|
| 828 |
-
|
| 829 |
-
Args:
|
| 830 |
-
idim (int): Input dimension.
|
| 831 |
-
odim (int): Output dimension.
|
| 832 |
-
dropout_rate (float): Dropout rate.
|
| 833 |
-
|
| 834 |
-
"""
|
| 835 |
-
|
| 836 |
-
def __init__(self, idim: int, odim: int, dropout_rate: float,
|
| 837 |
-
pos_enc_class: torch.nn.Module, dtype=None, device=None, operations=None):
|
| 838 |
-
"""Construct an linear object."""
|
| 839 |
-
super().__init__()
|
| 840 |
-
self.out = torch.nn.Sequential(
|
| 841 |
-
operations.Linear(idim, odim, dtype=dtype, device=device),
|
| 842 |
-
operations.LayerNorm(odim, eps=1e-5, dtype=dtype, device=device),
|
| 843 |
-
torch.nn.Dropout(dropout_rate),
|
| 844 |
-
)
|
| 845 |
-
self.pos_enc = pos_enc_class #rel_pos_espnet
|
| 846 |
-
|
| 847 |
-
def position_encoding(self, offset: Union[int, torch.Tensor],
|
| 848 |
-
size: int) -> torch.Tensor:
|
| 849 |
-
return self.pos_enc.position_encoding(offset, size)
|
| 850 |
-
|
| 851 |
-
def forward(
|
| 852 |
-
self,
|
| 853 |
-
x: torch.Tensor,
|
| 854 |
-
offset: Union[int, torch.Tensor] = 0
|
| 855 |
-
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 856 |
-
"""Input x.
|
| 857 |
-
|
| 858 |
-
Args:
|
| 859 |
-
x (torch.Tensor): Input tensor (#batch, time, idim).
|
| 860 |
-
x_mask (torch.Tensor): Input mask (#batch, 1, time).
|
| 861 |
-
|
| 862 |
-
Returns:
|
| 863 |
-
torch.Tensor: linear input tensor (#batch, time', odim),
|
| 864 |
-
where time' = time .
|
| 865 |
-
torch.Tensor: linear input mask (#batch, 1, time'),
|
| 866 |
-
where time' = time .
|
| 867 |
-
|
| 868 |
-
"""
|
| 869 |
-
x = self.out(x)
|
| 870 |
-
x, pos_emb = self.pos_enc(x, offset)
|
| 871 |
-
return x, pos_emb
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
ATTENTION_CLASSES = {
|
| 875 |
-
"selfattn": MultiHeadedAttention,
|
| 876 |
-
"rel_selfattn": RelPositionMultiHeadedAttention,
|
| 877 |
-
}
|
| 878 |
-
|
| 879 |
-
ACTIVATION_CLASSES = {
|
| 880 |
-
"hardtanh": torch.nn.Hardtanh,
|
| 881 |
-
"tanh": torch.nn.Tanh,
|
| 882 |
-
"relu": torch.nn.ReLU,
|
| 883 |
-
"selu": torch.nn.SELU,
|
| 884 |
-
"swish": getattr(torch.nn, "SiLU", Swish),
|
| 885 |
-
"gelu": torch.nn.GELU,
|
| 886 |
-
}
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
|
| 890 |
-
"""Make mask tensor containing indices of padded part.
|
| 891 |
-
|
| 892 |
-
See description of make_non_pad_mask.
|
| 893 |
-
|
| 894 |
-
Args:
|
| 895 |
-
lengths (torch.Tensor): Batch of lengths (B,).
|
| 896 |
-
Returns:
|
| 897 |
-
torch.Tensor: Mask tensor containing indices of padded part.
|
| 898 |
-
|
| 899 |
-
Examples:
|
| 900 |
-
>>> lengths = [5, 3, 2]
|
| 901 |
-
>>> make_pad_mask(lengths)
|
| 902 |
-
masks = [[0, 0, 0, 0 ,0],
|
| 903 |
-
[0, 0, 0, 1, 1],
|
| 904 |
-
[0, 0, 1, 1, 1]]
|
| 905 |
-
"""
|
| 906 |
-
batch_size = lengths.size(0)
|
| 907 |
-
max_len = max_len if max_len > 0 else lengths.max().item()
|
| 908 |
-
seq_range = torch.arange(0,
|
| 909 |
-
max_len,
|
| 910 |
-
dtype=torch.int64,
|
| 911 |
-
device=lengths.device)
|
| 912 |
-
seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
|
| 913 |
-
seq_length_expand = lengths.unsqueeze(-1)
|
| 914 |
-
mask = seq_range_expand >= seq_length_expand
|
| 915 |
-
return mask
|
| 916 |
-
|
| 917 |
-
#https://github.com/FunAudioLLM/CosyVoice/blob/main/examples/magicdata-read/cosyvoice/conf/cosyvoice.yaml
|
| 918 |
-
class ConformerEncoder(torch.nn.Module):
|
| 919 |
-
"""Conformer encoder module."""
|
| 920 |
-
|
| 921 |
-
def __init__(
|
| 922 |
-
self,
|
| 923 |
-
input_size: int,
|
| 924 |
-
output_size: int = 1024,
|
| 925 |
-
attention_heads: int = 16,
|
| 926 |
-
linear_units: int = 4096,
|
| 927 |
-
num_blocks: int = 6,
|
| 928 |
-
dropout_rate: float = 0.1,
|
| 929 |
-
positional_dropout_rate: float = 0.1,
|
| 930 |
-
attention_dropout_rate: float = 0.0,
|
| 931 |
-
input_layer: str = 'linear',
|
| 932 |
-
pos_enc_layer_type: str = 'rel_pos_espnet',
|
| 933 |
-
normalize_before: bool = True,
|
| 934 |
-
static_chunk_size: int = 1, # 1: causal_mask; 0: full_mask
|
| 935 |
-
use_dynamic_chunk: bool = False,
|
| 936 |
-
use_dynamic_left_chunk: bool = False,
|
| 937 |
-
positionwise_conv_kernel_size: int = 1,
|
| 938 |
-
macaron_style: bool =False,
|
| 939 |
-
selfattention_layer_type: str = "rel_selfattn",
|
| 940 |
-
activation_type: str = "swish",
|
| 941 |
-
use_cnn_module: bool = False,
|
| 942 |
-
cnn_module_kernel: int = 15,
|
| 943 |
-
causal: bool = False,
|
| 944 |
-
cnn_module_norm: str = "batch_norm",
|
| 945 |
-
key_bias: bool = True,
|
| 946 |
-
dtype=None, device=None, operations=None
|
| 947 |
-
):
|
| 948 |
-
"""Construct ConformerEncoder
|
| 949 |
-
|
| 950 |
-
Args:
|
| 951 |
-
input_size to use_dynamic_chunk, see in BaseEncoder
|
| 952 |
-
positionwise_conv_kernel_size (int): Kernel size of positionwise
|
| 953 |
-
conv1d layer.
|
| 954 |
-
macaron_style (bool): Whether to use macaron style for
|
| 955 |
-
positionwise layer.
|
| 956 |
-
selfattention_layer_type (str): Encoder attention layer type,
|
| 957 |
-
the parameter has no effect now, it's just for configure
|
| 958 |
-
compatibility. #'rel_selfattn'
|
| 959 |
-
activation_type (str): Encoder activation function type.
|
| 960 |
-
use_cnn_module (bool): Whether to use convolution module.
|
| 961 |
-
cnn_module_kernel (int): Kernel size of convolution module.
|
| 962 |
-
causal (bool): whether to use causal convolution or not.
|
| 963 |
-
key_bias: whether use bias in attention.linear_k, False for whisper models.
|
| 964 |
-
"""
|
| 965 |
-
super().__init__()
|
| 966 |
-
self.output_size = output_size
|
| 967 |
-
self.embed = LinearEmbed(input_size, output_size, dropout_rate,
|
| 968 |
-
EspnetRelPositionalEncoding(output_size, positional_dropout_rate), dtype=dtype, device=device, operations=operations)
|
| 969 |
-
self.normalize_before = normalize_before
|
| 970 |
-
self.after_norm = operations.LayerNorm(output_size, eps=1e-5, dtype=dtype, device=device)
|
| 971 |
-
self.use_dynamic_chunk = use_dynamic_chunk
|
| 972 |
-
|
| 973 |
-
self.static_chunk_size = static_chunk_size
|
| 974 |
-
self.use_dynamic_chunk = use_dynamic_chunk
|
| 975 |
-
self.use_dynamic_left_chunk = use_dynamic_left_chunk
|
| 976 |
-
activation = ACTIVATION_CLASSES[activation_type]()
|
| 977 |
-
|
| 978 |
-
# self-attention module definition
|
| 979 |
-
encoder_selfattn_layer_args = (
|
| 980 |
-
attention_heads,
|
| 981 |
-
output_size,
|
| 982 |
-
attention_dropout_rate,
|
| 983 |
-
key_bias,
|
| 984 |
-
)
|
| 985 |
-
# feed-forward module definition
|
| 986 |
-
positionwise_layer_args = (
|
| 987 |
-
output_size,
|
| 988 |
-
linear_units,
|
| 989 |
-
dropout_rate,
|
| 990 |
-
activation,
|
| 991 |
-
)
|
| 992 |
-
# convolution module definition
|
| 993 |
-
convolution_layer_args = (output_size, cnn_module_kernel, activation,
|
| 994 |
-
cnn_module_norm, causal)
|
| 995 |
-
|
| 996 |
-
self.encoders = torch.nn.ModuleList([
|
| 997 |
-
ConformerEncoderLayer(
|
| 998 |
-
output_size,
|
| 999 |
-
RelPositionMultiHeadedAttention(
|
| 1000 |
-
*encoder_selfattn_layer_args, dtype=dtype, device=device, operations=operations),
|
| 1001 |
-
PositionwiseFeedForward(*positionwise_layer_args, dtype=dtype, device=device, operations=operations),
|
| 1002 |
-
PositionwiseFeedForward(
|
| 1003 |
-
*positionwise_layer_args, dtype=dtype, device=device, operations=operations) if macaron_style else None,
|
| 1004 |
-
ConvolutionModule(
|
| 1005 |
-
*convolution_layer_args, dtype=dtype, device=device, operations=operations) if use_cnn_module else None,
|
| 1006 |
-
dropout_rate,
|
| 1007 |
-
normalize_before, dtype=dtype, device=device, operations=operations
|
| 1008 |
-
) for _ in range(num_blocks)
|
| 1009 |
-
])
|
| 1010 |
-
|
| 1011 |
-
def forward_layers(self, xs: torch.Tensor, chunk_masks: torch.Tensor,
|
| 1012 |
-
pos_emb: torch.Tensor,
|
| 1013 |
-
mask_pad: torch.Tensor) -> torch.Tensor:
|
| 1014 |
-
for layer in self.encoders:
|
| 1015 |
-
xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
|
| 1016 |
-
return xs
|
| 1017 |
-
|
| 1018 |
-
def forward(
|
| 1019 |
-
self,
|
| 1020 |
-
xs: torch.Tensor,
|
| 1021 |
-
pad_mask: torch.Tensor,
|
| 1022 |
-
decoding_chunk_size: int = 0,
|
| 1023 |
-
num_decoding_left_chunks: int = -1,
|
| 1024 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 1025 |
-
"""Embed positions in tensor.
|
| 1026 |
-
|
| 1027 |
-
Args:
|
| 1028 |
-
xs: padded input tensor (B, T, D)
|
| 1029 |
-
xs_lens: input length (B)
|
| 1030 |
-
decoding_chunk_size: decoding chunk size for dynamic chunk
|
| 1031 |
-
0: default for training, use random dynamic chunk.
|
| 1032 |
-
<0: for decoding, use full chunk.
|
| 1033 |
-
>0: for decoding, use fixed chunk size as set.
|
| 1034 |
-
num_decoding_left_chunks: number of left chunks, this is for decoding,
|
| 1035 |
-
the chunk size is decoding_chunk_size.
|
| 1036 |
-
>=0: use num_decoding_left_chunks
|
| 1037 |
-
<0: use all left chunks
|
| 1038 |
-
Returns:
|
| 1039 |
-
encoder output tensor xs, and subsampled masks
|
| 1040 |
-
xs: padded output tensor (B, T' ~= T/subsample_rate, D)
|
| 1041 |
-
masks: torch.Tensor batch padding mask after subsample
|
| 1042 |
-
(B, 1, T' ~= T/subsample_rate)
|
| 1043 |
-
NOTE(xcsong):
|
| 1044 |
-
We pass the `__call__` method of the modules instead of `forward` to the
|
| 1045 |
-
checkpointing API because `__call__` attaches all the hooks of the module.
|
| 1046 |
-
https://discuss.pytorch.org/t/any-different-between-model-input-and-model-forward-input/3690/2
|
| 1047 |
-
"""
|
| 1048 |
-
masks = None
|
| 1049 |
-
if pad_mask is not None:
|
| 1050 |
-
masks = pad_mask.to(torch.bool).unsqueeze(1) # (B, 1, T)
|
| 1051 |
-
xs, pos_emb = self.embed(xs)
|
| 1052 |
-
mask_pad = masks # (B, 1, T/subsample_rate)
|
| 1053 |
-
chunk_masks = add_optional_chunk_mask(xs, masks,
|
| 1054 |
-
self.use_dynamic_chunk,
|
| 1055 |
-
self.use_dynamic_left_chunk,
|
| 1056 |
-
decoding_chunk_size,
|
| 1057 |
-
self.static_chunk_size,
|
| 1058 |
-
num_decoding_left_chunks)
|
| 1059 |
-
|
| 1060 |
-
xs = self.forward_layers(xs, chunk_masks, pos_emb, mask_pad)
|
| 1061 |
-
if self.normalize_before:
|
| 1062 |
-
xs = self.after_norm(xs)
|
| 1063 |
-
# Here we assume the mask is not changed in encoder layers, so just
|
| 1064 |
-
# return the masks before encoder layers, and the masks will be used
|
| 1065 |
-
# for cross attention with decoder later
|
| 1066 |
-
return xs, masks
|
| 1067 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/ace/model.py
DELETED
|
@@ -1,385 +0,0 @@
|
|
| 1 |
-
# Original from: https://github.com/ace-step/ACE-Step/blob/main/models/ace_step_transformer.py
|
| 2 |
-
|
| 3 |
-
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 4 |
-
#
|
| 5 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
-
# you may not use this file except in compliance with the License.
|
| 7 |
-
# You may obtain a copy of the License at
|
| 8 |
-
#
|
| 9 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
-
#
|
| 11 |
-
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
-
# See the License for the specific language governing permissions and
|
| 15 |
-
# limitations under the License.
|
| 16 |
-
from typing import Optional, List, Union
|
| 17 |
-
|
| 18 |
-
import torch
|
| 19 |
-
from torch import nn
|
| 20 |
-
|
| 21 |
-
import comfy.model_management
|
| 22 |
-
|
| 23 |
-
from comfy.ldm.lightricks.model import TimestepEmbedding, Timesteps
|
| 24 |
-
from .attention import LinearTransformerBlock, t2i_modulate
|
| 25 |
-
from .lyric_encoder import ConformerEncoder as LyricEncoder
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def cross_norm(hidden_states, controlnet_input):
|
| 29 |
-
# input N x T x c
|
| 30 |
-
mean_hidden_states, std_hidden_states = hidden_states.mean(dim=(1,2), keepdim=True), hidden_states.std(dim=(1,2), keepdim=True)
|
| 31 |
-
mean_controlnet_input, std_controlnet_input = controlnet_input.mean(dim=(1,2), keepdim=True), controlnet_input.std(dim=(1,2), keepdim=True)
|
| 32 |
-
controlnet_input = (controlnet_input - mean_controlnet_input) * (std_hidden_states / (std_controlnet_input + 1e-12)) + mean_hidden_states
|
| 33 |
-
return controlnet_input
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
# Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Qwen2
|
| 37 |
-
class Qwen2RotaryEmbedding(nn.Module):
|
| 38 |
-
def __init__(self, dim, max_position_embeddings=2048, base=10000, dtype=None, device=None):
|
| 39 |
-
super().__init__()
|
| 40 |
-
|
| 41 |
-
self.dim = dim
|
| 42 |
-
self.max_position_embeddings = max_position_embeddings
|
| 43 |
-
self.base = base
|
| 44 |
-
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=device).float() / self.dim))
|
| 45 |
-
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 46 |
-
|
| 47 |
-
# Build here to make `torch.jit.trace` work.
|
| 48 |
-
self._set_cos_sin_cache(
|
| 49 |
-
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 53 |
-
self.max_seq_len_cached = seq_len
|
| 54 |
-
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
| 55 |
-
|
| 56 |
-
freqs = torch.outer(t, self.inv_freq)
|
| 57 |
-
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 58 |
-
emb = torch.cat((freqs, freqs), dim=-1)
|
| 59 |
-
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
| 60 |
-
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
| 61 |
-
|
| 62 |
-
def forward(self, x, seq_len=None):
|
| 63 |
-
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 64 |
-
if seq_len > self.max_seq_len_cached:
|
| 65 |
-
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
| 66 |
-
|
| 67 |
-
return (
|
| 68 |
-
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
| 69 |
-
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
| 70 |
-
)
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
class T2IFinalLayer(nn.Module):
|
| 74 |
-
"""
|
| 75 |
-
The final layer of Sana.
|
| 76 |
-
"""
|
| 77 |
-
|
| 78 |
-
def __init__(self, hidden_size, patch_size=[16, 1], out_channels=256, dtype=None, device=None, operations=None):
|
| 79 |
-
super().__init__()
|
| 80 |
-
self.norm_final = operations.RMSNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
|
| 81 |
-
self.linear = operations.Linear(hidden_size, patch_size[0] * patch_size[1] * out_channels, bias=True, dtype=dtype, device=device)
|
| 82 |
-
self.scale_shift_table = nn.Parameter(torch.empty(2, hidden_size, dtype=dtype, device=device))
|
| 83 |
-
self.out_channels = out_channels
|
| 84 |
-
self.patch_size = patch_size
|
| 85 |
-
|
| 86 |
-
def unpatchfy(
|
| 87 |
-
self,
|
| 88 |
-
hidden_states: torch.Tensor,
|
| 89 |
-
width: int,
|
| 90 |
-
):
|
| 91 |
-
# 4 unpatchify
|
| 92 |
-
new_height, new_width = 1, hidden_states.size(1)
|
| 93 |
-
hidden_states = hidden_states.reshape(
|
| 94 |
-
shape=(hidden_states.shape[0], new_height, new_width, self.patch_size[0], self.patch_size[1], self.out_channels)
|
| 95 |
-
).contiguous()
|
| 96 |
-
hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
|
| 97 |
-
output = hidden_states.reshape(
|
| 98 |
-
shape=(hidden_states.shape[0], self.out_channels, new_height * self.patch_size[0], new_width * self.patch_size[1])
|
| 99 |
-
).contiguous()
|
| 100 |
-
if width > new_width:
|
| 101 |
-
output = torch.nn.functional.pad(output, (0, width - new_width, 0, 0), 'constant', 0)
|
| 102 |
-
elif width < new_width:
|
| 103 |
-
output = output[:, :, :, :width]
|
| 104 |
-
return output
|
| 105 |
-
|
| 106 |
-
def forward(self, x, t, output_length):
|
| 107 |
-
shift, scale = (comfy.model_management.cast_to(self.scale_shift_table[None], device=t.device, dtype=t.dtype) + t[:, None]).chunk(2, dim=1)
|
| 108 |
-
x = t2i_modulate(self.norm_final(x), shift, scale)
|
| 109 |
-
x = self.linear(x)
|
| 110 |
-
# unpatchify
|
| 111 |
-
output = self.unpatchfy(x, output_length)
|
| 112 |
-
return output
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
class PatchEmbed(nn.Module):
|
| 116 |
-
"""2D Image to Patch Embedding"""
|
| 117 |
-
|
| 118 |
-
def __init__(
|
| 119 |
-
self,
|
| 120 |
-
height=16,
|
| 121 |
-
width=4096,
|
| 122 |
-
patch_size=(16, 1),
|
| 123 |
-
in_channels=8,
|
| 124 |
-
embed_dim=1152,
|
| 125 |
-
bias=True,
|
| 126 |
-
dtype=None, device=None, operations=None
|
| 127 |
-
):
|
| 128 |
-
super().__init__()
|
| 129 |
-
patch_size_h, patch_size_w = patch_size
|
| 130 |
-
self.early_conv_layers = nn.Sequential(
|
| 131 |
-
operations.Conv2d(in_channels, in_channels*256, kernel_size=patch_size, stride=patch_size, padding=0, bias=bias, dtype=dtype, device=device),
|
| 132 |
-
operations.GroupNorm(num_groups=32, num_channels=in_channels*256, eps=1e-6, affine=True, dtype=dtype, device=device),
|
| 133 |
-
operations.Conv2d(in_channels*256, embed_dim, kernel_size=1, stride=1, padding=0, bias=bias, dtype=dtype, device=device)
|
| 134 |
-
)
|
| 135 |
-
self.patch_size = patch_size
|
| 136 |
-
self.height, self.width = height // patch_size_h, width // patch_size_w
|
| 137 |
-
self.base_size = self.width
|
| 138 |
-
|
| 139 |
-
def forward(self, latent):
|
| 140 |
-
# early convolutions, N x C x H x W -> N x 256 * sqrt(patch_size) x H/patch_size x W/patch_size
|
| 141 |
-
latent = self.early_conv_layers(latent)
|
| 142 |
-
latent = latent.flatten(2).transpose(1, 2) # BCHW -> BNC
|
| 143 |
-
return latent
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
class ACEStepTransformer2DModel(nn.Module):
|
| 147 |
-
# _supports_gradient_checkpointing = True
|
| 148 |
-
|
| 149 |
-
def __init__(
|
| 150 |
-
self,
|
| 151 |
-
in_channels: Optional[int] = 8,
|
| 152 |
-
num_layers: int = 28,
|
| 153 |
-
inner_dim: int = 1536,
|
| 154 |
-
attention_head_dim: int = 64,
|
| 155 |
-
num_attention_heads: int = 24,
|
| 156 |
-
mlp_ratio: float = 4.0,
|
| 157 |
-
out_channels: int = 8,
|
| 158 |
-
max_position: int = 32768,
|
| 159 |
-
rope_theta: float = 1000000.0,
|
| 160 |
-
speaker_embedding_dim: int = 512,
|
| 161 |
-
text_embedding_dim: int = 768,
|
| 162 |
-
ssl_encoder_depths: List[int] = [9, 9],
|
| 163 |
-
ssl_names: List[str] = ["mert", "m-hubert"],
|
| 164 |
-
ssl_latent_dims: List[int] = [1024, 768],
|
| 165 |
-
lyric_encoder_vocab_size: int = 6681,
|
| 166 |
-
lyric_hidden_size: int = 1024,
|
| 167 |
-
patch_size: List[int] = [16, 1],
|
| 168 |
-
max_height: int = 16,
|
| 169 |
-
max_width: int = 4096,
|
| 170 |
-
audio_model=None,
|
| 171 |
-
dtype=None, device=None, operations=None
|
| 172 |
-
|
| 173 |
-
):
|
| 174 |
-
super().__init__()
|
| 175 |
-
|
| 176 |
-
self.dtype = dtype
|
| 177 |
-
self.num_attention_heads = num_attention_heads
|
| 178 |
-
self.attention_head_dim = attention_head_dim
|
| 179 |
-
inner_dim = num_attention_heads * attention_head_dim
|
| 180 |
-
self.inner_dim = inner_dim
|
| 181 |
-
self.out_channels = out_channels
|
| 182 |
-
self.max_position = max_position
|
| 183 |
-
self.patch_size = patch_size
|
| 184 |
-
|
| 185 |
-
self.rope_theta = rope_theta
|
| 186 |
-
|
| 187 |
-
self.rotary_emb = Qwen2RotaryEmbedding(
|
| 188 |
-
dim=self.attention_head_dim,
|
| 189 |
-
max_position_embeddings=self.max_position,
|
| 190 |
-
base=self.rope_theta,
|
| 191 |
-
dtype=dtype,
|
| 192 |
-
device=device,
|
| 193 |
-
)
|
| 194 |
-
|
| 195 |
-
# 2. Define input layers
|
| 196 |
-
self.in_channels = in_channels
|
| 197 |
-
|
| 198 |
-
self.num_layers = num_layers
|
| 199 |
-
# 3. Define transformers blocks
|
| 200 |
-
self.transformer_blocks = nn.ModuleList(
|
| 201 |
-
[
|
| 202 |
-
LinearTransformerBlock(
|
| 203 |
-
dim=self.inner_dim,
|
| 204 |
-
num_attention_heads=self.num_attention_heads,
|
| 205 |
-
attention_head_dim=attention_head_dim,
|
| 206 |
-
mlp_ratio=mlp_ratio,
|
| 207 |
-
add_cross_attention=True,
|
| 208 |
-
add_cross_attention_dim=self.inner_dim,
|
| 209 |
-
dtype=dtype,
|
| 210 |
-
device=device,
|
| 211 |
-
operations=operations,
|
| 212 |
-
)
|
| 213 |
-
for i in range(self.num_layers)
|
| 214 |
-
]
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
|
| 218 |
-
self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=self.inner_dim, dtype=dtype, device=device, operations=operations)
|
| 219 |
-
self.t_block = nn.Sequential(nn.SiLU(), operations.Linear(self.inner_dim, 6 * self.inner_dim, bias=True, dtype=dtype, device=device))
|
| 220 |
-
|
| 221 |
-
# speaker
|
| 222 |
-
self.speaker_embedder = operations.Linear(speaker_embedding_dim, self.inner_dim, dtype=dtype, device=device)
|
| 223 |
-
|
| 224 |
-
# genre
|
| 225 |
-
self.genre_embedder = operations.Linear(text_embedding_dim, self.inner_dim, dtype=dtype, device=device)
|
| 226 |
-
|
| 227 |
-
# lyric
|
| 228 |
-
self.lyric_embs = operations.Embedding(lyric_encoder_vocab_size, lyric_hidden_size, dtype=dtype, device=device)
|
| 229 |
-
self.lyric_encoder = LyricEncoder(input_size=lyric_hidden_size, static_chunk_size=0, dtype=dtype, device=device, operations=operations)
|
| 230 |
-
self.lyric_proj = operations.Linear(lyric_hidden_size, self.inner_dim, dtype=dtype, device=device)
|
| 231 |
-
|
| 232 |
-
projector_dim = 2 * self.inner_dim
|
| 233 |
-
|
| 234 |
-
self.projectors = nn.ModuleList([
|
| 235 |
-
nn.Sequential(
|
| 236 |
-
operations.Linear(self.inner_dim, projector_dim, dtype=dtype, device=device),
|
| 237 |
-
nn.SiLU(),
|
| 238 |
-
operations.Linear(projector_dim, projector_dim, dtype=dtype, device=device),
|
| 239 |
-
nn.SiLU(),
|
| 240 |
-
operations.Linear(projector_dim, ssl_dim, dtype=dtype, device=device),
|
| 241 |
-
) for ssl_dim in ssl_latent_dims
|
| 242 |
-
])
|
| 243 |
-
|
| 244 |
-
self.proj_in = PatchEmbed(
|
| 245 |
-
height=max_height,
|
| 246 |
-
width=max_width,
|
| 247 |
-
patch_size=patch_size,
|
| 248 |
-
embed_dim=self.inner_dim,
|
| 249 |
-
bias=True,
|
| 250 |
-
dtype=dtype,
|
| 251 |
-
device=device,
|
| 252 |
-
operations=operations,
|
| 253 |
-
)
|
| 254 |
-
|
| 255 |
-
self.final_layer = T2IFinalLayer(self.inner_dim, patch_size=patch_size, out_channels=out_channels, dtype=dtype, device=device, operations=operations)
|
| 256 |
-
|
| 257 |
-
def forward_lyric_encoder(
|
| 258 |
-
self,
|
| 259 |
-
lyric_token_idx: Optional[torch.LongTensor] = None,
|
| 260 |
-
lyric_mask: Optional[torch.LongTensor] = None,
|
| 261 |
-
out_dtype=None,
|
| 262 |
-
):
|
| 263 |
-
# N x T x D
|
| 264 |
-
lyric_embs = self.lyric_embs(lyric_token_idx, out_dtype=out_dtype)
|
| 265 |
-
prompt_prenet_out, _mask = self.lyric_encoder(lyric_embs, lyric_mask, decoding_chunk_size=1, num_decoding_left_chunks=-1)
|
| 266 |
-
prompt_prenet_out = self.lyric_proj(prompt_prenet_out)
|
| 267 |
-
return prompt_prenet_out
|
| 268 |
-
|
| 269 |
-
def encode(
|
| 270 |
-
self,
|
| 271 |
-
encoder_text_hidden_states: Optional[torch.Tensor] = None,
|
| 272 |
-
text_attention_mask: Optional[torch.LongTensor] = None,
|
| 273 |
-
speaker_embeds: Optional[torch.FloatTensor] = None,
|
| 274 |
-
lyric_token_idx: Optional[torch.LongTensor] = None,
|
| 275 |
-
lyric_mask: Optional[torch.LongTensor] = None,
|
| 276 |
-
lyrics_strength=1.0,
|
| 277 |
-
):
|
| 278 |
-
|
| 279 |
-
bs = encoder_text_hidden_states.shape[0]
|
| 280 |
-
device = encoder_text_hidden_states.device
|
| 281 |
-
|
| 282 |
-
# speaker embedding
|
| 283 |
-
encoder_spk_hidden_states = self.speaker_embedder(speaker_embeds).unsqueeze(1)
|
| 284 |
-
|
| 285 |
-
# genre embedding
|
| 286 |
-
encoder_text_hidden_states = self.genre_embedder(encoder_text_hidden_states)
|
| 287 |
-
|
| 288 |
-
# lyric
|
| 289 |
-
encoder_lyric_hidden_states = self.forward_lyric_encoder(
|
| 290 |
-
lyric_token_idx=lyric_token_idx,
|
| 291 |
-
lyric_mask=lyric_mask,
|
| 292 |
-
out_dtype=encoder_text_hidden_states.dtype,
|
| 293 |
-
)
|
| 294 |
-
|
| 295 |
-
encoder_lyric_hidden_states *= lyrics_strength
|
| 296 |
-
|
| 297 |
-
encoder_hidden_states = torch.cat([encoder_spk_hidden_states, encoder_text_hidden_states, encoder_lyric_hidden_states], dim=1)
|
| 298 |
-
|
| 299 |
-
encoder_hidden_mask = None
|
| 300 |
-
if text_attention_mask is not None:
|
| 301 |
-
speaker_mask = torch.ones(bs, 1, device=device)
|
| 302 |
-
encoder_hidden_mask = torch.cat([speaker_mask, text_attention_mask, lyric_mask], dim=1)
|
| 303 |
-
|
| 304 |
-
return encoder_hidden_states, encoder_hidden_mask
|
| 305 |
-
|
| 306 |
-
def decode(
|
| 307 |
-
self,
|
| 308 |
-
hidden_states: torch.Tensor,
|
| 309 |
-
attention_mask: torch.Tensor,
|
| 310 |
-
encoder_hidden_states: torch.Tensor,
|
| 311 |
-
encoder_hidden_mask: torch.Tensor,
|
| 312 |
-
timestep: Optional[torch.Tensor],
|
| 313 |
-
output_length: int = 0,
|
| 314 |
-
block_controlnet_hidden_states: Optional[Union[List[torch.Tensor], torch.Tensor]] = None,
|
| 315 |
-
controlnet_scale: Union[float, torch.Tensor] = 1.0,
|
| 316 |
-
):
|
| 317 |
-
embedded_timestep = self.timestep_embedder(self.time_proj(timestep).to(dtype=hidden_states.dtype))
|
| 318 |
-
temb = self.t_block(embedded_timestep)
|
| 319 |
-
|
| 320 |
-
hidden_states = self.proj_in(hidden_states)
|
| 321 |
-
|
| 322 |
-
# controlnet logic
|
| 323 |
-
if block_controlnet_hidden_states is not None:
|
| 324 |
-
control_condi = cross_norm(hidden_states, block_controlnet_hidden_states)
|
| 325 |
-
hidden_states = hidden_states + control_condi * controlnet_scale
|
| 326 |
-
|
| 327 |
-
# inner_hidden_states = []
|
| 328 |
-
|
| 329 |
-
rotary_freqs_cis = self.rotary_emb(hidden_states, seq_len=hidden_states.shape[1])
|
| 330 |
-
encoder_rotary_freqs_cis = self.rotary_emb(encoder_hidden_states, seq_len=encoder_hidden_states.shape[1])
|
| 331 |
-
|
| 332 |
-
for index_block, block in enumerate(self.transformer_blocks):
|
| 333 |
-
hidden_states = block(
|
| 334 |
-
hidden_states=hidden_states,
|
| 335 |
-
attention_mask=attention_mask,
|
| 336 |
-
encoder_hidden_states=encoder_hidden_states,
|
| 337 |
-
encoder_attention_mask=encoder_hidden_mask,
|
| 338 |
-
rotary_freqs_cis=rotary_freqs_cis,
|
| 339 |
-
rotary_freqs_cis_cross=encoder_rotary_freqs_cis,
|
| 340 |
-
temb=temb,
|
| 341 |
-
)
|
| 342 |
-
|
| 343 |
-
output = self.final_layer(hidden_states, embedded_timestep, output_length)
|
| 344 |
-
return output
|
| 345 |
-
|
| 346 |
-
def forward(
|
| 347 |
-
self,
|
| 348 |
-
x,
|
| 349 |
-
timestep,
|
| 350 |
-
attention_mask=None,
|
| 351 |
-
context: Optional[torch.Tensor] = None,
|
| 352 |
-
text_attention_mask: Optional[torch.LongTensor] = None,
|
| 353 |
-
speaker_embeds: Optional[torch.FloatTensor] = None,
|
| 354 |
-
lyric_token_idx: Optional[torch.LongTensor] = None,
|
| 355 |
-
lyric_mask: Optional[torch.LongTensor] = None,
|
| 356 |
-
block_controlnet_hidden_states: Optional[Union[List[torch.Tensor], torch.Tensor]] = None,
|
| 357 |
-
controlnet_scale: Union[float, torch.Tensor] = 1.0,
|
| 358 |
-
lyrics_strength=1.0,
|
| 359 |
-
**kwargs
|
| 360 |
-
):
|
| 361 |
-
hidden_states = x
|
| 362 |
-
encoder_text_hidden_states = context
|
| 363 |
-
encoder_hidden_states, encoder_hidden_mask = self.encode(
|
| 364 |
-
encoder_text_hidden_states=encoder_text_hidden_states,
|
| 365 |
-
text_attention_mask=text_attention_mask,
|
| 366 |
-
speaker_embeds=speaker_embeds,
|
| 367 |
-
lyric_token_idx=lyric_token_idx,
|
| 368 |
-
lyric_mask=lyric_mask,
|
| 369 |
-
lyrics_strength=lyrics_strength,
|
| 370 |
-
)
|
| 371 |
-
|
| 372 |
-
output_length = hidden_states.shape[-1]
|
| 373 |
-
|
| 374 |
-
output = self.decode(
|
| 375 |
-
hidden_states=hidden_states,
|
| 376 |
-
attention_mask=attention_mask,
|
| 377 |
-
encoder_hidden_states=encoder_hidden_states,
|
| 378 |
-
encoder_hidden_mask=encoder_hidden_mask,
|
| 379 |
-
timestep=timestep,
|
| 380 |
-
output_length=output_length,
|
| 381 |
-
block_controlnet_hidden_states=block_controlnet_hidden_states,
|
| 382 |
-
controlnet_scale=controlnet_scale,
|
| 383 |
-
)
|
| 384 |
-
|
| 385 |
-
return output
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/ace/vae/autoencoder_dc.py
DELETED
|
@@ -1,644 +0,0 @@
|
|
| 1 |
-
# Rewritten from diffusers
|
| 2 |
-
import torch
|
| 3 |
-
import torch.nn as nn
|
| 4 |
-
import torch.nn.functional as F
|
| 5 |
-
from typing import Tuple, Union
|
| 6 |
-
|
| 7 |
-
import comfy.model_management
|
| 8 |
-
import comfy.ops
|
| 9 |
-
ops = comfy.ops.disable_weight_init
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class RMSNorm(ops.RMSNorm):
|
| 13 |
-
def __init__(self, dim, eps=1e-5, elementwise_affine=True, bias=False):
|
| 14 |
-
super().__init__(dim, eps=eps, elementwise_affine=elementwise_affine)
|
| 15 |
-
if elementwise_affine:
|
| 16 |
-
self.bias = nn.Parameter(torch.empty(dim)) if bias else None
|
| 17 |
-
|
| 18 |
-
def forward(self, x):
|
| 19 |
-
x = super().forward(x)
|
| 20 |
-
if self.elementwise_affine:
|
| 21 |
-
if self.bias is not None:
|
| 22 |
-
x = x + comfy.model_management.cast_to(self.bias, dtype=x.dtype, device=x.device)
|
| 23 |
-
return x
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def get_normalization(norm_type, num_features, num_groups=32, eps=1e-5):
|
| 27 |
-
if norm_type == "batch_norm":
|
| 28 |
-
return nn.BatchNorm2d(num_features)
|
| 29 |
-
elif norm_type == "group_norm":
|
| 30 |
-
return ops.GroupNorm(num_groups, num_features)
|
| 31 |
-
elif norm_type == "layer_norm":
|
| 32 |
-
return ops.LayerNorm(num_features)
|
| 33 |
-
elif norm_type == "rms_norm":
|
| 34 |
-
return RMSNorm(num_features, eps=eps, elementwise_affine=True, bias=True)
|
| 35 |
-
else:
|
| 36 |
-
raise ValueError(f"Unknown normalization type: {norm_type}")
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def get_activation(activation_type):
|
| 40 |
-
if activation_type == "relu":
|
| 41 |
-
return nn.ReLU()
|
| 42 |
-
elif activation_type == "relu6":
|
| 43 |
-
return nn.ReLU6()
|
| 44 |
-
elif activation_type == "silu":
|
| 45 |
-
return nn.SiLU()
|
| 46 |
-
elif activation_type == "leaky_relu":
|
| 47 |
-
return nn.LeakyReLU(0.2)
|
| 48 |
-
else:
|
| 49 |
-
raise ValueError(f"Unknown activation type: {activation_type}")
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
class ResBlock(nn.Module):
|
| 53 |
-
def __init__(
|
| 54 |
-
self,
|
| 55 |
-
in_channels: int,
|
| 56 |
-
out_channels: int,
|
| 57 |
-
norm_type: str = "batch_norm",
|
| 58 |
-
act_fn: str = "relu6",
|
| 59 |
-
) -> None:
|
| 60 |
-
super().__init__()
|
| 61 |
-
|
| 62 |
-
self.norm_type = norm_type
|
| 63 |
-
self.nonlinearity = get_activation(act_fn) if act_fn is not None else nn.Identity()
|
| 64 |
-
self.conv1 = ops.Conv2d(in_channels, in_channels, 3, 1, 1)
|
| 65 |
-
self.conv2 = ops.Conv2d(in_channels, out_channels, 3, 1, 1, bias=False)
|
| 66 |
-
self.norm = get_normalization(norm_type, out_channels)
|
| 67 |
-
|
| 68 |
-
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 69 |
-
residual = hidden_states
|
| 70 |
-
hidden_states = self.conv1(hidden_states)
|
| 71 |
-
hidden_states = self.nonlinearity(hidden_states)
|
| 72 |
-
hidden_states = self.conv2(hidden_states)
|
| 73 |
-
|
| 74 |
-
if self.norm_type == "rms_norm":
|
| 75 |
-
# move channel to the last dimension so we apply RMSnorm across channel dimension
|
| 76 |
-
hidden_states = self.norm(hidden_states.movedim(1, -1)).movedim(-1, 1)
|
| 77 |
-
else:
|
| 78 |
-
hidden_states = self.norm(hidden_states)
|
| 79 |
-
|
| 80 |
-
return hidden_states + residual
|
| 81 |
-
|
| 82 |
-
class SanaMultiscaleAttentionProjection(nn.Module):
|
| 83 |
-
def __init__(
|
| 84 |
-
self,
|
| 85 |
-
in_channels: int,
|
| 86 |
-
num_attention_heads: int,
|
| 87 |
-
kernel_size: int,
|
| 88 |
-
) -> None:
|
| 89 |
-
super().__init__()
|
| 90 |
-
|
| 91 |
-
channels = 3 * in_channels
|
| 92 |
-
self.proj_in = ops.Conv2d(
|
| 93 |
-
channels,
|
| 94 |
-
channels,
|
| 95 |
-
kernel_size,
|
| 96 |
-
padding=kernel_size // 2,
|
| 97 |
-
groups=channels,
|
| 98 |
-
bias=False,
|
| 99 |
-
)
|
| 100 |
-
self.proj_out = ops.Conv2d(channels, channels, 1, 1, 0, groups=3 * num_attention_heads, bias=False)
|
| 101 |
-
|
| 102 |
-
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 103 |
-
hidden_states = self.proj_in(hidden_states)
|
| 104 |
-
hidden_states = self.proj_out(hidden_states)
|
| 105 |
-
return hidden_states
|
| 106 |
-
|
| 107 |
-
class SanaMultiscaleLinearAttention(nn.Module):
|
| 108 |
-
def __init__(
|
| 109 |
-
self,
|
| 110 |
-
in_channels: int,
|
| 111 |
-
out_channels: int,
|
| 112 |
-
num_attention_heads: int = None,
|
| 113 |
-
attention_head_dim: int = 8,
|
| 114 |
-
mult: float = 1.0,
|
| 115 |
-
norm_type: str = "batch_norm",
|
| 116 |
-
kernel_sizes: tuple = (5,),
|
| 117 |
-
eps: float = 1e-15,
|
| 118 |
-
residual_connection: bool = False,
|
| 119 |
-
):
|
| 120 |
-
super().__init__()
|
| 121 |
-
|
| 122 |
-
self.eps = eps
|
| 123 |
-
self.attention_head_dim = attention_head_dim
|
| 124 |
-
self.norm_type = norm_type
|
| 125 |
-
self.residual_connection = residual_connection
|
| 126 |
-
|
| 127 |
-
num_attention_heads = (
|
| 128 |
-
int(in_channels // attention_head_dim * mult)
|
| 129 |
-
if num_attention_heads is None
|
| 130 |
-
else num_attention_heads
|
| 131 |
-
)
|
| 132 |
-
inner_dim = num_attention_heads * attention_head_dim
|
| 133 |
-
|
| 134 |
-
self.to_q = ops.Linear(in_channels, inner_dim, bias=False)
|
| 135 |
-
self.to_k = ops.Linear(in_channels, inner_dim, bias=False)
|
| 136 |
-
self.to_v = ops.Linear(in_channels, inner_dim, bias=False)
|
| 137 |
-
|
| 138 |
-
self.to_qkv_multiscale = nn.ModuleList()
|
| 139 |
-
for kernel_size in kernel_sizes:
|
| 140 |
-
self.to_qkv_multiscale.append(
|
| 141 |
-
SanaMultiscaleAttentionProjection(inner_dim, num_attention_heads, kernel_size)
|
| 142 |
-
)
|
| 143 |
-
|
| 144 |
-
self.nonlinearity = nn.ReLU()
|
| 145 |
-
self.to_out = ops.Linear(inner_dim * (1 + len(kernel_sizes)), out_channels, bias=False)
|
| 146 |
-
self.norm_out = get_normalization(norm_type, out_channels)
|
| 147 |
-
|
| 148 |
-
def apply_linear_attention(self, query, key, value):
|
| 149 |
-
value = F.pad(value, (0, 0, 0, 1), mode="constant", value=1)
|
| 150 |
-
scores = torch.matmul(value, key.transpose(-1, -2))
|
| 151 |
-
hidden_states = torch.matmul(scores, query)
|
| 152 |
-
|
| 153 |
-
hidden_states = hidden_states.to(dtype=torch.float32)
|
| 154 |
-
hidden_states = hidden_states[:, :, :-1] / (hidden_states[:, :, -1:] + self.eps)
|
| 155 |
-
return hidden_states
|
| 156 |
-
|
| 157 |
-
def apply_quadratic_attention(self, query, key, value):
|
| 158 |
-
scores = torch.matmul(key.transpose(-1, -2), query)
|
| 159 |
-
scores = scores.to(dtype=torch.float32)
|
| 160 |
-
scores = scores / (torch.sum(scores, dim=2, keepdim=True) + self.eps)
|
| 161 |
-
hidden_states = torch.matmul(value, scores.to(value.dtype))
|
| 162 |
-
return hidden_states
|
| 163 |
-
|
| 164 |
-
def forward(self, hidden_states):
|
| 165 |
-
height, width = hidden_states.shape[-2:]
|
| 166 |
-
if height * width > self.attention_head_dim:
|
| 167 |
-
use_linear_attention = True
|
| 168 |
-
else:
|
| 169 |
-
use_linear_attention = False
|
| 170 |
-
|
| 171 |
-
residual = hidden_states
|
| 172 |
-
|
| 173 |
-
batch_size, _, height, width = list(hidden_states.size())
|
| 174 |
-
original_dtype = hidden_states.dtype
|
| 175 |
-
|
| 176 |
-
hidden_states = hidden_states.movedim(1, -1)
|
| 177 |
-
query = self.to_q(hidden_states)
|
| 178 |
-
key = self.to_k(hidden_states)
|
| 179 |
-
value = self.to_v(hidden_states)
|
| 180 |
-
hidden_states = torch.cat([query, key, value], dim=3)
|
| 181 |
-
hidden_states = hidden_states.movedim(-1, 1)
|
| 182 |
-
|
| 183 |
-
multi_scale_qkv = [hidden_states]
|
| 184 |
-
for block in self.to_qkv_multiscale:
|
| 185 |
-
multi_scale_qkv.append(block(hidden_states))
|
| 186 |
-
|
| 187 |
-
hidden_states = torch.cat(multi_scale_qkv, dim=1)
|
| 188 |
-
|
| 189 |
-
if use_linear_attention:
|
| 190 |
-
# for linear attention upcast hidden_states to float32
|
| 191 |
-
hidden_states = hidden_states.to(dtype=torch.float32)
|
| 192 |
-
|
| 193 |
-
hidden_states = hidden_states.reshape(batch_size, -1, 3 * self.attention_head_dim, height * width)
|
| 194 |
-
|
| 195 |
-
query, key, value = hidden_states.chunk(3, dim=2)
|
| 196 |
-
query = self.nonlinearity(query)
|
| 197 |
-
key = self.nonlinearity(key)
|
| 198 |
-
|
| 199 |
-
if use_linear_attention:
|
| 200 |
-
hidden_states = self.apply_linear_attention(query, key, value)
|
| 201 |
-
hidden_states = hidden_states.to(dtype=original_dtype)
|
| 202 |
-
else:
|
| 203 |
-
hidden_states = self.apply_quadratic_attention(query, key, value)
|
| 204 |
-
|
| 205 |
-
hidden_states = torch.reshape(hidden_states, (batch_size, -1, height, width))
|
| 206 |
-
hidden_states = self.to_out(hidden_states.movedim(1, -1)).movedim(-1, 1)
|
| 207 |
-
|
| 208 |
-
if self.norm_type == "rms_norm":
|
| 209 |
-
hidden_states = self.norm_out(hidden_states.movedim(1, -1)).movedim(-1, 1)
|
| 210 |
-
else:
|
| 211 |
-
hidden_states = self.norm_out(hidden_states)
|
| 212 |
-
|
| 213 |
-
if self.residual_connection:
|
| 214 |
-
hidden_states = hidden_states + residual
|
| 215 |
-
|
| 216 |
-
return hidden_states
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
class EfficientViTBlock(nn.Module):
|
| 220 |
-
def __init__(
|
| 221 |
-
self,
|
| 222 |
-
in_channels: int,
|
| 223 |
-
mult: float = 1.0,
|
| 224 |
-
attention_head_dim: int = 32,
|
| 225 |
-
qkv_multiscales: tuple = (5,),
|
| 226 |
-
norm_type: str = "batch_norm",
|
| 227 |
-
) -> None:
|
| 228 |
-
super().__init__()
|
| 229 |
-
|
| 230 |
-
self.attn = SanaMultiscaleLinearAttention(
|
| 231 |
-
in_channels=in_channels,
|
| 232 |
-
out_channels=in_channels,
|
| 233 |
-
mult=mult,
|
| 234 |
-
attention_head_dim=attention_head_dim,
|
| 235 |
-
norm_type=norm_type,
|
| 236 |
-
kernel_sizes=qkv_multiscales,
|
| 237 |
-
residual_connection=True,
|
| 238 |
-
)
|
| 239 |
-
|
| 240 |
-
self.conv_out = GLUMBConv(
|
| 241 |
-
in_channels=in_channels,
|
| 242 |
-
out_channels=in_channels,
|
| 243 |
-
norm_type="rms_norm",
|
| 244 |
-
)
|
| 245 |
-
|
| 246 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 247 |
-
x = self.attn(x)
|
| 248 |
-
x = self.conv_out(x)
|
| 249 |
-
return x
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
class GLUMBConv(nn.Module):
|
| 253 |
-
def __init__(
|
| 254 |
-
self,
|
| 255 |
-
in_channels: int,
|
| 256 |
-
out_channels: int,
|
| 257 |
-
expand_ratio: float = 4,
|
| 258 |
-
norm_type: str = None,
|
| 259 |
-
residual_connection: bool = True,
|
| 260 |
-
) -> None:
|
| 261 |
-
super().__init__()
|
| 262 |
-
|
| 263 |
-
hidden_channels = int(expand_ratio * in_channels)
|
| 264 |
-
self.norm_type = norm_type
|
| 265 |
-
self.residual_connection = residual_connection
|
| 266 |
-
|
| 267 |
-
self.nonlinearity = nn.SiLU()
|
| 268 |
-
self.conv_inverted = ops.Conv2d(in_channels, hidden_channels * 2, 1, 1, 0)
|
| 269 |
-
self.conv_depth = ops.Conv2d(hidden_channels * 2, hidden_channels * 2, 3, 1, 1, groups=hidden_channels * 2)
|
| 270 |
-
self.conv_point = ops.Conv2d(hidden_channels, out_channels, 1, 1, 0, bias=False)
|
| 271 |
-
|
| 272 |
-
self.norm = None
|
| 273 |
-
if norm_type == "rms_norm":
|
| 274 |
-
self.norm = RMSNorm(out_channels, eps=1e-5, elementwise_affine=True, bias=True)
|
| 275 |
-
|
| 276 |
-
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 277 |
-
if self.residual_connection:
|
| 278 |
-
residual = hidden_states
|
| 279 |
-
|
| 280 |
-
hidden_states = self.conv_inverted(hidden_states)
|
| 281 |
-
hidden_states = self.nonlinearity(hidden_states)
|
| 282 |
-
|
| 283 |
-
hidden_states = self.conv_depth(hidden_states)
|
| 284 |
-
hidden_states, gate = torch.chunk(hidden_states, 2, dim=1)
|
| 285 |
-
hidden_states = hidden_states * self.nonlinearity(gate)
|
| 286 |
-
|
| 287 |
-
hidden_states = self.conv_point(hidden_states)
|
| 288 |
-
|
| 289 |
-
if self.norm_type == "rms_norm":
|
| 290 |
-
# move channel to the last dimension so we apply RMSnorm across channel dimension
|
| 291 |
-
hidden_states = self.norm(hidden_states.movedim(1, -1)).movedim(-1, 1)
|
| 292 |
-
|
| 293 |
-
if self.residual_connection:
|
| 294 |
-
hidden_states = hidden_states + residual
|
| 295 |
-
|
| 296 |
-
return hidden_states
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
def get_block(
|
| 300 |
-
block_type: str,
|
| 301 |
-
in_channels: int,
|
| 302 |
-
out_channels: int,
|
| 303 |
-
attention_head_dim: int,
|
| 304 |
-
norm_type: str,
|
| 305 |
-
act_fn: str,
|
| 306 |
-
qkv_mutliscales: tuple = (),
|
| 307 |
-
):
|
| 308 |
-
if block_type == "ResBlock":
|
| 309 |
-
block = ResBlock(in_channels, out_channels, norm_type, act_fn)
|
| 310 |
-
elif block_type == "EfficientViTBlock":
|
| 311 |
-
block = EfficientViTBlock(
|
| 312 |
-
in_channels,
|
| 313 |
-
attention_head_dim=attention_head_dim,
|
| 314 |
-
norm_type=norm_type,
|
| 315 |
-
qkv_multiscales=qkv_mutliscales
|
| 316 |
-
)
|
| 317 |
-
else:
|
| 318 |
-
raise ValueError(f"Block with {block_type=} is not supported.")
|
| 319 |
-
|
| 320 |
-
return block
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
class DCDownBlock2d(nn.Module):
|
| 324 |
-
def __init__(self, in_channels: int, out_channels: int, downsample: bool = False, shortcut: bool = True) -> None:
|
| 325 |
-
super().__init__()
|
| 326 |
-
|
| 327 |
-
self.downsample = downsample
|
| 328 |
-
self.factor = 2
|
| 329 |
-
self.stride = 1 if downsample else 2
|
| 330 |
-
self.group_size = in_channels * self.factor**2 // out_channels
|
| 331 |
-
self.shortcut = shortcut
|
| 332 |
-
|
| 333 |
-
out_ratio = self.factor**2
|
| 334 |
-
if downsample:
|
| 335 |
-
assert out_channels % out_ratio == 0
|
| 336 |
-
out_channels = out_channels // out_ratio
|
| 337 |
-
|
| 338 |
-
self.conv = ops.Conv2d(
|
| 339 |
-
in_channels,
|
| 340 |
-
out_channels,
|
| 341 |
-
kernel_size=3,
|
| 342 |
-
stride=self.stride,
|
| 343 |
-
padding=1,
|
| 344 |
-
)
|
| 345 |
-
|
| 346 |
-
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 347 |
-
x = self.conv(hidden_states)
|
| 348 |
-
if self.downsample:
|
| 349 |
-
x = F.pixel_unshuffle(x, self.factor)
|
| 350 |
-
|
| 351 |
-
if self.shortcut:
|
| 352 |
-
y = F.pixel_unshuffle(hidden_states, self.factor)
|
| 353 |
-
y = y.unflatten(1, (-1, self.group_size))
|
| 354 |
-
y = y.mean(dim=2)
|
| 355 |
-
hidden_states = x + y
|
| 356 |
-
else:
|
| 357 |
-
hidden_states = x
|
| 358 |
-
|
| 359 |
-
return hidden_states
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
class DCUpBlock2d(nn.Module):
|
| 363 |
-
def __init__(
|
| 364 |
-
self,
|
| 365 |
-
in_channels: int,
|
| 366 |
-
out_channels: int,
|
| 367 |
-
interpolate: bool = False,
|
| 368 |
-
shortcut: bool = True,
|
| 369 |
-
interpolation_mode: str = "nearest",
|
| 370 |
-
) -> None:
|
| 371 |
-
super().__init__()
|
| 372 |
-
|
| 373 |
-
self.interpolate = interpolate
|
| 374 |
-
self.interpolation_mode = interpolation_mode
|
| 375 |
-
self.shortcut = shortcut
|
| 376 |
-
self.factor = 2
|
| 377 |
-
self.repeats = out_channels * self.factor**2 // in_channels
|
| 378 |
-
|
| 379 |
-
out_ratio = self.factor**2
|
| 380 |
-
if not interpolate:
|
| 381 |
-
out_channels = out_channels * out_ratio
|
| 382 |
-
|
| 383 |
-
self.conv = ops.Conv2d(in_channels, out_channels, 3, 1, 1)
|
| 384 |
-
|
| 385 |
-
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 386 |
-
if self.interpolate:
|
| 387 |
-
x = F.interpolate(hidden_states, scale_factor=self.factor, mode=self.interpolation_mode)
|
| 388 |
-
x = self.conv(x)
|
| 389 |
-
else:
|
| 390 |
-
x = self.conv(hidden_states)
|
| 391 |
-
x = F.pixel_shuffle(x, self.factor)
|
| 392 |
-
|
| 393 |
-
if self.shortcut:
|
| 394 |
-
y = hidden_states.repeat_interleave(self.repeats, dim=1, output_size=hidden_states.shape[1] * self.repeats)
|
| 395 |
-
y = F.pixel_shuffle(y, self.factor)
|
| 396 |
-
hidden_states = x + y
|
| 397 |
-
else:
|
| 398 |
-
hidden_states = x
|
| 399 |
-
|
| 400 |
-
return hidden_states
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
class Encoder(nn.Module):
|
| 404 |
-
def __init__(
|
| 405 |
-
self,
|
| 406 |
-
in_channels: int,
|
| 407 |
-
latent_channels: int,
|
| 408 |
-
attention_head_dim: int = 32,
|
| 409 |
-
block_type: str or tuple = "ResBlock",
|
| 410 |
-
block_out_channels: tuple = (128, 256, 512, 512, 1024, 1024),
|
| 411 |
-
layers_per_block: tuple = (2, 2, 2, 2, 2, 2),
|
| 412 |
-
qkv_multiscales: tuple = ((), (), (), (5,), (5,), (5,)),
|
| 413 |
-
downsample_block_type: str = "pixel_unshuffle",
|
| 414 |
-
out_shortcut: bool = True,
|
| 415 |
-
):
|
| 416 |
-
super().__init__()
|
| 417 |
-
|
| 418 |
-
num_blocks = len(block_out_channels)
|
| 419 |
-
|
| 420 |
-
if isinstance(block_type, str):
|
| 421 |
-
block_type = (block_type,) * num_blocks
|
| 422 |
-
|
| 423 |
-
if layers_per_block[0] > 0:
|
| 424 |
-
self.conv_in = ops.Conv2d(
|
| 425 |
-
in_channels,
|
| 426 |
-
block_out_channels[0] if layers_per_block[0] > 0 else block_out_channels[1],
|
| 427 |
-
kernel_size=3,
|
| 428 |
-
stride=1,
|
| 429 |
-
padding=1,
|
| 430 |
-
)
|
| 431 |
-
else:
|
| 432 |
-
self.conv_in = DCDownBlock2d(
|
| 433 |
-
in_channels=in_channels,
|
| 434 |
-
out_channels=block_out_channels[0] if layers_per_block[0] > 0 else block_out_channels[1],
|
| 435 |
-
downsample=downsample_block_type == "pixel_unshuffle",
|
| 436 |
-
shortcut=False,
|
| 437 |
-
)
|
| 438 |
-
|
| 439 |
-
down_blocks = []
|
| 440 |
-
for i, (out_channel, num_layers) in enumerate(zip(block_out_channels, layers_per_block)):
|
| 441 |
-
down_block_list = []
|
| 442 |
-
|
| 443 |
-
for _ in range(num_layers):
|
| 444 |
-
block = get_block(
|
| 445 |
-
block_type[i],
|
| 446 |
-
out_channel,
|
| 447 |
-
out_channel,
|
| 448 |
-
attention_head_dim=attention_head_dim,
|
| 449 |
-
norm_type="rms_norm",
|
| 450 |
-
act_fn="silu",
|
| 451 |
-
qkv_mutliscales=qkv_multiscales[i],
|
| 452 |
-
)
|
| 453 |
-
down_block_list.append(block)
|
| 454 |
-
|
| 455 |
-
if i < num_blocks - 1 and num_layers > 0:
|
| 456 |
-
downsample_block = DCDownBlock2d(
|
| 457 |
-
in_channels=out_channel,
|
| 458 |
-
out_channels=block_out_channels[i + 1],
|
| 459 |
-
downsample=downsample_block_type == "pixel_unshuffle",
|
| 460 |
-
shortcut=True,
|
| 461 |
-
)
|
| 462 |
-
down_block_list.append(downsample_block)
|
| 463 |
-
|
| 464 |
-
down_blocks.append(nn.Sequential(*down_block_list))
|
| 465 |
-
|
| 466 |
-
self.down_blocks = nn.ModuleList(down_blocks)
|
| 467 |
-
|
| 468 |
-
self.conv_out = ops.Conv2d(block_out_channels[-1], latent_channels, 3, 1, 1)
|
| 469 |
-
|
| 470 |
-
self.out_shortcut = out_shortcut
|
| 471 |
-
if out_shortcut:
|
| 472 |
-
self.out_shortcut_average_group_size = block_out_channels[-1] // latent_channels
|
| 473 |
-
|
| 474 |
-
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 475 |
-
hidden_states = self.conv_in(hidden_states)
|
| 476 |
-
for down_block in self.down_blocks:
|
| 477 |
-
hidden_states = down_block(hidden_states)
|
| 478 |
-
|
| 479 |
-
if self.out_shortcut:
|
| 480 |
-
x = hidden_states.unflatten(1, (-1, self.out_shortcut_average_group_size))
|
| 481 |
-
x = x.mean(dim=2)
|
| 482 |
-
hidden_states = self.conv_out(hidden_states) + x
|
| 483 |
-
else:
|
| 484 |
-
hidden_states = self.conv_out(hidden_states)
|
| 485 |
-
|
| 486 |
-
return hidden_states
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
class Decoder(nn.Module):
|
| 490 |
-
def __init__(
|
| 491 |
-
self,
|
| 492 |
-
in_channels: int,
|
| 493 |
-
latent_channels: int,
|
| 494 |
-
attention_head_dim: int = 32,
|
| 495 |
-
block_type: str or tuple = "ResBlock",
|
| 496 |
-
block_out_channels: tuple = (128, 256, 512, 512, 1024, 1024),
|
| 497 |
-
layers_per_block: tuple = (2, 2, 2, 2, 2, 2),
|
| 498 |
-
qkv_multiscales: tuple = ((), (), (), (5,), (5,), (5,)),
|
| 499 |
-
norm_type: str or tuple = "rms_norm",
|
| 500 |
-
act_fn: str or tuple = "silu",
|
| 501 |
-
upsample_block_type: str = "pixel_shuffle",
|
| 502 |
-
in_shortcut: bool = True,
|
| 503 |
-
):
|
| 504 |
-
super().__init__()
|
| 505 |
-
|
| 506 |
-
num_blocks = len(block_out_channels)
|
| 507 |
-
|
| 508 |
-
if isinstance(block_type, str):
|
| 509 |
-
block_type = (block_type,) * num_blocks
|
| 510 |
-
if isinstance(norm_type, str):
|
| 511 |
-
norm_type = (norm_type,) * num_blocks
|
| 512 |
-
if isinstance(act_fn, str):
|
| 513 |
-
act_fn = (act_fn,) * num_blocks
|
| 514 |
-
|
| 515 |
-
self.conv_in = ops.Conv2d(latent_channels, block_out_channels[-1], 3, 1, 1)
|
| 516 |
-
|
| 517 |
-
self.in_shortcut = in_shortcut
|
| 518 |
-
if in_shortcut:
|
| 519 |
-
self.in_shortcut_repeats = block_out_channels[-1] // latent_channels
|
| 520 |
-
|
| 521 |
-
up_blocks = []
|
| 522 |
-
for i, (out_channel, num_layers) in reversed(list(enumerate(zip(block_out_channels, layers_per_block)))):
|
| 523 |
-
up_block_list = []
|
| 524 |
-
|
| 525 |
-
if i < num_blocks - 1 and num_layers > 0:
|
| 526 |
-
upsample_block = DCUpBlock2d(
|
| 527 |
-
block_out_channels[i + 1],
|
| 528 |
-
out_channel,
|
| 529 |
-
interpolate=upsample_block_type == "interpolate",
|
| 530 |
-
shortcut=True,
|
| 531 |
-
)
|
| 532 |
-
up_block_list.append(upsample_block)
|
| 533 |
-
|
| 534 |
-
for _ in range(num_layers):
|
| 535 |
-
block = get_block(
|
| 536 |
-
block_type[i],
|
| 537 |
-
out_channel,
|
| 538 |
-
out_channel,
|
| 539 |
-
attention_head_dim=attention_head_dim,
|
| 540 |
-
norm_type=norm_type[i],
|
| 541 |
-
act_fn=act_fn[i],
|
| 542 |
-
qkv_mutliscales=qkv_multiscales[i],
|
| 543 |
-
)
|
| 544 |
-
up_block_list.append(block)
|
| 545 |
-
|
| 546 |
-
up_blocks.insert(0, nn.Sequential(*up_block_list))
|
| 547 |
-
|
| 548 |
-
self.up_blocks = nn.ModuleList(up_blocks)
|
| 549 |
-
|
| 550 |
-
channels = block_out_channels[0] if layers_per_block[0] > 0 else block_out_channels[1]
|
| 551 |
-
|
| 552 |
-
self.norm_out = RMSNorm(channels, 1e-5, elementwise_affine=True, bias=True)
|
| 553 |
-
self.conv_act = nn.ReLU()
|
| 554 |
-
self.conv_out = None
|
| 555 |
-
|
| 556 |
-
if layers_per_block[0] > 0:
|
| 557 |
-
self.conv_out = ops.Conv2d(channels, in_channels, 3, 1, 1)
|
| 558 |
-
else:
|
| 559 |
-
self.conv_out = DCUpBlock2d(
|
| 560 |
-
channels, in_channels, interpolate=upsample_block_type == "interpolate", shortcut=False
|
| 561 |
-
)
|
| 562 |
-
|
| 563 |
-
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 564 |
-
if self.in_shortcut:
|
| 565 |
-
x = hidden_states.repeat_interleave(
|
| 566 |
-
self.in_shortcut_repeats, dim=1, output_size=hidden_states.shape[1] * self.in_shortcut_repeats
|
| 567 |
-
)
|
| 568 |
-
hidden_states = self.conv_in(hidden_states) + x
|
| 569 |
-
else:
|
| 570 |
-
hidden_states = self.conv_in(hidden_states)
|
| 571 |
-
|
| 572 |
-
for up_block in reversed(self.up_blocks):
|
| 573 |
-
hidden_states = up_block(hidden_states)
|
| 574 |
-
|
| 575 |
-
hidden_states = self.norm_out(hidden_states.movedim(1, -1)).movedim(-1, 1)
|
| 576 |
-
hidden_states = self.conv_act(hidden_states)
|
| 577 |
-
hidden_states = self.conv_out(hidden_states)
|
| 578 |
-
return hidden_states
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
class AutoencoderDC(nn.Module):
|
| 582 |
-
def __init__(
|
| 583 |
-
self,
|
| 584 |
-
in_channels: int = 2,
|
| 585 |
-
latent_channels: int = 8,
|
| 586 |
-
attention_head_dim: int = 32,
|
| 587 |
-
encoder_block_types: Union[str, Tuple[str]] = ["ResBlock", "ResBlock", "ResBlock", "EfficientViTBlock"],
|
| 588 |
-
decoder_block_types: Union[str, Tuple[str]] = ["ResBlock", "ResBlock", "ResBlock", "EfficientViTBlock"],
|
| 589 |
-
encoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 1024),
|
| 590 |
-
decoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 1024),
|
| 591 |
-
encoder_layers_per_block: Tuple[int] = (2, 2, 3, 3),
|
| 592 |
-
decoder_layers_per_block: Tuple[int] = (3, 3, 3, 3),
|
| 593 |
-
encoder_qkv_multiscales: Tuple[Tuple[int, ...], ...] = ((), (), (5,), (5,)),
|
| 594 |
-
decoder_qkv_multiscales: Tuple[Tuple[int, ...], ...] = ((), (), (5,), (5,)),
|
| 595 |
-
upsample_block_type: str = "interpolate",
|
| 596 |
-
downsample_block_type: str = "Conv",
|
| 597 |
-
decoder_norm_types: Union[str, Tuple[str]] = "rms_norm",
|
| 598 |
-
decoder_act_fns: Union[str, Tuple[str]] = "silu",
|
| 599 |
-
scaling_factor: float = 0.41407,
|
| 600 |
-
) -> None:
|
| 601 |
-
super().__init__()
|
| 602 |
-
|
| 603 |
-
self.encoder = Encoder(
|
| 604 |
-
in_channels=in_channels,
|
| 605 |
-
latent_channels=latent_channels,
|
| 606 |
-
attention_head_dim=attention_head_dim,
|
| 607 |
-
block_type=encoder_block_types,
|
| 608 |
-
block_out_channels=encoder_block_out_channels,
|
| 609 |
-
layers_per_block=encoder_layers_per_block,
|
| 610 |
-
qkv_multiscales=encoder_qkv_multiscales,
|
| 611 |
-
downsample_block_type=downsample_block_type,
|
| 612 |
-
)
|
| 613 |
-
|
| 614 |
-
self.decoder = Decoder(
|
| 615 |
-
in_channels=in_channels,
|
| 616 |
-
latent_channels=latent_channels,
|
| 617 |
-
attention_head_dim=attention_head_dim,
|
| 618 |
-
block_type=decoder_block_types,
|
| 619 |
-
block_out_channels=decoder_block_out_channels,
|
| 620 |
-
layers_per_block=decoder_layers_per_block,
|
| 621 |
-
qkv_multiscales=decoder_qkv_multiscales,
|
| 622 |
-
norm_type=decoder_norm_types,
|
| 623 |
-
act_fn=decoder_act_fns,
|
| 624 |
-
upsample_block_type=upsample_block_type,
|
| 625 |
-
)
|
| 626 |
-
|
| 627 |
-
self.scaling_factor = scaling_factor
|
| 628 |
-
self.spatial_compression_ratio = 2 ** (len(encoder_block_out_channels) - 1)
|
| 629 |
-
|
| 630 |
-
def encode(self, x: torch.Tensor) -> torch.Tensor:
|
| 631 |
-
"""Internal encoding function."""
|
| 632 |
-
encoded = self.encoder(x)
|
| 633 |
-
return encoded * self.scaling_factor
|
| 634 |
-
|
| 635 |
-
def decode(self, z: torch.Tensor) -> torch.Tensor:
|
| 636 |
-
# Scale the latents back
|
| 637 |
-
z = z / self.scaling_factor
|
| 638 |
-
decoded = self.decoder(z)
|
| 639 |
-
return decoded
|
| 640 |
-
|
| 641 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 642 |
-
z = self.encode(x)
|
| 643 |
-
return self.decode(z)
|
| 644 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/ace/vae/music_dcae_pipeline.py
DELETED
|
@@ -1,109 +0,0 @@
|
|
| 1 |
-
# Original from: https://github.com/ace-step/ACE-Step/blob/main/music_dcae/music_dcae_pipeline.py
|
| 2 |
-
import torch
|
| 3 |
-
from .autoencoder_dc import AutoencoderDC
|
| 4 |
-
import logging
|
| 5 |
-
try:
|
| 6 |
-
import torchaudio
|
| 7 |
-
except:
|
| 8 |
-
logging.warning("torchaudio missing, ACE model will be broken")
|
| 9 |
-
|
| 10 |
-
import torchvision.transforms as transforms
|
| 11 |
-
from .music_vocoder import ADaMoSHiFiGANV1
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
class MusicDCAE(torch.nn.Module):
|
| 15 |
-
def __init__(self, source_sample_rate=None, dcae_config={}, vocoder_config={}):
|
| 16 |
-
super(MusicDCAE, self).__init__()
|
| 17 |
-
|
| 18 |
-
self.dcae = AutoencoderDC(**dcae_config)
|
| 19 |
-
self.vocoder = ADaMoSHiFiGANV1(**vocoder_config)
|
| 20 |
-
|
| 21 |
-
if source_sample_rate is None:
|
| 22 |
-
self.source_sample_rate = 48000
|
| 23 |
-
else:
|
| 24 |
-
self.source_sample_rate = source_sample_rate
|
| 25 |
-
|
| 26 |
-
# self.resampler = torchaudio.transforms.Resample(source_sample_rate, 44100)
|
| 27 |
-
|
| 28 |
-
self.transform = transforms.Compose([
|
| 29 |
-
transforms.Normalize(0.5, 0.5),
|
| 30 |
-
])
|
| 31 |
-
self.min_mel_value = -11.0
|
| 32 |
-
self.max_mel_value = 3.0
|
| 33 |
-
self.audio_chunk_size = int(round((1024 * 512 / 44100 * 48000)))
|
| 34 |
-
self.mel_chunk_size = 1024
|
| 35 |
-
self.time_dimention_multiple = 8
|
| 36 |
-
self.latent_chunk_size = self.mel_chunk_size // self.time_dimention_multiple
|
| 37 |
-
self.scale_factor = 0.1786
|
| 38 |
-
self.shift_factor = -1.9091
|
| 39 |
-
|
| 40 |
-
def load_audio(self, audio_path):
|
| 41 |
-
audio, sr = torchaudio.load(audio_path)
|
| 42 |
-
return audio, sr
|
| 43 |
-
|
| 44 |
-
def forward_mel(self, audios):
|
| 45 |
-
mels = []
|
| 46 |
-
for i in range(len(audios)):
|
| 47 |
-
image = self.vocoder.mel_transform(audios[i])
|
| 48 |
-
mels.append(image)
|
| 49 |
-
mels = torch.stack(mels)
|
| 50 |
-
return mels
|
| 51 |
-
|
| 52 |
-
@torch.no_grad()
|
| 53 |
-
def encode(self, audios, audio_lengths=None, sr=None):
|
| 54 |
-
if audio_lengths is None:
|
| 55 |
-
audio_lengths = torch.tensor([audios.shape[2]] * audios.shape[0])
|
| 56 |
-
audio_lengths = audio_lengths.to(audios.device)
|
| 57 |
-
|
| 58 |
-
if sr is None:
|
| 59 |
-
sr = self.source_sample_rate
|
| 60 |
-
|
| 61 |
-
if sr != 44100:
|
| 62 |
-
audios = torchaudio.functional.resample(audios, sr, 44100)
|
| 63 |
-
|
| 64 |
-
max_audio_len = audios.shape[-1]
|
| 65 |
-
if max_audio_len % (8 * 512) != 0:
|
| 66 |
-
audios = torch.nn.functional.pad(audios, (0, 8 * 512 - max_audio_len % (8 * 512)))
|
| 67 |
-
|
| 68 |
-
mels = self.forward_mel(audios)
|
| 69 |
-
mels = (mels - self.min_mel_value) / (self.max_mel_value - self.min_mel_value)
|
| 70 |
-
mels = self.transform(mels)
|
| 71 |
-
latents = []
|
| 72 |
-
for mel in mels:
|
| 73 |
-
latent = self.dcae.encoder(mel.unsqueeze(0))
|
| 74 |
-
latents.append(latent)
|
| 75 |
-
latents = torch.cat(latents, dim=0)
|
| 76 |
-
# latent_lengths = (audio_lengths / sr * 44100 / 512 / self.time_dimention_multiple).long()
|
| 77 |
-
latents = (latents - self.shift_factor) * self.scale_factor
|
| 78 |
-
return latents
|
| 79 |
-
# return latents, latent_lengths
|
| 80 |
-
|
| 81 |
-
@torch.no_grad()
|
| 82 |
-
def decode(self, latents, audio_lengths=None, sr=None):
|
| 83 |
-
latents = latents / self.scale_factor + self.shift_factor
|
| 84 |
-
|
| 85 |
-
pred_wavs = []
|
| 86 |
-
|
| 87 |
-
for latent in latents:
|
| 88 |
-
mels = self.dcae.decoder(latent.unsqueeze(0))
|
| 89 |
-
mels = mels * 0.5 + 0.5
|
| 90 |
-
mels = mels * (self.max_mel_value - self.min_mel_value) + self.min_mel_value
|
| 91 |
-
wav = self.vocoder.decode(mels[0]).squeeze(1)
|
| 92 |
-
|
| 93 |
-
if sr is not None:
|
| 94 |
-
# resampler = torchaudio.transforms.Resample(44100, sr).to(latents.device).to(latents.dtype)
|
| 95 |
-
wav = torchaudio.functional.resample(wav, 44100, sr)
|
| 96 |
-
# wav = resampler(wav)
|
| 97 |
-
else:
|
| 98 |
-
sr = 44100
|
| 99 |
-
pred_wavs.append(wav)
|
| 100 |
-
|
| 101 |
-
if audio_lengths is not None:
|
| 102 |
-
pred_wavs = [wav[:, :length].cpu() for wav, length in zip(pred_wavs, audio_lengths)]
|
| 103 |
-
return torch.stack(pred_wavs)
|
| 104 |
-
# return sr, pred_wavs
|
| 105 |
-
|
| 106 |
-
def forward(self, audios, audio_lengths=None, sr=None):
|
| 107 |
-
latents, latent_lengths = self.encode(audios=audios, audio_lengths=audio_lengths, sr=sr)
|
| 108 |
-
sr, pred_wavs = self.decode(latents=latents, audio_lengths=audio_lengths, sr=sr)
|
| 109 |
-
return sr, pred_wavs, latents, latent_lengths
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/ace/vae/music_log_mel.py
DELETED
|
@@ -1,113 +0,0 @@
|
|
| 1 |
-
# Original from: https://github.com/ace-step/ACE-Step/blob/main/music_dcae/music_log_mel.py
|
| 2 |
-
import torch
|
| 3 |
-
import torch.nn as nn
|
| 4 |
-
from torch import Tensor
|
| 5 |
-
import logging
|
| 6 |
-
try:
|
| 7 |
-
from torchaudio.transforms import MelScale
|
| 8 |
-
except:
|
| 9 |
-
logging.warning("torchaudio missing, ACE model will be broken")
|
| 10 |
-
|
| 11 |
-
import comfy.model_management
|
| 12 |
-
|
| 13 |
-
class LinearSpectrogram(nn.Module):
|
| 14 |
-
def __init__(
|
| 15 |
-
self,
|
| 16 |
-
n_fft=2048,
|
| 17 |
-
win_length=2048,
|
| 18 |
-
hop_length=512,
|
| 19 |
-
center=False,
|
| 20 |
-
mode="pow2_sqrt",
|
| 21 |
-
):
|
| 22 |
-
super().__init__()
|
| 23 |
-
|
| 24 |
-
self.n_fft = n_fft
|
| 25 |
-
self.win_length = win_length
|
| 26 |
-
self.hop_length = hop_length
|
| 27 |
-
self.center = center
|
| 28 |
-
self.mode = mode
|
| 29 |
-
|
| 30 |
-
self.register_buffer("window", torch.hann_window(win_length))
|
| 31 |
-
|
| 32 |
-
def forward(self, y: Tensor) -> Tensor:
|
| 33 |
-
if y.ndim == 3:
|
| 34 |
-
y = y.squeeze(1)
|
| 35 |
-
|
| 36 |
-
y = torch.nn.functional.pad(
|
| 37 |
-
y.unsqueeze(1),
|
| 38 |
-
(
|
| 39 |
-
(self.win_length - self.hop_length) // 2,
|
| 40 |
-
(self.win_length - self.hop_length + 1) // 2,
|
| 41 |
-
),
|
| 42 |
-
mode="reflect",
|
| 43 |
-
).squeeze(1)
|
| 44 |
-
dtype = y.dtype
|
| 45 |
-
spec = torch.stft(
|
| 46 |
-
y.float(),
|
| 47 |
-
self.n_fft,
|
| 48 |
-
hop_length=self.hop_length,
|
| 49 |
-
win_length=self.win_length,
|
| 50 |
-
window=comfy.model_management.cast_to(self.window, dtype=torch.float32, device=y.device),
|
| 51 |
-
center=self.center,
|
| 52 |
-
pad_mode="reflect",
|
| 53 |
-
normalized=False,
|
| 54 |
-
onesided=True,
|
| 55 |
-
return_complex=True,
|
| 56 |
-
)
|
| 57 |
-
spec = torch.view_as_real(spec)
|
| 58 |
-
|
| 59 |
-
if self.mode == "pow2_sqrt":
|
| 60 |
-
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
|
| 61 |
-
spec = spec.to(dtype)
|
| 62 |
-
return spec
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
class LogMelSpectrogram(nn.Module):
|
| 66 |
-
def __init__(
|
| 67 |
-
self,
|
| 68 |
-
sample_rate=44100,
|
| 69 |
-
n_fft=2048,
|
| 70 |
-
win_length=2048,
|
| 71 |
-
hop_length=512,
|
| 72 |
-
n_mels=128,
|
| 73 |
-
center=False,
|
| 74 |
-
f_min=0.0,
|
| 75 |
-
f_max=None,
|
| 76 |
-
):
|
| 77 |
-
super().__init__()
|
| 78 |
-
|
| 79 |
-
self.sample_rate = sample_rate
|
| 80 |
-
self.n_fft = n_fft
|
| 81 |
-
self.win_length = win_length
|
| 82 |
-
self.hop_length = hop_length
|
| 83 |
-
self.center = center
|
| 84 |
-
self.n_mels = n_mels
|
| 85 |
-
self.f_min = f_min
|
| 86 |
-
self.f_max = f_max or sample_rate // 2
|
| 87 |
-
|
| 88 |
-
self.spectrogram = LinearSpectrogram(n_fft, win_length, hop_length, center)
|
| 89 |
-
self.mel_scale = MelScale(
|
| 90 |
-
self.n_mels,
|
| 91 |
-
self.sample_rate,
|
| 92 |
-
self.f_min,
|
| 93 |
-
self.f_max,
|
| 94 |
-
self.n_fft // 2 + 1,
|
| 95 |
-
"slaney",
|
| 96 |
-
"slaney",
|
| 97 |
-
)
|
| 98 |
-
|
| 99 |
-
def compress(self, x: Tensor) -> Tensor:
|
| 100 |
-
return torch.log(torch.clamp(x, min=1e-5))
|
| 101 |
-
|
| 102 |
-
def decompress(self, x: Tensor) -> Tensor:
|
| 103 |
-
return torch.exp(x)
|
| 104 |
-
|
| 105 |
-
def forward(self, x: Tensor, return_linear: bool = False) -> Tensor:
|
| 106 |
-
linear = self.spectrogram(x)
|
| 107 |
-
x = self.mel_scale(linear)
|
| 108 |
-
x = self.compress(x)
|
| 109 |
-
# print(x.shape)
|
| 110 |
-
if return_linear:
|
| 111 |
-
return x, self.compress(linear)
|
| 112 |
-
|
| 113 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/ace/vae/music_vocoder.py
DELETED
|
@@ -1,538 +0,0 @@
|
|
| 1 |
-
# Original from: https://github.com/ace-step/ACE-Step/blob/main/music_dcae/music_vocoder.py
|
| 2 |
-
import torch
|
| 3 |
-
from torch import nn
|
| 4 |
-
|
| 5 |
-
from functools import partial
|
| 6 |
-
from math import prod
|
| 7 |
-
from typing import Callable, Tuple, List
|
| 8 |
-
|
| 9 |
-
import numpy as np
|
| 10 |
-
import torch.nn.functional as F
|
| 11 |
-
from torch.nn.utils.parametrize import remove_parametrizations as remove_weight_norm
|
| 12 |
-
|
| 13 |
-
from .music_log_mel import LogMelSpectrogram
|
| 14 |
-
|
| 15 |
-
import comfy.model_management
|
| 16 |
-
import comfy.ops
|
| 17 |
-
ops = comfy.ops.disable_weight_init
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def drop_path(
|
| 21 |
-
x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True
|
| 22 |
-
):
|
| 23 |
-
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 24 |
-
|
| 25 |
-
This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
|
| 26 |
-
the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 27 |
-
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
|
| 28 |
-
changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
|
| 29 |
-
'survival rate' as the argument.
|
| 30 |
-
|
| 31 |
-
""" # noqa: E501
|
| 32 |
-
|
| 33 |
-
if drop_prob == 0.0 or not training:
|
| 34 |
-
return x
|
| 35 |
-
keep_prob = 1 - drop_prob
|
| 36 |
-
shape = (x.shape[0],) + (1,) * (
|
| 37 |
-
x.ndim - 1
|
| 38 |
-
) # work with diff dim tensors, not just 2D ConvNets
|
| 39 |
-
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
|
| 40 |
-
if keep_prob > 0.0 and scale_by_keep:
|
| 41 |
-
random_tensor.div_(keep_prob)
|
| 42 |
-
return x * random_tensor
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
class DropPath(nn.Module):
|
| 46 |
-
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" # noqa: E501
|
| 47 |
-
|
| 48 |
-
def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True):
|
| 49 |
-
super(DropPath, self).__init__()
|
| 50 |
-
self.drop_prob = drop_prob
|
| 51 |
-
self.scale_by_keep = scale_by_keep
|
| 52 |
-
|
| 53 |
-
def forward(self, x):
|
| 54 |
-
return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
|
| 55 |
-
|
| 56 |
-
def extra_repr(self):
|
| 57 |
-
return f"drop_prob={round(self.drop_prob,3):0.3f}"
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
class LayerNorm(nn.Module):
|
| 61 |
-
r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
|
| 62 |
-
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
|
| 63 |
-
shape (batch_size, height, width, channels) while channels_first corresponds to inputs
|
| 64 |
-
with shape (batch_size, channels, height, width).
|
| 65 |
-
""" # noqa: E501
|
| 66 |
-
|
| 67 |
-
def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
|
| 68 |
-
super().__init__()
|
| 69 |
-
self.weight = nn.Parameter(torch.ones(normalized_shape))
|
| 70 |
-
self.bias = nn.Parameter(torch.zeros(normalized_shape))
|
| 71 |
-
self.eps = eps
|
| 72 |
-
self.data_format = data_format
|
| 73 |
-
if self.data_format not in ["channels_last", "channels_first"]:
|
| 74 |
-
raise NotImplementedError
|
| 75 |
-
self.normalized_shape = (normalized_shape,)
|
| 76 |
-
|
| 77 |
-
def forward(self, x):
|
| 78 |
-
if self.data_format == "channels_last":
|
| 79 |
-
return F.layer_norm(
|
| 80 |
-
x, self.normalized_shape, comfy.model_management.cast_to(self.weight, dtype=x.dtype, device=x.device), comfy.model_management.cast_to(self.bias, dtype=x.dtype, device=x.device), self.eps
|
| 81 |
-
)
|
| 82 |
-
elif self.data_format == "channels_first":
|
| 83 |
-
u = x.mean(1, keepdim=True)
|
| 84 |
-
s = (x - u).pow(2).mean(1, keepdim=True)
|
| 85 |
-
x = (x - u) / torch.sqrt(s + self.eps)
|
| 86 |
-
x = comfy.model_management.cast_to(self.weight[:, None], dtype=x.dtype, device=x.device) * x + comfy.model_management.cast_to(self.bias[:, None], dtype=x.dtype, device=x.device)
|
| 87 |
-
return x
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
class ConvNeXtBlock(nn.Module):
|
| 91 |
-
r"""ConvNeXt Block. There are two equivalent implementations:
|
| 92 |
-
(1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
|
| 93 |
-
(2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
|
| 94 |
-
We use (2) as we find it slightly faster in PyTorch
|
| 95 |
-
|
| 96 |
-
Args:
|
| 97 |
-
dim (int): Number of input channels.
|
| 98 |
-
drop_path (float): Stochastic depth rate. Default: 0.0
|
| 99 |
-
layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
|
| 100 |
-
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0.
|
| 101 |
-
kernel_size (int): Kernel size for depthwise conv. Default: 7.
|
| 102 |
-
dilation (int): Dilation for depthwise conv. Default: 1.
|
| 103 |
-
""" # noqa: E501
|
| 104 |
-
|
| 105 |
-
def __init__(
|
| 106 |
-
self,
|
| 107 |
-
dim: int,
|
| 108 |
-
drop_path: float = 0.0,
|
| 109 |
-
layer_scale_init_value: float = 1e-6,
|
| 110 |
-
mlp_ratio: float = 4.0,
|
| 111 |
-
kernel_size: int = 7,
|
| 112 |
-
dilation: int = 1,
|
| 113 |
-
):
|
| 114 |
-
super().__init__()
|
| 115 |
-
|
| 116 |
-
self.dwconv = ops.Conv1d(
|
| 117 |
-
dim,
|
| 118 |
-
dim,
|
| 119 |
-
kernel_size=kernel_size,
|
| 120 |
-
padding=int(dilation * (kernel_size - 1) / 2),
|
| 121 |
-
groups=dim,
|
| 122 |
-
) # depthwise conv
|
| 123 |
-
self.norm = LayerNorm(dim, eps=1e-6)
|
| 124 |
-
self.pwconv1 = ops.Linear(
|
| 125 |
-
dim, int(mlp_ratio * dim)
|
| 126 |
-
) # pointwise/1x1 convs, implemented with linear layers
|
| 127 |
-
self.act = nn.GELU()
|
| 128 |
-
self.pwconv2 = ops.Linear(int(mlp_ratio * dim), dim)
|
| 129 |
-
self.gamma = (
|
| 130 |
-
nn.Parameter(torch.empty((dim)), requires_grad=False)
|
| 131 |
-
if layer_scale_init_value > 0
|
| 132 |
-
else None
|
| 133 |
-
)
|
| 134 |
-
self.drop_path = DropPath(
|
| 135 |
-
drop_path) if drop_path > 0.0 else nn.Identity()
|
| 136 |
-
|
| 137 |
-
def forward(self, x, apply_residual: bool = True):
|
| 138 |
-
input = x
|
| 139 |
-
|
| 140 |
-
x = self.dwconv(x)
|
| 141 |
-
x = x.permute(0, 2, 1) # (N, C, L) -> (N, L, C)
|
| 142 |
-
x = self.norm(x)
|
| 143 |
-
x = self.pwconv1(x)
|
| 144 |
-
x = self.act(x)
|
| 145 |
-
x = self.pwconv2(x)
|
| 146 |
-
|
| 147 |
-
if self.gamma is not None:
|
| 148 |
-
x = comfy.model_management.cast_to(self.gamma, dtype=x.dtype, device=x.device) * x
|
| 149 |
-
|
| 150 |
-
x = x.permute(0, 2, 1) # (N, L, C) -> (N, C, L)
|
| 151 |
-
x = self.drop_path(x)
|
| 152 |
-
|
| 153 |
-
if apply_residual:
|
| 154 |
-
x = input + x
|
| 155 |
-
|
| 156 |
-
return x
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
class ParallelConvNeXtBlock(nn.Module):
|
| 160 |
-
def __init__(self, kernel_sizes: List[int], *args, **kwargs):
|
| 161 |
-
super().__init__()
|
| 162 |
-
self.blocks = nn.ModuleList(
|
| 163 |
-
[
|
| 164 |
-
ConvNeXtBlock(kernel_size=kernel_size, *args, **kwargs)
|
| 165 |
-
for kernel_size in kernel_sizes
|
| 166 |
-
]
|
| 167 |
-
)
|
| 168 |
-
|
| 169 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 170 |
-
return torch.stack(
|
| 171 |
-
[block(x, apply_residual=False) for block in self.blocks] + [x],
|
| 172 |
-
dim=1,
|
| 173 |
-
).sum(dim=1)
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
class ConvNeXtEncoder(nn.Module):
|
| 177 |
-
def __init__(
|
| 178 |
-
self,
|
| 179 |
-
input_channels=3,
|
| 180 |
-
depths=[3, 3, 9, 3],
|
| 181 |
-
dims=[96, 192, 384, 768],
|
| 182 |
-
drop_path_rate=0.0,
|
| 183 |
-
layer_scale_init_value=1e-6,
|
| 184 |
-
kernel_sizes: Tuple[int] = (7,),
|
| 185 |
-
):
|
| 186 |
-
super().__init__()
|
| 187 |
-
assert len(depths) == len(dims)
|
| 188 |
-
|
| 189 |
-
self.channel_layers = nn.ModuleList()
|
| 190 |
-
stem = nn.Sequential(
|
| 191 |
-
ops.Conv1d(
|
| 192 |
-
input_channels,
|
| 193 |
-
dims[0],
|
| 194 |
-
kernel_size=7,
|
| 195 |
-
padding=3,
|
| 196 |
-
padding_mode="replicate",
|
| 197 |
-
),
|
| 198 |
-
LayerNorm(dims[0], eps=1e-6, data_format="channels_first"),
|
| 199 |
-
)
|
| 200 |
-
self.channel_layers.append(stem)
|
| 201 |
-
|
| 202 |
-
for i in range(len(depths) - 1):
|
| 203 |
-
mid_layer = nn.Sequential(
|
| 204 |
-
LayerNorm(dims[i], eps=1e-6, data_format="channels_first"),
|
| 205 |
-
ops.Conv1d(dims[i], dims[i + 1], kernel_size=1),
|
| 206 |
-
)
|
| 207 |
-
self.channel_layers.append(mid_layer)
|
| 208 |
-
|
| 209 |
-
block_fn = (
|
| 210 |
-
partial(ConvNeXtBlock, kernel_size=kernel_sizes[0])
|
| 211 |
-
if len(kernel_sizes) == 1
|
| 212 |
-
else partial(ParallelConvNeXtBlock, kernel_sizes=kernel_sizes)
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
self.stages = nn.ModuleList()
|
| 216 |
-
drop_path_rates = [
|
| 217 |
-
x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
|
| 218 |
-
]
|
| 219 |
-
|
| 220 |
-
cur = 0
|
| 221 |
-
for i in range(len(depths)):
|
| 222 |
-
stage = nn.Sequential(
|
| 223 |
-
*[
|
| 224 |
-
block_fn(
|
| 225 |
-
dim=dims[i],
|
| 226 |
-
drop_path=drop_path_rates[cur + j],
|
| 227 |
-
layer_scale_init_value=layer_scale_init_value,
|
| 228 |
-
)
|
| 229 |
-
for j in range(depths[i])
|
| 230 |
-
]
|
| 231 |
-
)
|
| 232 |
-
self.stages.append(stage)
|
| 233 |
-
cur += depths[i]
|
| 234 |
-
|
| 235 |
-
self.norm = LayerNorm(dims[-1], eps=1e-6, data_format="channels_first")
|
| 236 |
-
|
| 237 |
-
def forward(
|
| 238 |
-
self,
|
| 239 |
-
x: torch.Tensor,
|
| 240 |
-
) -> torch.Tensor:
|
| 241 |
-
for channel_layer, stage in zip(self.channel_layers, self.stages):
|
| 242 |
-
x = channel_layer(x)
|
| 243 |
-
x = stage(x)
|
| 244 |
-
|
| 245 |
-
return self.norm(x)
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
def get_padding(kernel_size, dilation=1):
|
| 249 |
-
return (kernel_size * dilation - dilation) // 2
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
class ResBlock1(torch.nn.Module):
|
| 253 |
-
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
| 254 |
-
super().__init__()
|
| 255 |
-
|
| 256 |
-
self.convs1 = nn.ModuleList(
|
| 257 |
-
[
|
| 258 |
-
torch.nn.utils.parametrizations.weight_norm(
|
| 259 |
-
ops.Conv1d(
|
| 260 |
-
channels,
|
| 261 |
-
channels,
|
| 262 |
-
kernel_size,
|
| 263 |
-
1,
|
| 264 |
-
dilation=dilation[0],
|
| 265 |
-
padding=get_padding(kernel_size, dilation[0]),
|
| 266 |
-
)
|
| 267 |
-
),
|
| 268 |
-
torch.nn.utils.parametrizations.weight_norm(
|
| 269 |
-
ops.Conv1d(
|
| 270 |
-
channels,
|
| 271 |
-
channels,
|
| 272 |
-
kernel_size,
|
| 273 |
-
1,
|
| 274 |
-
dilation=dilation[1],
|
| 275 |
-
padding=get_padding(kernel_size, dilation[1]),
|
| 276 |
-
)
|
| 277 |
-
),
|
| 278 |
-
torch.nn.utils.parametrizations.weight_norm(
|
| 279 |
-
ops.Conv1d(
|
| 280 |
-
channels,
|
| 281 |
-
channels,
|
| 282 |
-
kernel_size,
|
| 283 |
-
1,
|
| 284 |
-
dilation=dilation[2],
|
| 285 |
-
padding=get_padding(kernel_size, dilation[2]),
|
| 286 |
-
)
|
| 287 |
-
),
|
| 288 |
-
]
|
| 289 |
-
)
|
| 290 |
-
|
| 291 |
-
self.convs2 = nn.ModuleList(
|
| 292 |
-
[
|
| 293 |
-
torch.nn.utils.parametrizations.weight_norm(
|
| 294 |
-
ops.Conv1d(
|
| 295 |
-
channels,
|
| 296 |
-
channels,
|
| 297 |
-
kernel_size,
|
| 298 |
-
1,
|
| 299 |
-
dilation=1,
|
| 300 |
-
padding=get_padding(kernel_size, 1),
|
| 301 |
-
)
|
| 302 |
-
),
|
| 303 |
-
torch.nn.utils.parametrizations.weight_norm(
|
| 304 |
-
ops.Conv1d(
|
| 305 |
-
channels,
|
| 306 |
-
channels,
|
| 307 |
-
kernel_size,
|
| 308 |
-
1,
|
| 309 |
-
dilation=1,
|
| 310 |
-
padding=get_padding(kernel_size, 1),
|
| 311 |
-
)
|
| 312 |
-
),
|
| 313 |
-
torch.nn.utils.parametrizations.weight_norm(
|
| 314 |
-
ops.Conv1d(
|
| 315 |
-
channels,
|
| 316 |
-
channels,
|
| 317 |
-
kernel_size,
|
| 318 |
-
1,
|
| 319 |
-
dilation=1,
|
| 320 |
-
padding=get_padding(kernel_size, 1),
|
| 321 |
-
)
|
| 322 |
-
),
|
| 323 |
-
]
|
| 324 |
-
)
|
| 325 |
-
|
| 326 |
-
def forward(self, x):
|
| 327 |
-
for c1, c2 in zip(self.convs1, self.convs2):
|
| 328 |
-
xt = F.silu(x)
|
| 329 |
-
xt = c1(xt)
|
| 330 |
-
xt = F.silu(xt)
|
| 331 |
-
xt = c2(xt)
|
| 332 |
-
x = xt + x
|
| 333 |
-
return x
|
| 334 |
-
|
| 335 |
-
def remove_weight_norm(self):
|
| 336 |
-
for conv in self.convs1:
|
| 337 |
-
remove_weight_norm(conv)
|
| 338 |
-
for conv in self.convs2:
|
| 339 |
-
remove_weight_norm(conv)
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
class HiFiGANGenerator(nn.Module):
|
| 343 |
-
def __init__(
|
| 344 |
-
self,
|
| 345 |
-
*,
|
| 346 |
-
hop_length: int = 512,
|
| 347 |
-
upsample_rates: Tuple[int] = (8, 8, 2, 2, 2),
|
| 348 |
-
upsample_kernel_sizes: Tuple[int] = (16, 16, 8, 2, 2),
|
| 349 |
-
resblock_kernel_sizes: Tuple[int] = (3, 7, 11),
|
| 350 |
-
resblock_dilation_sizes: Tuple[Tuple[int]] = (
|
| 351 |
-
(1, 3, 5), (1, 3, 5), (1, 3, 5)),
|
| 352 |
-
num_mels: int = 128,
|
| 353 |
-
upsample_initial_channel: int = 512,
|
| 354 |
-
use_template: bool = True,
|
| 355 |
-
pre_conv_kernel_size: int = 7,
|
| 356 |
-
post_conv_kernel_size: int = 7,
|
| 357 |
-
post_activation: Callable = partial(nn.SiLU, inplace=True),
|
| 358 |
-
):
|
| 359 |
-
super().__init__()
|
| 360 |
-
|
| 361 |
-
assert (
|
| 362 |
-
prod(upsample_rates) == hop_length
|
| 363 |
-
), f"hop_length must be {prod(upsample_rates)}"
|
| 364 |
-
|
| 365 |
-
self.conv_pre = torch.nn.utils.parametrizations.weight_norm(
|
| 366 |
-
ops.Conv1d(
|
| 367 |
-
num_mels,
|
| 368 |
-
upsample_initial_channel,
|
| 369 |
-
pre_conv_kernel_size,
|
| 370 |
-
1,
|
| 371 |
-
padding=get_padding(pre_conv_kernel_size),
|
| 372 |
-
)
|
| 373 |
-
)
|
| 374 |
-
|
| 375 |
-
self.num_upsamples = len(upsample_rates)
|
| 376 |
-
self.num_kernels = len(resblock_kernel_sizes)
|
| 377 |
-
|
| 378 |
-
self.noise_convs = nn.ModuleList()
|
| 379 |
-
self.use_template = use_template
|
| 380 |
-
self.ups = nn.ModuleList()
|
| 381 |
-
|
| 382 |
-
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
| 383 |
-
c_cur = upsample_initial_channel // (2 ** (i + 1))
|
| 384 |
-
self.ups.append(
|
| 385 |
-
torch.nn.utils.parametrizations.weight_norm(
|
| 386 |
-
ops.ConvTranspose1d(
|
| 387 |
-
upsample_initial_channel // (2**i),
|
| 388 |
-
upsample_initial_channel // (2 ** (i + 1)),
|
| 389 |
-
k,
|
| 390 |
-
u,
|
| 391 |
-
padding=(k - u) // 2,
|
| 392 |
-
)
|
| 393 |
-
)
|
| 394 |
-
)
|
| 395 |
-
|
| 396 |
-
if not use_template:
|
| 397 |
-
continue
|
| 398 |
-
|
| 399 |
-
if i + 1 < len(upsample_rates):
|
| 400 |
-
stride_f0 = np.prod(upsample_rates[i + 1:])
|
| 401 |
-
self.noise_convs.append(
|
| 402 |
-
ops.Conv1d(
|
| 403 |
-
1,
|
| 404 |
-
c_cur,
|
| 405 |
-
kernel_size=stride_f0 * 2,
|
| 406 |
-
stride=stride_f0,
|
| 407 |
-
padding=stride_f0 // 2,
|
| 408 |
-
)
|
| 409 |
-
)
|
| 410 |
-
else:
|
| 411 |
-
self.noise_convs.append(ops.Conv1d(1, c_cur, kernel_size=1))
|
| 412 |
-
|
| 413 |
-
self.resblocks = nn.ModuleList()
|
| 414 |
-
for i in range(len(self.ups)):
|
| 415 |
-
ch = upsample_initial_channel // (2 ** (i + 1))
|
| 416 |
-
for k, d in zip(resblock_kernel_sizes, resblock_dilation_sizes):
|
| 417 |
-
self.resblocks.append(ResBlock1(ch, k, d))
|
| 418 |
-
|
| 419 |
-
self.activation_post = post_activation()
|
| 420 |
-
self.conv_post = torch.nn.utils.parametrizations.weight_norm(
|
| 421 |
-
ops.Conv1d(
|
| 422 |
-
ch,
|
| 423 |
-
1,
|
| 424 |
-
post_conv_kernel_size,
|
| 425 |
-
1,
|
| 426 |
-
padding=get_padding(post_conv_kernel_size),
|
| 427 |
-
)
|
| 428 |
-
)
|
| 429 |
-
|
| 430 |
-
def forward(self, x, template=None):
|
| 431 |
-
x = self.conv_pre(x)
|
| 432 |
-
|
| 433 |
-
for i in range(self.num_upsamples):
|
| 434 |
-
x = F.silu(x, inplace=True)
|
| 435 |
-
x = self.ups[i](x)
|
| 436 |
-
|
| 437 |
-
if self.use_template:
|
| 438 |
-
x = x + self.noise_convs[i](template)
|
| 439 |
-
|
| 440 |
-
xs = None
|
| 441 |
-
|
| 442 |
-
for j in range(self.num_kernels):
|
| 443 |
-
if xs is None:
|
| 444 |
-
xs = self.resblocks[i * self.num_kernels + j](x)
|
| 445 |
-
else:
|
| 446 |
-
xs += self.resblocks[i * self.num_kernels + j](x)
|
| 447 |
-
|
| 448 |
-
x = xs / self.num_kernels
|
| 449 |
-
|
| 450 |
-
x = self.activation_post(x)
|
| 451 |
-
x = self.conv_post(x)
|
| 452 |
-
x = torch.tanh(x)
|
| 453 |
-
|
| 454 |
-
return x
|
| 455 |
-
|
| 456 |
-
def remove_weight_norm(self):
|
| 457 |
-
for up in self.ups:
|
| 458 |
-
remove_weight_norm(up)
|
| 459 |
-
for block in self.resblocks:
|
| 460 |
-
block.remove_weight_norm()
|
| 461 |
-
remove_weight_norm(self.conv_pre)
|
| 462 |
-
remove_weight_norm(self.conv_post)
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
class ADaMoSHiFiGANV1(nn.Module):
|
| 466 |
-
def __init__(
|
| 467 |
-
self,
|
| 468 |
-
input_channels: int = 128,
|
| 469 |
-
depths: List[int] = [3, 3, 9, 3],
|
| 470 |
-
dims: List[int] = [128, 256, 384, 512],
|
| 471 |
-
drop_path_rate: float = 0.0,
|
| 472 |
-
kernel_sizes: Tuple[int] = (7,),
|
| 473 |
-
upsample_rates: Tuple[int] = (4, 4, 2, 2, 2, 2, 2),
|
| 474 |
-
upsample_kernel_sizes: Tuple[int] = (8, 8, 4, 4, 4, 4, 4),
|
| 475 |
-
resblock_kernel_sizes: Tuple[int] = (3, 7, 11, 13),
|
| 476 |
-
resblock_dilation_sizes: Tuple[Tuple[int]] = (
|
| 477 |
-
(1, 3, 5), (1, 3, 5), (1, 3, 5), (1, 3, 5)),
|
| 478 |
-
num_mels: int = 512,
|
| 479 |
-
upsample_initial_channel: int = 1024,
|
| 480 |
-
use_template: bool = False,
|
| 481 |
-
pre_conv_kernel_size: int = 13,
|
| 482 |
-
post_conv_kernel_size: int = 13,
|
| 483 |
-
sampling_rate: int = 44100,
|
| 484 |
-
n_fft: int = 2048,
|
| 485 |
-
win_length: int = 2048,
|
| 486 |
-
hop_length: int = 512,
|
| 487 |
-
f_min: int = 40,
|
| 488 |
-
f_max: int = 16000,
|
| 489 |
-
n_mels: int = 128,
|
| 490 |
-
):
|
| 491 |
-
super().__init__()
|
| 492 |
-
|
| 493 |
-
self.backbone = ConvNeXtEncoder(
|
| 494 |
-
input_channels=input_channels,
|
| 495 |
-
depths=depths,
|
| 496 |
-
dims=dims,
|
| 497 |
-
drop_path_rate=drop_path_rate,
|
| 498 |
-
kernel_sizes=kernel_sizes,
|
| 499 |
-
)
|
| 500 |
-
|
| 501 |
-
self.head = HiFiGANGenerator(
|
| 502 |
-
hop_length=hop_length,
|
| 503 |
-
upsample_rates=upsample_rates,
|
| 504 |
-
upsample_kernel_sizes=upsample_kernel_sizes,
|
| 505 |
-
resblock_kernel_sizes=resblock_kernel_sizes,
|
| 506 |
-
resblock_dilation_sizes=resblock_dilation_sizes,
|
| 507 |
-
num_mels=num_mels,
|
| 508 |
-
upsample_initial_channel=upsample_initial_channel,
|
| 509 |
-
use_template=use_template,
|
| 510 |
-
pre_conv_kernel_size=pre_conv_kernel_size,
|
| 511 |
-
post_conv_kernel_size=post_conv_kernel_size,
|
| 512 |
-
)
|
| 513 |
-
self.sampling_rate = sampling_rate
|
| 514 |
-
self.mel_transform = LogMelSpectrogram(
|
| 515 |
-
sample_rate=sampling_rate,
|
| 516 |
-
n_fft=n_fft,
|
| 517 |
-
win_length=win_length,
|
| 518 |
-
hop_length=hop_length,
|
| 519 |
-
f_min=f_min,
|
| 520 |
-
f_max=f_max,
|
| 521 |
-
n_mels=n_mels,
|
| 522 |
-
)
|
| 523 |
-
self.eval()
|
| 524 |
-
|
| 525 |
-
@torch.no_grad()
|
| 526 |
-
def decode(self, mel):
|
| 527 |
-
y = self.backbone(mel)
|
| 528 |
-
y = self.head(y)
|
| 529 |
-
return y
|
| 530 |
-
|
| 531 |
-
@torch.no_grad()
|
| 532 |
-
def encode(self, x):
|
| 533 |
-
return self.mel_transform(x)
|
| 534 |
-
|
| 535 |
-
def forward(self, mel):
|
| 536 |
-
y = self.backbone(mel)
|
| 537 |
-
y = self.head(y)
|
| 538 |
-
return y
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/audio/autoencoder.py
DELETED
|
@@ -1,276 +0,0 @@
|
|
| 1 |
-
# code adapted from: https://github.com/Stability-AI/stable-audio-tools
|
| 2 |
-
|
| 3 |
-
import torch
|
| 4 |
-
from torch import nn
|
| 5 |
-
from typing import Literal
|
| 6 |
-
import math
|
| 7 |
-
import comfy.ops
|
| 8 |
-
ops = comfy.ops.disable_weight_init
|
| 9 |
-
|
| 10 |
-
def vae_sample(mean, scale):
|
| 11 |
-
stdev = nn.functional.softplus(scale) + 1e-4
|
| 12 |
-
var = stdev * stdev
|
| 13 |
-
logvar = torch.log(var)
|
| 14 |
-
latents = torch.randn_like(mean) * stdev + mean
|
| 15 |
-
|
| 16 |
-
kl = (mean * mean + var - logvar - 1).sum(1).mean()
|
| 17 |
-
|
| 18 |
-
return latents, kl
|
| 19 |
-
|
| 20 |
-
class VAEBottleneck(nn.Module):
|
| 21 |
-
def __init__(self):
|
| 22 |
-
super().__init__()
|
| 23 |
-
self.is_discrete = False
|
| 24 |
-
|
| 25 |
-
def encode(self, x, return_info=False, **kwargs):
|
| 26 |
-
info = {}
|
| 27 |
-
|
| 28 |
-
mean, scale = x.chunk(2, dim=1)
|
| 29 |
-
|
| 30 |
-
x, kl = vae_sample(mean, scale)
|
| 31 |
-
|
| 32 |
-
info["kl"] = kl
|
| 33 |
-
|
| 34 |
-
if return_info:
|
| 35 |
-
return x, info
|
| 36 |
-
else:
|
| 37 |
-
return x
|
| 38 |
-
|
| 39 |
-
def decode(self, x):
|
| 40 |
-
return x
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def snake_beta(x, alpha, beta):
|
| 44 |
-
return x + (1.0 / (beta + 0.000000001)) * pow(torch.sin(x * alpha), 2)
|
| 45 |
-
|
| 46 |
-
# Adapted from https://github.com/NVIDIA/BigVGAN/blob/main/activations.py under MIT license
|
| 47 |
-
class SnakeBeta(nn.Module):
|
| 48 |
-
|
| 49 |
-
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True):
|
| 50 |
-
super(SnakeBeta, self).__init__()
|
| 51 |
-
self.in_features = in_features
|
| 52 |
-
|
| 53 |
-
# initialize alpha
|
| 54 |
-
self.alpha_logscale = alpha_logscale
|
| 55 |
-
if self.alpha_logscale: # log scale alphas initialized to zeros
|
| 56 |
-
self.alpha = nn.Parameter(torch.zeros(in_features) * alpha)
|
| 57 |
-
self.beta = nn.Parameter(torch.zeros(in_features) * alpha)
|
| 58 |
-
else: # linear scale alphas initialized to ones
|
| 59 |
-
self.alpha = nn.Parameter(torch.ones(in_features) * alpha)
|
| 60 |
-
self.beta = nn.Parameter(torch.ones(in_features) * alpha)
|
| 61 |
-
|
| 62 |
-
# self.alpha.requires_grad = alpha_trainable
|
| 63 |
-
# self.beta.requires_grad = alpha_trainable
|
| 64 |
-
|
| 65 |
-
self.no_div_by_zero = 0.000000001
|
| 66 |
-
|
| 67 |
-
def forward(self, x):
|
| 68 |
-
alpha = self.alpha.unsqueeze(0).unsqueeze(-1).to(x.device) # line up with x to [B, C, T]
|
| 69 |
-
beta = self.beta.unsqueeze(0).unsqueeze(-1).to(x.device)
|
| 70 |
-
if self.alpha_logscale:
|
| 71 |
-
alpha = torch.exp(alpha)
|
| 72 |
-
beta = torch.exp(beta)
|
| 73 |
-
x = snake_beta(x, alpha, beta)
|
| 74 |
-
|
| 75 |
-
return x
|
| 76 |
-
|
| 77 |
-
def WNConv1d(*args, **kwargs):
|
| 78 |
-
return torch.nn.utils.parametrizations.weight_norm(ops.Conv1d(*args, **kwargs))
|
| 79 |
-
|
| 80 |
-
def WNConvTranspose1d(*args, **kwargs):
|
| 81 |
-
return torch.nn.utils.parametrizations.weight_norm(ops.ConvTranspose1d(*args, **kwargs))
|
| 82 |
-
|
| 83 |
-
def get_activation(activation: Literal["elu", "snake", "none"], antialias=False, channels=None) -> nn.Module:
|
| 84 |
-
if activation == "elu":
|
| 85 |
-
act = torch.nn.ELU()
|
| 86 |
-
elif activation == "snake":
|
| 87 |
-
act = SnakeBeta(channels)
|
| 88 |
-
elif activation == "none":
|
| 89 |
-
act = torch.nn.Identity()
|
| 90 |
-
else:
|
| 91 |
-
raise ValueError(f"Unknown activation {activation}")
|
| 92 |
-
|
| 93 |
-
if antialias:
|
| 94 |
-
act = Activation1d(act) # noqa: F821 Activation1d is not defined
|
| 95 |
-
|
| 96 |
-
return act
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
class ResidualUnit(nn.Module):
|
| 100 |
-
def __init__(self, in_channels, out_channels, dilation, use_snake=False, antialias_activation=False):
|
| 101 |
-
super().__init__()
|
| 102 |
-
|
| 103 |
-
self.dilation = dilation
|
| 104 |
-
|
| 105 |
-
padding = (dilation * (7-1)) // 2
|
| 106 |
-
|
| 107 |
-
self.layers = nn.Sequential(
|
| 108 |
-
get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=out_channels),
|
| 109 |
-
WNConv1d(in_channels=in_channels, out_channels=out_channels,
|
| 110 |
-
kernel_size=7, dilation=dilation, padding=padding),
|
| 111 |
-
get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=out_channels),
|
| 112 |
-
WNConv1d(in_channels=out_channels, out_channels=out_channels,
|
| 113 |
-
kernel_size=1)
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
def forward(self, x):
|
| 117 |
-
res = x
|
| 118 |
-
|
| 119 |
-
#x = checkpoint(self.layers, x)
|
| 120 |
-
x = self.layers(x)
|
| 121 |
-
|
| 122 |
-
return x + res
|
| 123 |
-
|
| 124 |
-
class EncoderBlock(nn.Module):
|
| 125 |
-
def __init__(self, in_channels, out_channels, stride, use_snake=False, antialias_activation=False):
|
| 126 |
-
super().__init__()
|
| 127 |
-
|
| 128 |
-
self.layers = nn.Sequential(
|
| 129 |
-
ResidualUnit(in_channels=in_channels,
|
| 130 |
-
out_channels=in_channels, dilation=1, use_snake=use_snake),
|
| 131 |
-
ResidualUnit(in_channels=in_channels,
|
| 132 |
-
out_channels=in_channels, dilation=3, use_snake=use_snake),
|
| 133 |
-
ResidualUnit(in_channels=in_channels,
|
| 134 |
-
out_channels=in_channels, dilation=9, use_snake=use_snake),
|
| 135 |
-
get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=in_channels),
|
| 136 |
-
WNConv1d(in_channels=in_channels, out_channels=out_channels,
|
| 137 |
-
kernel_size=2*stride, stride=stride, padding=math.ceil(stride/2)),
|
| 138 |
-
)
|
| 139 |
-
|
| 140 |
-
def forward(self, x):
|
| 141 |
-
return self.layers(x)
|
| 142 |
-
|
| 143 |
-
class DecoderBlock(nn.Module):
|
| 144 |
-
def __init__(self, in_channels, out_channels, stride, use_snake=False, antialias_activation=False, use_nearest_upsample=False):
|
| 145 |
-
super().__init__()
|
| 146 |
-
|
| 147 |
-
if use_nearest_upsample:
|
| 148 |
-
upsample_layer = nn.Sequential(
|
| 149 |
-
nn.Upsample(scale_factor=stride, mode="nearest"),
|
| 150 |
-
WNConv1d(in_channels=in_channels,
|
| 151 |
-
out_channels=out_channels,
|
| 152 |
-
kernel_size=2*stride,
|
| 153 |
-
stride=1,
|
| 154 |
-
bias=False,
|
| 155 |
-
padding='same')
|
| 156 |
-
)
|
| 157 |
-
else:
|
| 158 |
-
upsample_layer = WNConvTranspose1d(in_channels=in_channels,
|
| 159 |
-
out_channels=out_channels,
|
| 160 |
-
kernel_size=2*stride, stride=stride, padding=math.ceil(stride/2))
|
| 161 |
-
|
| 162 |
-
self.layers = nn.Sequential(
|
| 163 |
-
get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=in_channels),
|
| 164 |
-
upsample_layer,
|
| 165 |
-
ResidualUnit(in_channels=out_channels, out_channels=out_channels,
|
| 166 |
-
dilation=1, use_snake=use_snake),
|
| 167 |
-
ResidualUnit(in_channels=out_channels, out_channels=out_channels,
|
| 168 |
-
dilation=3, use_snake=use_snake),
|
| 169 |
-
ResidualUnit(in_channels=out_channels, out_channels=out_channels,
|
| 170 |
-
dilation=9, use_snake=use_snake),
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
def forward(self, x):
|
| 174 |
-
return self.layers(x)
|
| 175 |
-
|
| 176 |
-
class OobleckEncoder(nn.Module):
|
| 177 |
-
def __init__(self,
|
| 178 |
-
in_channels=2,
|
| 179 |
-
channels=128,
|
| 180 |
-
latent_dim=32,
|
| 181 |
-
c_mults = [1, 2, 4, 8],
|
| 182 |
-
strides = [2, 4, 8, 8],
|
| 183 |
-
use_snake=False,
|
| 184 |
-
antialias_activation=False
|
| 185 |
-
):
|
| 186 |
-
super().__init__()
|
| 187 |
-
|
| 188 |
-
c_mults = [1] + c_mults
|
| 189 |
-
|
| 190 |
-
self.depth = len(c_mults)
|
| 191 |
-
|
| 192 |
-
layers = [
|
| 193 |
-
WNConv1d(in_channels=in_channels, out_channels=c_mults[0] * channels, kernel_size=7, padding=3)
|
| 194 |
-
]
|
| 195 |
-
|
| 196 |
-
for i in range(self.depth-1):
|
| 197 |
-
layers += [EncoderBlock(in_channels=c_mults[i]*channels, out_channels=c_mults[i+1]*channels, stride=strides[i], use_snake=use_snake)]
|
| 198 |
-
|
| 199 |
-
layers += [
|
| 200 |
-
get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=c_mults[-1] * channels),
|
| 201 |
-
WNConv1d(in_channels=c_mults[-1]*channels, out_channels=latent_dim, kernel_size=3, padding=1)
|
| 202 |
-
]
|
| 203 |
-
|
| 204 |
-
self.layers = nn.Sequential(*layers)
|
| 205 |
-
|
| 206 |
-
def forward(self, x):
|
| 207 |
-
return self.layers(x)
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
class OobleckDecoder(nn.Module):
|
| 211 |
-
def __init__(self,
|
| 212 |
-
out_channels=2,
|
| 213 |
-
channels=128,
|
| 214 |
-
latent_dim=32,
|
| 215 |
-
c_mults = [1, 2, 4, 8],
|
| 216 |
-
strides = [2, 4, 8, 8],
|
| 217 |
-
use_snake=False,
|
| 218 |
-
antialias_activation=False,
|
| 219 |
-
use_nearest_upsample=False,
|
| 220 |
-
final_tanh=True):
|
| 221 |
-
super().__init__()
|
| 222 |
-
|
| 223 |
-
c_mults = [1] + c_mults
|
| 224 |
-
|
| 225 |
-
self.depth = len(c_mults)
|
| 226 |
-
|
| 227 |
-
layers = [
|
| 228 |
-
WNConv1d(in_channels=latent_dim, out_channels=c_mults[-1]*channels, kernel_size=7, padding=3),
|
| 229 |
-
]
|
| 230 |
-
|
| 231 |
-
for i in range(self.depth-1, 0, -1):
|
| 232 |
-
layers += [DecoderBlock(
|
| 233 |
-
in_channels=c_mults[i]*channels,
|
| 234 |
-
out_channels=c_mults[i-1]*channels,
|
| 235 |
-
stride=strides[i-1],
|
| 236 |
-
use_snake=use_snake,
|
| 237 |
-
antialias_activation=antialias_activation,
|
| 238 |
-
use_nearest_upsample=use_nearest_upsample
|
| 239 |
-
)
|
| 240 |
-
]
|
| 241 |
-
|
| 242 |
-
layers += [
|
| 243 |
-
get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=c_mults[0] * channels),
|
| 244 |
-
WNConv1d(in_channels=c_mults[0] * channels, out_channels=out_channels, kernel_size=7, padding=3, bias=False),
|
| 245 |
-
nn.Tanh() if final_tanh else nn.Identity()
|
| 246 |
-
]
|
| 247 |
-
|
| 248 |
-
self.layers = nn.Sequential(*layers)
|
| 249 |
-
|
| 250 |
-
def forward(self, x):
|
| 251 |
-
return self.layers(x)
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
class AudioOobleckVAE(nn.Module):
|
| 255 |
-
def __init__(self,
|
| 256 |
-
in_channels=2,
|
| 257 |
-
channels=128,
|
| 258 |
-
latent_dim=64,
|
| 259 |
-
c_mults = [1, 2, 4, 8, 16],
|
| 260 |
-
strides = [2, 4, 4, 8, 8],
|
| 261 |
-
use_snake=True,
|
| 262 |
-
antialias_activation=False,
|
| 263 |
-
use_nearest_upsample=False,
|
| 264 |
-
final_tanh=False):
|
| 265 |
-
super().__init__()
|
| 266 |
-
self.encoder = OobleckEncoder(in_channels, channels, latent_dim * 2, c_mults, strides, use_snake, antialias_activation)
|
| 267 |
-
self.decoder = OobleckDecoder(in_channels, channels, latent_dim, c_mults, strides, use_snake, antialias_activation,
|
| 268 |
-
use_nearest_upsample=use_nearest_upsample, final_tanh=final_tanh)
|
| 269 |
-
self.bottleneck = VAEBottleneck()
|
| 270 |
-
|
| 271 |
-
def encode(self, x):
|
| 272 |
-
return self.bottleneck.encode(self.encoder(x))
|
| 273 |
-
|
| 274 |
-
def decode(self, x):
|
| 275 |
-
return self.decoder(self.bottleneck.decode(x))
|
| 276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/audio/dit.py
DELETED
|
@@ -1,896 +0,0 @@
|
|
| 1 |
-
# code adapted from: https://github.com/Stability-AI/stable-audio-tools
|
| 2 |
-
|
| 3 |
-
from comfy.ldm.modules.attention import optimized_attention
|
| 4 |
-
import typing as tp
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
|
| 8 |
-
from einops import rearrange
|
| 9 |
-
from torch import nn
|
| 10 |
-
from torch.nn import functional as F
|
| 11 |
-
import math
|
| 12 |
-
import comfy.ops
|
| 13 |
-
|
| 14 |
-
class FourierFeatures(nn.Module):
|
| 15 |
-
def __init__(self, in_features, out_features, std=1., dtype=None, device=None):
|
| 16 |
-
super().__init__()
|
| 17 |
-
assert out_features % 2 == 0
|
| 18 |
-
self.weight = nn.Parameter(torch.empty(
|
| 19 |
-
[out_features // 2, in_features], dtype=dtype, device=device))
|
| 20 |
-
|
| 21 |
-
def forward(self, input):
|
| 22 |
-
f = 2 * math.pi * input @ comfy.ops.cast_to_input(self.weight.T, input)
|
| 23 |
-
return torch.cat([f.cos(), f.sin()], dim=-1)
|
| 24 |
-
|
| 25 |
-
# norms
|
| 26 |
-
class LayerNorm(nn.Module):
|
| 27 |
-
def __init__(self, dim, bias=False, fix_scale=False, dtype=None, device=None):
|
| 28 |
-
"""
|
| 29 |
-
bias-less layernorm has been shown to be more stable. most newer models have moved towards rmsnorm, also bias-less
|
| 30 |
-
"""
|
| 31 |
-
super().__init__()
|
| 32 |
-
|
| 33 |
-
self.gamma = nn.Parameter(torch.empty(dim, dtype=dtype, device=device))
|
| 34 |
-
|
| 35 |
-
if bias:
|
| 36 |
-
self.beta = nn.Parameter(torch.empty(dim, dtype=dtype, device=device))
|
| 37 |
-
else:
|
| 38 |
-
self.beta = None
|
| 39 |
-
|
| 40 |
-
def forward(self, x):
|
| 41 |
-
beta = self.beta
|
| 42 |
-
if beta is not None:
|
| 43 |
-
beta = comfy.ops.cast_to_input(beta, x)
|
| 44 |
-
return F.layer_norm(x, x.shape[-1:], weight=comfy.ops.cast_to_input(self.gamma, x), bias=beta)
|
| 45 |
-
|
| 46 |
-
class GLU(nn.Module):
|
| 47 |
-
def __init__(
|
| 48 |
-
self,
|
| 49 |
-
dim_in,
|
| 50 |
-
dim_out,
|
| 51 |
-
activation,
|
| 52 |
-
use_conv = False,
|
| 53 |
-
conv_kernel_size = 3,
|
| 54 |
-
dtype=None,
|
| 55 |
-
device=None,
|
| 56 |
-
operations=None,
|
| 57 |
-
):
|
| 58 |
-
super().__init__()
|
| 59 |
-
self.act = activation
|
| 60 |
-
self.proj = operations.Linear(dim_in, dim_out * 2, dtype=dtype, device=device) if not use_conv else operations.Conv1d(dim_in, dim_out * 2, conv_kernel_size, padding = (conv_kernel_size // 2), dtype=dtype, device=device)
|
| 61 |
-
self.use_conv = use_conv
|
| 62 |
-
|
| 63 |
-
def forward(self, x):
|
| 64 |
-
if self.use_conv:
|
| 65 |
-
x = rearrange(x, 'b n d -> b d n')
|
| 66 |
-
x = self.proj(x)
|
| 67 |
-
x = rearrange(x, 'b d n -> b n d')
|
| 68 |
-
else:
|
| 69 |
-
x = self.proj(x)
|
| 70 |
-
|
| 71 |
-
x, gate = x.chunk(2, dim = -1)
|
| 72 |
-
return x * self.act(gate)
|
| 73 |
-
|
| 74 |
-
class AbsolutePositionalEmbedding(nn.Module):
|
| 75 |
-
def __init__(self, dim, max_seq_len):
|
| 76 |
-
super().__init__()
|
| 77 |
-
self.scale = dim ** -0.5
|
| 78 |
-
self.max_seq_len = max_seq_len
|
| 79 |
-
self.emb = nn.Embedding(max_seq_len, dim)
|
| 80 |
-
|
| 81 |
-
def forward(self, x, pos = None, seq_start_pos = None):
|
| 82 |
-
seq_len, device = x.shape[1], x.device
|
| 83 |
-
assert seq_len <= self.max_seq_len, f'you are passing in a sequence length of {seq_len} but your absolute positional embedding has a max sequence length of {self.max_seq_len}'
|
| 84 |
-
|
| 85 |
-
if pos is None:
|
| 86 |
-
pos = torch.arange(seq_len, device = device)
|
| 87 |
-
|
| 88 |
-
if seq_start_pos is not None:
|
| 89 |
-
pos = (pos - seq_start_pos[..., None]).clamp(min = 0)
|
| 90 |
-
|
| 91 |
-
pos_emb = self.emb(pos)
|
| 92 |
-
pos_emb = pos_emb * self.scale
|
| 93 |
-
return pos_emb
|
| 94 |
-
|
| 95 |
-
class ScaledSinusoidalEmbedding(nn.Module):
|
| 96 |
-
def __init__(self, dim, theta = 10000):
|
| 97 |
-
super().__init__()
|
| 98 |
-
assert (dim % 2) == 0, 'dimension must be divisible by 2'
|
| 99 |
-
self.scale = nn.Parameter(torch.ones(1) * dim ** -0.5)
|
| 100 |
-
|
| 101 |
-
half_dim = dim // 2
|
| 102 |
-
freq_seq = torch.arange(half_dim).float() / half_dim
|
| 103 |
-
inv_freq = theta ** -freq_seq
|
| 104 |
-
self.register_buffer('inv_freq', inv_freq, persistent = False)
|
| 105 |
-
|
| 106 |
-
def forward(self, x, pos = None, seq_start_pos = None):
|
| 107 |
-
seq_len, device = x.shape[1], x.device
|
| 108 |
-
|
| 109 |
-
if pos is None:
|
| 110 |
-
pos = torch.arange(seq_len, device = device)
|
| 111 |
-
|
| 112 |
-
if seq_start_pos is not None:
|
| 113 |
-
pos = pos - seq_start_pos[..., None]
|
| 114 |
-
|
| 115 |
-
emb = torch.einsum('i, j -> i j', pos, self.inv_freq)
|
| 116 |
-
emb = torch.cat((emb.sin(), emb.cos()), dim = -1)
|
| 117 |
-
return emb * self.scale
|
| 118 |
-
|
| 119 |
-
class RotaryEmbedding(nn.Module):
|
| 120 |
-
def __init__(
|
| 121 |
-
self,
|
| 122 |
-
dim,
|
| 123 |
-
use_xpos = False,
|
| 124 |
-
scale_base = 512,
|
| 125 |
-
interpolation_factor = 1.,
|
| 126 |
-
base = 10000,
|
| 127 |
-
base_rescale_factor = 1.,
|
| 128 |
-
dtype=None,
|
| 129 |
-
device=None,
|
| 130 |
-
):
|
| 131 |
-
super().__init__()
|
| 132 |
-
# proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
|
| 133 |
-
# has some connection to NTK literature
|
| 134 |
-
# https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/
|
| 135 |
-
base *= base_rescale_factor ** (dim / (dim - 2))
|
| 136 |
-
|
| 137 |
-
# inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 138 |
-
self.register_buffer('inv_freq', torch.empty((dim // 2,), device=device, dtype=dtype))
|
| 139 |
-
|
| 140 |
-
assert interpolation_factor >= 1.
|
| 141 |
-
self.interpolation_factor = interpolation_factor
|
| 142 |
-
|
| 143 |
-
if not use_xpos:
|
| 144 |
-
self.register_buffer('scale', None)
|
| 145 |
-
return
|
| 146 |
-
|
| 147 |
-
scale = (torch.arange(0, dim, 2) + 0.4 * dim) / (1.4 * dim)
|
| 148 |
-
|
| 149 |
-
self.scale_base = scale_base
|
| 150 |
-
self.register_buffer('scale', scale)
|
| 151 |
-
|
| 152 |
-
def forward_from_seq_len(self, seq_len, device, dtype):
|
| 153 |
-
# device = self.inv_freq.device
|
| 154 |
-
|
| 155 |
-
t = torch.arange(seq_len, device=device, dtype=dtype)
|
| 156 |
-
return self.forward(t)
|
| 157 |
-
|
| 158 |
-
def forward(self, t):
|
| 159 |
-
# device = self.inv_freq.device
|
| 160 |
-
device = t.device
|
| 161 |
-
|
| 162 |
-
# t = t.to(torch.float32)
|
| 163 |
-
|
| 164 |
-
t = t / self.interpolation_factor
|
| 165 |
-
|
| 166 |
-
freqs = torch.einsum('i , j -> i j', t, comfy.ops.cast_to_input(self.inv_freq, t))
|
| 167 |
-
freqs = torch.cat((freqs, freqs), dim = -1)
|
| 168 |
-
|
| 169 |
-
if self.scale is None:
|
| 170 |
-
return freqs, 1.
|
| 171 |
-
|
| 172 |
-
power = (torch.arange(seq_len, device = device) - (seq_len // 2)) / self.scale_base # noqa: F821 seq_len is not defined
|
| 173 |
-
scale = comfy.ops.cast_to_input(self.scale, t) ** rearrange(power, 'n -> n 1')
|
| 174 |
-
scale = torch.cat((scale, scale), dim = -1)
|
| 175 |
-
|
| 176 |
-
return freqs, scale
|
| 177 |
-
|
| 178 |
-
def rotate_half(x):
|
| 179 |
-
x = rearrange(x, '... (j d) -> ... j d', j = 2)
|
| 180 |
-
x1, x2 = x.unbind(dim = -2)
|
| 181 |
-
return torch.cat((-x2, x1), dim = -1)
|
| 182 |
-
|
| 183 |
-
def apply_rotary_pos_emb(t, freqs, scale = 1):
|
| 184 |
-
out_dtype = t.dtype
|
| 185 |
-
|
| 186 |
-
# cast to float32 if necessary for numerical stability
|
| 187 |
-
dtype = t.dtype #reduce(torch.promote_types, (t.dtype, freqs.dtype, torch.float32))
|
| 188 |
-
rot_dim, seq_len = freqs.shape[-1], t.shape[-2]
|
| 189 |
-
freqs, t = freqs.to(dtype), t.to(dtype)
|
| 190 |
-
freqs = freqs[-seq_len:, :]
|
| 191 |
-
|
| 192 |
-
if t.ndim == 4 and freqs.ndim == 3:
|
| 193 |
-
freqs = rearrange(freqs, 'b n d -> b 1 n d')
|
| 194 |
-
|
| 195 |
-
# partial rotary embeddings, Wang et al. GPT-J
|
| 196 |
-
t, t_unrotated = t[..., :rot_dim], t[..., rot_dim:]
|
| 197 |
-
t = (t * freqs.cos() * scale) + (rotate_half(t) * freqs.sin() * scale)
|
| 198 |
-
|
| 199 |
-
t, t_unrotated = t.to(out_dtype), t_unrotated.to(out_dtype)
|
| 200 |
-
|
| 201 |
-
return torch.cat((t, t_unrotated), dim = -1)
|
| 202 |
-
|
| 203 |
-
class FeedForward(nn.Module):
|
| 204 |
-
def __init__(
|
| 205 |
-
self,
|
| 206 |
-
dim,
|
| 207 |
-
dim_out = None,
|
| 208 |
-
mult = 4,
|
| 209 |
-
no_bias = False,
|
| 210 |
-
glu = True,
|
| 211 |
-
use_conv = False,
|
| 212 |
-
conv_kernel_size = 3,
|
| 213 |
-
zero_init_output = True,
|
| 214 |
-
dtype=None,
|
| 215 |
-
device=None,
|
| 216 |
-
operations=None,
|
| 217 |
-
):
|
| 218 |
-
super().__init__()
|
| 219 |
-
inner_dim = int(dim * mult)
|
| 220 |
-
|
| 221 |
-
# Default to SwiGLU
|
| 222 |
-
|
| 223 |
-
activation = nn.SiLU()
|
| 224 |
-
|
| 225 |
-
dim_out = dim if dim_out is None else dim_out
|
| 226 |
-
|
| 227 |
-
if glu:
|
| 228 |
-
linear_in = GLU(dim, inner_dim, activation, dtype=dtype, device=device, operations=operations)
|
| 229 |
-
else:
|
| 230 |
-
linear_in = nn.Sequential(
|
| 231 |
-
rearrange('b n d -> b d n') if use_conv else nn.Identity(),
|
| 232 |
-
operations.Linear(dim, inner_dim, bias = not no_bias, dtype=dtype, device=device) if not use_conv else operations.Conv1d(dim, inner_dim, conv_kernel_size, padding = (conv_kernel_size // 2), bias = not no_bias, dtype=dtype, device=device),
|
| 233 |
-
rearrange('b n d -> b d n') if use_conv else nn.Identity(),
|
| 234 |
-
activation
|
| 235 |
-
)
|
| 236 |
-
|
| 237 |
-
linear_out = operations.Linear(inner_dim, dim_out, bias = not no_bias, dtype=dtype, device=device) if not use_conv else operations.Conv1d(inner_dim, dim_out, conv_kernel_size, padding = (conv_kernel_size // 2), bias = not no_bias, dtype=dtype, device=device)
|
| 238 |
-
|
| 239 |
-
# # init last linear layer to 0
|
| 240 |
-
# if zero_init_output:
|
| 241 |
-
# nn.init.zeros_(linear_out.weight)
|
| 242 |
-
# if not no_bias:
|
| 243 |
-
# nn.init.zeros_(linear_out.bias)
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
self.ff = nn.Sequential(
|
| 247 |
-
linear_in,
|
| 248 |
-
rearrange('b d n -> b n d') if use_conv else nn.Identity(),
|
| 249 |
-
linear_out,
|
| 250 |
-
rearrange('b n d -> b d n') if use_conv else nn.Identity(),
|
| 251 |
-
)
|
| 252 |
-
|
| 253 |
-
def forward(self, x):
|
| 254 |
-
return self.ff(x)
|
| 255 |
-
|
| 256 |
-
class Attention(nn.Module):
|
| 257 |
-
def __init__(
|
| 258 |
-
self,
|
| 259 |
-
dim,
|
| 260 |
-
dim_heads = 64,
|
| 261 |
-
dim_context = None,
|
| 262 |
-
causal = False,
|
| 263 |
-
zero_init_output=True,
|
| 264 |
-
qk_norm = False,
|
| 265 |
-
natten_kernel_size = None,
|
| 266 |
-
dtype=None,
|
| 267 |
-
device=None,
|
| 268 |
-
operations=None,
|
| 269 |
-
):
|
| 270 |
-
super().__init__()
|
| 271 |
-
self.dim = dim
|
| 272 |
-
self.dim_heads = dim_heads
|
| 273 |
-
self.causal = causal
|
| 274 |
-
|
| 275 |
-
dim_kv = dim_context if dim_context is not None else dim
|
| 276 |
-
|
| 277 |
-
self.num_heads = dim // dim_heads
|
| 278 |
-
self.kv_heads = dim_kv // dim_heads
|
| 279 |
-
|
| 280 |
-
if dim_context is not None:
|
| 281 |
-
self.to_q = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 282 |
-
self.to_kv = operations.Linear(dim_kv, dim_kv * 2, bias=False, dtype=dtype, device=device)
|
| 283 |
-
else:
|
| 284 |
-
self.to_qkv = operations.Linear(dim, dim * 3, bias=False, dtype=dtype, device=device)
|
| 285 |
-
|
| 286 |
-
self.to_out = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 287 |
-
|
| 288 |
-
# if zero_init_output:
|
| 289 |
-
# nn.init.zeros_(self.to_out.weight)
|
| 290 |
-
|
| 291 |
-
self.qk_norm = qk_norm
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
def forward(
|
| 295 |
-
self,
|
| 296 |
-
x,
|
| 297 |
-
context = None,
|
| 298 |
-
mask = None,
|
| 299 |
-
context_mask = None,
|
| 300 |
-
rotary_pos_emb = None,
|
| 301 |
-
causal = None
|
| 302 |
-
):
|
| 303 |
-
h, kv_h, has_context = self.num_heads, self.kv_heads, context is not None
|
| 304 |
-
|
| 305 |
-
kv_input = context if has_context else x
|
| 306 |
-
|
| 307 |
-
if hasattr(self, 'to_q'):
|
| 308 |
-
# Use separate linear projections for q and k/v
|
| 309 |
-
q = self.to_q(x)
|
| 310 |
-
q = rearrange(q, 'b n (h d) -> b h n d', h = h)
|
| 311 |
-
|
| 312 |
-
k, v = self.to_kv(kv_input).chunk(2, dim=-1)
|
| 313 |
-
|
| 314 |
-
k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = kv_h), (k, v))
|
| 315 |
-
else:
|
| 316 |
-
# Use fused linear projection
|
| 317 |
-
q, k, v = self.to_qkv(x).chunk(3, dim=-1)
|
| 318 |
-
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), (q, k, v))
|
| 319 |
-
|
| 320 |
-
# Normalize q and k for cosine sim attention
|
| 321 |
-
if self.qk_norm:
|
| 322 |
-
q = F.normalize(q, dim=-1)
|
| 323 |
-
k = F.normalize(k, dim=-1)
|
| 324 |
-
|
| 325 |
-
if rotary_pos_emb is not None and not has_context:
|
| 326 |
-
freqs, _ = rotary_pos_emb
|
| 327 |
-
|
| 328 |
-
q_dtype = q.dtype
|
| 329 |
-
k_dtype = k.dtype
|
| 330 |
-
|
| 331 |
-
q = q.to(torch.float32)
|
| 332 |
-
k = k.to(torch.float32)
|
| 333 |
-
freqs = freqs.to(torch.float32)
|
| 334 |
-
|
| 335 |
-
q = apply_rotary_pos_emb(q, freqs)
|
| 336 |
-
k = apply_rotary_pos_emb(k, freqs)
|
| 337 |
-
|
| 338 |
-
q = q.to(q_dtype)
|
| 339 |
-
k = k.to(k_dtype)
|
| 340 |
-
|
| 341 |
-
input_mask = context_mask
|
| 342 |
-
|
| 343 |
-
if input_mask is None and not has_context:
|
| 344 |
-
input_mask = mask
|
| 345 |
-
|
| 346 |
-
# determine masking
|
| 347 |
-
masks = []
|
| 348 |
-
|
| 349 |
-
if input_mask is not None:
|
| 350 |
-
input_mask = rearrange(input_mask, 'b j -> b 1 1 j')
|
| 351 |
-
masks.append(~input_mask)
|
| 352 |
-
|
| 353 |
-
# Other masks will be added here later
|
| 354 |
-
n = q.shape[-2]
|
| 355 |
-
|
| 356 |
-
causal = self.causal if causal is None else causal
|
| 357 |
-
|
| 358 |
-
if n == 1 and causal:
|
| 359 |
-
causal = False
|
| 360 |
-
|
| 361 |
-
if h != kv_h:
|
| 362 |
-
# Repeat interleave kv_heads to match q_heads
|
| 363 |
-
heads_per_kv_head = h // kv_h
|
| 364 |
-
k, v = map(lambda t: t.repeat_interleave(heads_per_kv_head, dim = 1), (k, v))
|
| 365 |
-
|
| 366 |
-
out = optimized_attention(q, k, v, h, skip_reshape=True)
|
| 367 |
-
out = self.to_out(out)
|
| 368 |
-
|
| 369 |
-
if mask is not None:
|
| 370 |
-
mask = rearrange(mask, 'b n -> b n 1')
|
| 371 |
-
out = out.masked_fill(~mask, 0.)
|
| 372 |
-
|
| 373 |
-
return out
|
| 374 |
-
|
| 375 |
-
class ConformerModule(nn.Module):
|
| 376 |
-
def __init__(
|
| 377 |
-
self,
|
| 378 |
-
dim,
|
| 379 |
-
norm_kwargs = {},
|
| 380 |
-
):
|
| 381 |
-
|
| 382 |
-
super().__init__()
|
| 383 |
-
|
| 384 |
-
self.dim = dim
|
| 385 |
-
|
| 386 |
-
self.in_norm = LayerNorm(dim, **norm_kwargs)
|
| 387 |
-
self.pointwise_conv = nn.Conv1d(dim, dim, kernel_size=1, bias=False)
|
| 388 |
-
self.glu = GLU(dim, dim, nn.SiLU())
|
| 389 |
-
self.depthwise_conv = nn.Conv1d(dim, dim, kernel_size=17, groups=dim, padding=8, bias=False)
|
| 390 |
-
self.mid_norm = LayerNorm(dim, **norm_kwargs) # This is a batch norm in the original but I don't like batch norm
|
| 391 |
-
self.swish = nn.SiLU()
|
| 392 |
-
self.pointwise_conv_2 = nn.Conv1d(dim, dim, kernel_size=1, bias=False)
|
| 393 |
-
|
| 394 |
-
def forward(self, x):
|
| 395 |
-
x = self.in_norm(x)
|
| 396 |
-
x = rearrange(x, 'b n d -> b d n')
|
| 397 |
-
x = self.pointwise_conv(x)
|
| 398 |
-
x = rearrange(x, 'b d n -> b n d')
|
| 399 |
-
x = self.glu(x)
|
| 400 |
-
x = rearrange(x, 'b n d -> b d n')
|
| 401 |
-
x = self.depthwise_conv(x)
|
| 402 |
-
x = rearrange(x, 'b d n -> b n d')
|
| 403 |
-
x = self.mid_norm(x)
|
| 404 |
-
x = self.swish(x)
|
| 405 |
-
x = rearrange(x, 'b n d -> b d n')
|
| 406 |
-
x = self.pointwise_conv_2(x)
|
| 407 |
-
x = rearrange(x, 'b d n -> b n d')
|
| 408 |
-
|
| 409 |
-
return x
|
| 410 |
-
|
| 411 |
-
class TransformerBlock(nn.Module):
|
| 412 |
-
def __init__(
|
| 413 |
-
self,
|
| 414 |
-
dim,
|
| 415 |
-
dim_heads = 64,
|
| 416 |
-
cross_attend = False,
|
| 417 |
-
dim_context = None,
|
| 418 |
-
global_cond_dim = None,
|
| 419 |
-
causal = False,
|
| 420 |
-
zero_init_branch_outputs = True,
|
| 421 |
-
conformer = False,
|
| 422 |
-
layer_ix = -1,
|
| 423 |
-
remove_norms = False,
|
| 424 |
-
attn_kwargs = {},
|
| 425 |
-
ff_kwargs = {},
|
| 426 |
-
norm_kwargs = {},
|
| 427 |
-
dtype=None,
|
| 428 |
-
device=None,
|
| 429 |
-
operations=None,
|
| 430 |
-
):
|
| 431 |
-
|
| 432 |
-
super().__init__()
|
| 433 |
-
self.dim = dim
|
| 434 |
-
self.dim_heads = dim_heads
|
| 435 |
-
self.cross_attend = cross_attend
|
| 436 |
-
self.dim_context = dim_context
|
| 437 |
-
self.causal = causal
|
| 438 |
-
|
| 439 |
-
self.pre_norm = LayerNorm(dim, dtype=dtype, device=device, **norm_kwargs) if not remove_norms else nn.Identity()
|
| 440 |
-
|
| 441 |
-
self.self_attn = Attention(
|
| 442 |
-
dim,
|
| 443 |
-
dim_heads = dim_heads,
|
| 444 |
-
causal = causal,
|
| 445 |
-
zero_init_output=zero_init_branch_outputs,
|
| 446 |
-
dtype=dtype,
|
| 447 |
-
device=device,
|
| 448 |
-
operations=operations,
|
| 449 |
-
**attn_kwargs
|
| 450 |
-
)
|
| 451 |
-
|
| 452 |
-
if cross_attend:
|
| 453 |
-
self.cross_attend_norm = LayerNorm(dim, dtype=dtype, device=device, **norm_kwargs) if not remove_norms else nn.Identity()
|
| 454 |
-
self.cross_attn = Attention(
|
| 455 |
-
dim,
|
| 456 |
-
dim_heads = dim_heads,
|
| 457 |
-
dim_context=dim_context,
|
| 458 |
-
causal = causal,
|
| 459 |
-
zero_init_output=zero_init_branch_outputs,
|
| 460 |
-
dtype=dtype,
|
| 461 |
-
device=device,
|
| 462 |
-
operations=operations,
|
| 463 |
-
**attn_kwargs
|
| 464 |
-
)
|
| 465 |
-
|
| 466 |
-
self.ff_norm = LayerNorm(dim, dtype=dtype, device=device, **norm_kwargs) if not remove_norms else nn.Identity()
|
| 467 |
-
self.ff = FeedForward(dim, zero_init_output=zero_init_branch_outputs, dtype=dtype, device=device, operations=operations,**ff_kwargs)
|
| 468 |
-
|
| 469 |
-
self.layer_ix = layer_ix
|
| 470 |
-
|
| 471 |
-
self.conformer = ConformerModule(dim, norm_kwargs=norm_kwargs) if conformer else None
|
| 472 |
-
|
| 473 |
-
self.global_cond_dim = global_cond_dim
|
| 474 |
-
|
| 475 |
-
if global_cond_dim is not None:
|
| 476 |
-
self.to_scale_shift_gate = nn.Sequential(
|
| 477 |
-
nn.SiLU(),
|
| 478 |
-
nn.Linear(global_cond_dim, dim * 6, bias=False)
|
| 479 |
-
)
|
| 480 |
-
|
| 481 |
-
nn.init.zeros_(self.to_scale_shift_gate[1].weight)
|
| 482 |
-
#nn.init.zeros_(self.to_scale_shift_gate_self[1].bias)
|
| 483 |
-
|
| 484 |
-
def forward(
|
| 485 |
-
self,
|
| 486 |
-
x,
|
| 487 |
-
context = None,
|
| 488 |
-
global_cond=None,
|
| 489 |
-
mask = None,
|
| 490 |
-
context_mask = None,
|
| 491 |
-
rotary_pos_emb = None
|
| 492 |
-
):
|
| 493 |
-
if self.global_cond_dim is not None and self.global_cond_dim > 0 and global_cond is not None:
|
| 494 |
-
|
| 495 |
-
scale_self, shift_self, gate_self, scale_ff, shift_ff, gate_ff = self.to_scale_shift_gate(global_cond).unsqueeze(1).chunk(6, dim = -1)
|
| 496 |
-
|
| 497 |
-
# self-attention with adaLN
|
| 498 |
-
residual = x
|
| 499 |
-
x = self.pre_norm(x)
|
| 500 |
-
x = x * (1 + scale_self) + shift_self
|
| 501 |
-
x = self.self_attn(x, mask = mask, rotary_pos_emb = rotary_pos_emb)
|
| 502 |
-
x = x * torch.sigmoid(1 - gate_self)
|
| 503 |
-
x = x + residual
|
| 504 |
-
|
| 505 |
-
if context is not None:
|
| 506 |
-
x = x + self.cross_attn(self.cross_attend_norm(x), context = context, context_mask = context_mask)
|
| 507 |
-
|
| 508 |
-
if self.conformer is not None:
|
| 509 |
-
x = x + self.conformer(x)
|
| 510 |
-
|
| 511 |
-
# feedforward with adaLN
|
| 512 |
-
residual = x
|
| 513 |
-
x = self.ff_norm(x)
|
| 514 |
-
x = x * (1 + scale_ff) + shift_ff
|
| 515 |
-
x = self.ff(x)
|
| 516 |
-
x = x * torch.sigmoid(1 - gate_ff)
|
| 517 |
-
x = x + residual
|
| 518 |
-
|
| 519 |
-
else:
|
| 520 |
-
x = x + self.self_attn(self.pre_norm(x), mask = mask, rotary_pos_emb = rotary_pos_emb)
|
| 521 |
-
|
| 522 |
-
if context is not None:
|
| 523 |
-
x = x + self.cross_attn(self.cross_attend_norm(x), context = context, context_mask = context_mask)
|
| 524 |
-
|
| 525 |
-
if self.conformer is not None:
|
| 526 |
-
x = x + self.conformer(x)
|
| 527 |
-
|
| 528 |
-
x = x + self.ff(self.ff_norm(x))
|
| 529 |
-
|
| 530 |
-
return x
|
| 531 |
-
|
| 532 |
-
class ContinuousTransformer(nn.Module):
|
| 533 |
-
def __init__(
|
| 534 |
-
self,
|
| 535 |
-
dim,
|
| 536 |
-
depth,
|
| 537 |
-
*,
|
| 538 |
-
dim_in = None,
|
| 539 |
-
dim_out = None,
|
| 540 |
-
dim_heads = 64,
|
| 541 |
-
cross_attend=False,
|
| 542 |
-
cond_token_dim=None,
|
| 543 |
-
global_cond_dim=None,
|
| 544 |
-
causal=False,
|
| 545 |
-
rotary_pos_emb=True,
|
| 546 |
-
zero_init_branch_outputs=True,
|
| 547 |
-
conformer=False,
|
| 548 |
-
use_sinusoidal_emb=False,
|
| 549 |
-
use_abs_pos_emb=False,
|
| 550 |
-
abs_pos_emb_max_length=10000,
|
| 551 |
-
dtype=None,
|
| 552 |
-
device=None,
|
| 553 |
-
operations=None,
|
| 554 |
-
**kwargs
|
| 555 |
-
):
|
| 556 |
-
|
| 557 |
-
super().__init__()
|
| 558 |
-
|
| 559 |
-
self.dim = dim
|
| 560 |
-
self.depth = depth
|
| 561 |
-
self.causal = causal
|
| 562 |
-
self.layers = nn.ModuleList([])
|
| 563 |
-
|
| 564 |
-
self.project_in = operations.Linear(dim_in, dim, bias=False, dtype=dtype, device=device) if dim_in is not None else nn.Identity()
|
| 565 |
-
self.project_out = operations.Linear(dim, dim_out, bias=False, dtype=dtype, device=device) if dim_out is not None else nn.Identity()
|
| 566 |
-
|
| 567 |
-
if rotary_pos_emb:
|
| 568 |
-
self.rotary_pos_emb = RotaryEmbedding(max(dim_heads // 2, 32), device=device, dtype=dtype)
|
| 569 |
-
else:
|
| 570 |
-
self.rotary_pos_emb = None
|
| 571 |
-
|
| 572 |
-
self.use_sinusoidal_emb = use_sinusoidal_emb
|
| 573 |
-
if use_sinusoidal_emb:
|
| 574 |
-
self.pos_emb = ScaledSinusoidalEmbedding(dim)
|
| 575 |
-
|
| 576 |
-
self.use_abs_pos_emb = use_abs_pos_emb
|
| 577 |
-
if use_abs_pos_emb:
|
| 578 |
-
self.pos_emb = AbsolutePositionalEmbedding(dim, abs_pos_emb_max_length)
|
| 579 |
-
|
| 580 |
-
for i in range(depth):
|
| 581 |
-
self.layers.append(
|
| 582 |
-
TransformerBlock(
|
| 583 |
-
dim,
|
| 584 |
-
dim_heads = dim_heads,
|
| 585 |
-
cross_attend = cross_attend,
|
| 586 |
-
dim_context = cond_token_dim,
|
| 587 |
-
global_cond_dim = global_cond_dim,
|
| 588 |
-
causal = causal,
|
| 589 |
-
zero_init_branch_outputs = zero_init_branch_outputs,
|
| 590 |
-
conformer=conformer,
|
| 591 |
-
layer_ix=i,
|
| 592 |
-
dtype=dtype,
|
| 593 |
-
device=device,
|
| 594 |
-
operations=operations,
|
| 595 |
-
**kwargs
|
| 596 |
-
)
|
| 597 |
-
)
|
| 598 |
-
|
| 599 |
-
def forward(
|
| 600 |
-
self,
|
| 601 |
-
x,
|
| 602 |
-
mask = None,
|
| 603 |
-
prepend_embeds = None,
|
| 604 |
-
prepend_mask = None,
|
| 605 |
-
global_cond = None,
|
| 606 |
-
return_info = False,
|
| 607 |
-
**kwargs
|
| 608 |
-
):
|
| 609 |
-
patches_replace = kwargs.get("transformer_options", {}).get("patches_replace", {})
|
| 610 |
-
batch, seq, device = *x.shape[:2], x.device
|
| 611 |
-
context = kwargs["context"]
|
| 612 |
-
|
| 613 |
-
info = {
|
| 614 |
-
"hidden_states": [],
|
| 615 |
-
}
|
| 616 |
-
|
| 617 |
-
x = self.project_in(x)
|
| 618 |
-
|
| 619 |
-
if prepend_embeds is not None:
|
| 620 |
-
prepend_length, prepend_dim = prepend_embeds.shape[1:]
|
| 621 |
-
|
| 622 |
-
assert prepend_dim == x.shape[-1], 'prepend dimension must match sequence dimension'
|
| 623 |
-
|
| 624 |
-
x = torch.cat((prepend_embeds, x), dim = -2)
|
| 625 |
-
|
| 626 |
-
if prepend_mask is not None or mask is not None:
|
| 627 |
-
mask = mask if mask is not None else torch.ones((batch, seq), device = device, dtype = torch.bool)
|
| 628 |
-
prepend_mask = prepend_mask if prepend_mask is not None else torch.ones((batch, prepend_length), device = device, dtype = torch.bool)
|
| 629 |
-
|
| 630 |
-
mask = torch.cat((prepend_mask, mask), dim = -1)
|
| 631 |
-
|
| 632 |
-
# Attention layers
|
| 633 |
-
|
| 634 |
-
if self.rotary_pos_emb is not None:
|
| 635 |
-
rotary_pos_emb = self.rotary_pos_emb.forward_from_seq_len(x.shape[1], dtype=x.dtype, device=x.device)
|
| 636 |
-
else:
|
| 637 |
-
rotary_pos_emb = None
|
| 638 |
-
|
| 639 |
-
if self.use_sinusoidal_emb or self.use_abs_pos_emb:
|
| 640 |
-
x = x + self.pos_emb(x)
|
| 641 |
-
|
| 642 |
-
blocks_replace = patches_replace.get("dit", {})
|
| 643 |
-
# Iterate over the transformer layers
|
| 644 |
-
for i, layer in enumerate(self.layers):
|
| 645 |
-
if ("double_block", i) in blocks_replace:
|
| 646 |
-
def block_wrap(args):
|
| 647 |
-
out = {}
|
| 648 |
-
out["img"] = layer(args["img"], rotary_pos_emb=args["pe"], global_cond=args["vec"], context=args["txt"])
|
| 649 |
-
return out
|
| 650 |
-
|
| 651 |
-
out = blocks_replace[("double_block", i)]({"img": x, "txt": context, "vec": global_cond, "pe": rotary_pos_emb}, {"original_block": block_wrap})
|
| 652 |
-
x = out["img"]
|
| 653 |
-
else:
|
| 654 |
-
x = layer(x, rotary_pos_emb = rotary_pos_emb, global_cond=global_cond, context=context)
|
| 655 |
-
# x = checkpoint(layer, x, rotary_pos_emb = rotary_pos_emb, global_cond=global_cond, **kwargs)
|
| 656 |
-
|
| 657 |
-
if return_info:
|
| 658 |
-
info["hidden_states"].append(x)
|
| 659 |
-
|
| 660 |
-
x = self.project_out(x)
|
| 661 |
-
|
| 662 |
-
if return_info:
|
| 663 |
-
return x, info
|
| 664 |
-
|
| 665 |
-
return x
|
| 666 |
-
|
| 667 |
-
class AudioDiffusionTransformer(nn.Module):
|
| 668 |
-
def __init__(self,
|
| 669 |
-
io_channels=64,
|
| 670 |
-
patch_size=1,
|
| 671 |
-
embed_dim=1536,
|
| 672 |
-
cond_token_dim=768,
|
| 673 |
-
project_cond_tokens=False,
|
| 674 |
-
global_cond_dim=1536,
|
| 675 |
-
project_global_cond=True,
|
| 676 |
-
input_concat_dim=0,
|
| 677 |
-
prepend_cond_dim=0,
|
| 678 |
-
depth=24,
|
| 679 |
-
num_heads=24,
|
| 680 |
-
transformer_type: tp.Literal["continuous_transformer"] = "continuous_transformer",
|
| 681 |
-
global_cond_type: tp.Literal["prepend", "adaLN"] = "prepend",
|
| 682 |
-
audio_model="",
|
| 683 |
-
dtype=None,
|
| 684 |
-
device=None,
|
| 685 |
-
operations=None,
|
| 686 |
-
**kwargs):
|
| 687 |
-
|
| 688 |
-
super().__init__()
|
| 689 |
-
|
| 690 |
-
self.dtype = dtype
|
| 691 |
-
self.cond_token_dim = cond_token_dim
|
| 692 |
-
|
| 693 |
-
# Timestep embeddings
|
| 694 |
-
timestep_features_dim = 256
|
| 695 |
-
|
| 696 |
-
self.timestep_features = FourierFeatures(1, timestep_features_dim, dtype=dtype, device=device)
|
| 697 |
-
|
| 698 |
-
self.to_timestep_embed = nn.Sequential(
|
| 699 |
-
operations.Linear(timestep_features_dim, embed_dim, bias=True, dtype=dtype, device=device),
|
| 700 |
-
nn.SiLU(),
|
| 701 |
-
operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device),
|
| 702 |
-
)
|
| 703 |
-
|
| 704 |
-
if cond_token_dim > 0:
|
| 705 |
-
# Conditioning tokens
|
| 706 |
-
|
| 707 |
-
cond_embed_dim = cond_token_dim if not project_cond_tokens else embed_dim
|
| 708 |
-
self.to_cond_embed = nn.Sequential(
|
| 709 |
-
operations.Linear(cond_token_dim, cond_embed_dim, bias=False, dtype=dtype, device=device),
|
| 710 |
-
nn.SiLU(),
|
| 711 |
-
operations.Linear(cond_embed_dim, cond_embed_dim, bias=False, dtype=dtype, device=device)
|
| 712 |
-
)
|
| 713 |
-
else:
|
| 714 |
-
cond_embed_dim = 0
|
| 715 |
-
|
| 716 |
-
if global_cond_dim > 0:
|
| 717 |
-
# Global conditioning
|
| 718 |
-
global_embed_dim = global_cond_dim if not project_global_cond else embed_dim
|
| 719 |
-
self.to_global_embed = nn.Sequential(
|
| 720 |
-
operations.Linear(global_cond_dim, global_embed_dim, bias=False, dtype=dtype, device=device),
|
| 721 |
-
nn.SiLU(),
|
| 722 |
-
operations.Linear(global_embed_dim, global_embed_dim, bias=False, dtype=dtype, device=device)
|
| 723 |
-
)
|
| 724 |
-
|
| 725 |
-
if prepend_cond_dim > 0:
|
| 726 |
-
# Prepend conditioning
|
| 727 |
-
self.to_prepend_embed = nn.Sequential(
|
| 728 |
-
operations.Linear(prepend_cond_dim, embed_dim, bias=False, dtype=dtype, device=device),
|
| 729 |
-
nn.SiLU(),
|
| 730 |
-
operations.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
|
| 731 |
-
)
|
| 732 |
-
|
| 733 |
-
self.input_concat_dim = input_concat_dim
|
| 734 |
-
|
| 735 |
-
dim_in = io_channels + self.input_concat_dim
|
| 736 |
-
|
| 737 |
-
self.patch_size = patch_size
|
| 738 |
-
|
| 739 |
-
# Transformer
|
| 740 |
-
|
| 741 |
-
self.transformer_type = transformer_type
|
| 742 |
-
|
| 743 |
-
self.global_cond_type = global_cond_type
|
| 744 |
-
|
| 745 |
-
if self.transformer_type == "continuous_transformer":
|
| 746 |
-
|
| 747 |
-
global_dim = None
|
| 748 |
-
|
| 749 |
-
if self.global_cond_type == "adaLN":
|
| 750 |
-
# The global conditioning is projected to the embed_dim already at this point
|
| 751 |
-
global_dim = embed_dim
|
| 752 |
-
|
| 753 |
-
self.transformer = ContinuousTransformer(
|
| 754 |
-
dim=embed_dim,
|
| 755 |
-
depth=depth,
|
| 756 |
-
dim_heads=embed_dim // num_heads,
|
| 757 |
-
dim_in=dim_in * patch_size,
|
| 758 |
-
dim_out=io_channels * patch_size,
|
| 759 |
-
cross_attend = cond_token_dim > 0,
|
| 760 |
-
cond_token_dim = cond_embed_dim,
|
| 761 |
-
global_cond_dim=global_dim,
|
| 762 |
-
dtype=dtype,
|
| 763 |
-
device=device,
|
| 764 |
-
operations=operations,
|
| 765 |
-
**kwargs
|
| 766 |
-
)
|
| 767 |
-
else:
|
| 768 |
-
raise ValueError(f"Unknown transformer type: {self.transformer_type}")
|
| 769 |
-
|
| 770 |
-
self.preprocess_conv = operations.Conv1d(dim_in, dim_in, 1, bias=False, dtype=dtype, device=device)
|
| 771 |
-
self.postprocess_conv = operations.Conv1d(io_channels, io_channels, 1, bias=False, dtype=dtype, device=device)
|
| 772 |
-
|
| 773 |
-
def _forward(
|
| 774 |
-
self,
|
| 775 |
-
x,
|
| 776 |
-
t,
|
| 777 |
-
mask=None,
|
| 778 |
-
cross_attn_cond=None,
|
| 779 |
-
cross_attn_cond_mask=None,
|
| 780 |
-
input_concat_cond=None,
|
| 781 |
-
global_embed=None,
|
| 782 |
-
prepend_cond=None,
|
| 783 |
-
prepend_cond_mask=None,
|
| 784 |
-
return_info=False,
|
| 785 |
-
**kwargs):
|
| 786 |
-
|
| 787 |
-
if cross_attn_cond is not None:
|
| 788 |
-
cross_attn_cond = self.to_cond_embed(cross_attn_cond)
|
| 789 |
-
|
| 790 |
-
if global_embed is not None:
|
| 791 |
-
# Project the global conditioning to the embedding dimension
|
| 792 |
-
global_embed = self.to_global_embed(global_embed)
|
| 793 |
-
|
| 794 |
-
prepend_inputs = None
|
| 795 |
-
prepend_mask = None
|
| 796 |
-
prepend_length = 0
|
| 797 |
-
if prepend_cond is not None:
|
| 798 |
-
# Project the prepend conditioning to the embedding dimension
|
| 799 |
-
prepend_cond = self.to_prepend_embed(prepend_cond)
|
| 800 |
-
|
| 801 |
-
prepend_inputs = prepend_cond
|
| 802 |
-
if prepend_cond_mask is not None:
|
| 803 |
-
prepend_mask = prepend_cond_mask
|
| 804 |
-
|
| 805 |
-
if input_concat_cond is not None:
|
| 806 |
-
|
| 807 |
-
# Interpolate input_concat_cond to the same length as x
|
| 808 |
-
if input_concat_cond.shape[2] != x.shape[2]:
|
| 809 |
-
input_concat_cond = F.interpolate(input_concat_cond, (x.shape[2], ), mode='nearest')
|
| 810 |
-
|
| 811 |
-
x = torch.cat([x, input_concat_cond], dim=1)
|
| 812 |
-
|
| 813 |
-
# Get the batch of timestep embeddings
|
| 814 |
-
timestep_embed = self.to_timestep_embed(self.timestep_features(t[:, None]).to(x.dtype)) # (b, embed_dim)
|
| 815 |
-
|
| 816 |
-
# Timestep embedding is considered a global embedding. Add to the global conditioning if it exists
|
| 817 |
-
if global_embed is not None:
|
| 818 |
-
global_embed = global_embed + timestep_embed
|
| 819 |
-
else:
|
| 820 |
-
global_embed = timestep_embed
|
| 821 |
-
|
| 822 |
-
# Add the global_embed to the prepend inputs if there is no global conditioning support in the transformer
|
| 823 |
-
if self.global_cond_type == "prepend":
|
| 824 |
-
if prepend_inputs is None:
|
| 825 |
-
# Prepend inputs are just the global embed, and the mask is all ones
|
| 826 |
-
prepend_inputs = global_embed.unsqueeze(1)
|
| 827 |
-
prepend_mask = torch.ones((x.shape[0], 1), device=x.device, dtype=torch.bool)
|
| 828 |
-
else:
|
| 829 |
-
# Prepend inputs are the prepend conditioning + the global embed
|
| 830 |
-
prepend_inputs = torch.cat([prepend_inputs, global_embed.unsqueeze(1)], dim=1)
|
| 831 |
-
prepend_mask = torch.cat([prepend_mask, torch.ones((x.shape[0], 1), device=x.device, dtype=torch.bool)], dim=1)
|
| 832 |
-
|
| 833 |
-
prepend_length = prepend_inputs.shape[1]
|
| 834 |
-
|
| 835 |
-
x = self.preprocess_conv(x) + x
|
| 836 |
-
|
| 837 |
-
x = rearrange(x, "b c t -> b t c")
|
| 838 |
-
|
| 839 |
-
extra_args = {}
|
| 840 |
-
|
| 841 |
-
if self.global_cond_type == "adaLN":
|
| 842 |
-
extra_args["global_cond"] = global_embed
|
| 843 |
-
|
| 844 |
-
if self.patch_size > 1:
|
| 845 |
-
x = rearrange(x, "b (t p) c -> b t (c p)", p=self.patch_size)
|
| 846 |
-
|
| 847 |
-
if self.transformer_type == "x-transformers":
|
| 848 |
-
output = self.transformer(x, prepend_embeds=prepend_inputs, context=cross_attn_cond, context_mask=cross_attn_cond_mask, mask=mask, prepend_mask=prepend_mask, **extra_args, **kwargs)
|
| 849 |
-
elif self.transformer_type == "continuous_transformer":
|
| 850 |
-
output = self.transformer(x, prepend_embeds=prepend_inputs, context=cross_attn_cond, context_mask=cross_attn_cond_mask, mask=mask, prepend_mask=prepend_mask, return_info=return_info, **extra_args, **kwargs)
|
| 851 |
-
|
| 852 |
-
if return_info:
|
| 853 |
-
output, info = output
|
| 854 |
-
elif self.transformer_type == "mm_transformer":
|
| 855 |
-
output = self.transformer(x, context=cross_attn_cond, mask=mask, context_mask=cross_attn_cond_mask, **extra_args, **kwargs)
|
| 856 |
-
|
| 857 |
-
output = rearrange(output, "b t c -> b c t")[:,:,prepend_length:]
|
| 858 |
-
|
| 859 |
-
if self.patch_size > 1:
|
| 860 |
-
output = rearrange(output, "b (c p) t -> b c (t p)", p=self.patch_size)
|
| 861 |
-
|
| 862 |
-
output = self.postprocess_conv(output) + output
|
| 863 |
-
|
| 864 |
-
if return_info:
|
| 865 |
-
return output, info
|
| 866 |
-
|
| 867 |
-
return output
|
| 868 |
-
|
| 869 |
-
def forward(
|
| 870 |
-
self,
|
| 871 |
-
x,
|
| 872 |
-
timestep,
|
| 873 |
-
context=None,
|
| 874 |
-
context_mask=None,
|
| 875 |
-
input_concat_cond=None,
|
| 876 |
-
global_embed=None,
|
| 877 |
-
negative_global_embed=None,
|
| 878 |
-
prepend_cond=None,
|
| 879 |
-
prepend_cond_mask=None,
|
| 880 |
-
mask=None,
|
| 881 |
-
return_info=False,
|
| 882 |
-
control=None,
|
| 883 |
-
**kwargs):
|
| 884 |
-
return self._forward(
|
| 885 |
-
x,
|
| 886 |
-
timestep,
|
| 887 |
-
cross_attn_cond=context,
|
| 888 |
-
cross_attn_cond_mask=context_mask,
|
| 889 |
-
input_concat_cond=input_concat_cond,
|
| 890 |
-
global_embed=global_embed,
|
| 891 |
-
prepend_cond=prepend_cond,
|
| 892 |
-
prepend_cond_mask=prepend_cond_mask,
|
| 893 |
-
mask=mask,
|
| 894 |
-
return_info=return_info,
|
| 895 |
-
**kwargs
|
| 896 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/audio/embedders.py
DELETED
|
@@ -1,108 +0,0 @@
|
|
| 1 |
-
# code adapted from: https://github.com/Stability-AI/stable-audio-tools
|
| 2 |
-
|
| 3 |
-
import torch
|
| 4 |
-
import torch.nn as nn
|
| 5 |
-
from torch import Tensor
|
| 6 |
-
from typing import List, Union
|
| 7 |
-
from einops import rearrange
|
| 8 |
-
import math
|
| 9 |
-
import comfy.ops
|
| 10 |
-
|
| 11 |
-
class LearnedPositionalEmbedding(nn.Module):
|
| 12 |
-
"""Used for continuous time"""
|
| 13 |
-
|
| 14 |
-
def __init__(self, dim: int):
|
| 15 |
-
super().__init__()
|
| 16 |
-
assert (dim % 2) == 0
|
| 17 |
-
half_dim = dim // 2
|
| 18 |
-
self.weights = nn.Parameter(torch.empty(half_dim))
|
| 19 |
-
|
| 20 |
-
def forward(self, x: Tensor) -> Tensor:
|
| 21 |
-
x = rearrange(x, "b -> b 1")
|
| 22 |
-
freqs = x * rearrange(self.weights, "d -> 1 d") * 2 * math.pi
|
| 23 |
-
fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1)
|
| 24 |
-
fouriered = torch.cat((x, fouriered), dim=-1)
|
| 25 |
-
return fouriered
|
| 26 |
-
|
| 27 |
-
def TimePositionalEmbedding(dim: int, out_features: int) -> nn.Module:
|
| 28 |
-
return nn.Sequential(
|
| 29 |
-
LearnedPositionalEmbedding(dim),
|
| 30 |
-
comfy.ops.manual_cast.Linear(in_features=dim + 1, out_features=out_features),
|
| 31 |
-
)
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
class NumberEmbedder(nn.Module):
|
| 35 |
-
def __init__(
|
| 36 |
-
self,
|
| 37 |
-
features: int,
|
| 38 |
-
dim: int = 256,
|
| 39 |
-
):
|
| 40 |
-
super().__init__()
|
| 41 |
-
self.features = features
|
| 42 |
-
self.embedding = TimePositionalEmbedding(dim=dim, out_features=features)
|
| 43 |
-
|
| 44 |
-
def forward(self, x: Union[List[float], Tensor]) -> Tensor:
|
| 45 |
-
if not torch.is_tensor(x):
|
| 46 |
-
device = next(self.embedding.parameters()).device
|
| 47 |
-
x = torch.tensor(x, device=device)
|
| 48 |
-
assert isinstance(x, Tensor)
|
| 49 |
-
shape = x.shape
|
| 50 |
-
x = rearrange(x, "... -> (...)")
|
| 51 |
-
embedding = self.embedding(x)
|
| 52 |
-
x = embedding.view(*shape, self.features)
|
| 53 |
-
return x # type: ignore
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
class Conditioner(nn.Module):
|
| 57 |
-
def __init__(
|
| 58 |
-
self,
|
| 59 |
-
dim: int,
|
| 60 |
-
output_dim: int,
|
| 61 |
-
project_out: bool = False
|
| 62 |
-
):
|
| 63 |
-
|
| 64 |
-
super().__init__()
|
| 65 |
-
|
| 66 |
-
self.dim = dim
|
| 67 |
-
self.output_dim = output_dim
|
| 68 |
-
self.proj_out = nn.Linear(dim, output_dim) if (dim != output_dim or project_out) else nn.Identity()
|
| 69 |
-
|
| 70 |
-
def forward(self, x):
|
| 71 |
-
raise NotImplementedError()
|
| 72 |
-
|
| 73 |
-
class NumberConditioner(Conditioner):
|
| 74 |
-
'''
|
| 75 |
-
Conditioner that takes a list of floats, normalizes them for a given range, and returns a list of embeddings
|
| 76 |
-
'''
|
| 77 |
-
def __init__(self,
|
| 78 |
-
output_dim: int,
|
| 79 |
-
min_val: float=0,
|
| 80 |
-
max_val: float=1
|
| 81 |
-
):
|
| 82 |
-
super().__init__(output_dim, output_dim)
|
| 83 |
-
|
| 84 |
-
self.min_val = min_val
|
| 85 |
-
self.max_val = max_val
|
| 86 |
-
|
| 87 |
-
self.embedder = NumberEmbedder(features=output_dim)
|
| 88 |
-
|
| 89 |
-
def forward(self, floats, device=None):
|
| 90 |
-
# Cast the inputs to floats
|
| 91 |
-
floats = [float(x) for x in floats]
|
| 92 |
-
|
| 93 |
-
if device is None:
|
| 94 |
-
device = next(self.embedder.parameters()).device
|
| 95 |
-
|
| 96 |
-
floats = torch.tensor(floats).to(device)
|
| 97 |
-
|
| 98 |
-
floats = floats.clamp(self.min_val, self.max_val)
|
| 99 |
-
|
| 100 |
-
normalized_floats = (floats - self.min_val) / (self.max_val - self.min_val)
|
| 101 |
-
|
| 102 |
-
# Cast floats to same type as embedder
|
| 103 |
-
embedder_dtype = next(self.embedder.parameters()).dtype
|
| 104 |
-
normalized_floats = normalized_floats.to(embedder_dtype)
|
| 105 |
-
|
| 106 |
-
float_embeds = self.embedder(normalized_floats).unsqueeze(1)
|
| 107 |
-
|
| 108 |
-
return [float_embeds, torch.ones(float_embeds.shape[0], 1).to(device)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/aura/mmdit.py
DELETED
|
@@ -1,498 +0,0 @@
|
|
| 1 |
-
#AuraFlow MMDiT
|
| 2 |
-
#Originally written by the AuraFlow Authors
|
| 3 |
-
|
| 4 |
-
import math
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
import torch.nn as nn
|
| 8 |
-
import torch.nn.functional as F
|
| 9 |
-
|
| 10 |
-
from comfy.ldm.modules.attention import optimized_attention
|
| 11 |
-
import comfy.ops
|
| 12 |
-
import comfy.ldm.common_dit
|
| 13 |
-
|
| 14 |
-
def modulate(x, shift, scale):
|
| 15 |
-
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def find_multiple(n: int, k: int) -> int:
|
| 19 |
-
if n % k == 0:
|
| 20 |
-
return n
|
| 21 |
-
return n + k - (n % k)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
class MLP(nn.Module):
|
| 25 |
-
def __init__(self, dim, hidden_dim=None, dtype=None, device=None, operations=None) -> None:
|
| 26 |
-
super().__init__()
|
| 27 |
-
if hidden_dim is None:
|
| 28 |
-
hidden_dim = 4 * dim
|
| 29 |
-
|
| 30 |
-
n_hidden = int(2 * hidden_dim / 3)
|
| 31 |
-
n_hidden = find_multiple(n_hidden, 256)
|
| 32 |
-
|
| 33 |
-
self.c_fc1 = operations.Linear(dim, n_hidden, bias=False, dtype=dtype, device=device)
|
| 34 |
-
self.c_fc2 = operations.Linear(dim, n_hidden, bias=False, dtype=dtype, device=device)
|
| 35 |
-
self.c_proj = operations.Linear(n_hidden, dim, bias=False, dtype=dtype, device=device)
|
| 36 |
-
|
| 37 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 38 |
-
x = F.silu(self.c_fc1(x)) * self.c_fc2(x)
|
| 39 |
-
x = self.c_proj(x)
|
| 40 |
-
return x
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
class MultiHeadLayerNorm(nn.Module):
|
| 44 |
-
def __init__(self, hidden_size=None, eps=1e-5, dtype=None, device=None):
|
| 45 |
-
# Copy pasta from https://github.com/huggingface/transformers/blob/e5f71ecaae50ea476d1e12351003790273c4b2ed/src/transformers/models/cohere/modeling_cohere.py#L78
|
| 46 |
-
|
| 47 |
-
super().__init__()
|
| 48 |
-
self.weight = nn.Parameter(torch.empty(hidden_size, dtype=dtype, device=device))
|
| 49 |
-
self.variance_epsilon = eps
|
| 50 |
-
|
| 51 |
-
def forward(self, hidden_states):
|
| 52 |
-
input_dtype = hidden_states.dtype
|
| 53 |
-
hidden_states = hidden_states.to(torch.float32)
|
| 54 |
-
mean = hidden_states.mean(-1, keepdim=True)
|
| 55 |
-
variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True)
|
| 56 |
-
hidden_states = (hidden_states - mean) * torch.rsqrt(
|
| 57 |
-
variance + self.variance_epsilon
|
| 58 |
-
)
|
| 59 |
-
hidden_states = self.weight.to(torch.float32) * hidden_states
|
| 60 |
-
return hidden_states.to(input_dtype)
|
| 61 |
-
|
| 62 |
-
class SingleAttention(nn.Module):
|
| 63 |
-
def __init__(self, dim, n_heads, mh_qknorm=False, dtype=None, device=None, operations=None):
|
| 64 |
-
super().__init__()
|
| 65 |
-
|
| 66 |
-
self.n_heads = n_heads
|
| 67 |
-
self.head_dim = dim // n_heads
|
| 68 |
-
|
| 69 |
-
# this is for cond
|
| 70 |
-
self.w1q = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 71 |
-
self.w1k = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 72 |
-
self.w1v = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 73 |
-
self.w1o = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 74 |
-
|
| 75 |
-
self.q_norm1 = (
|
| 76 |
-
MultiHeadLayerNorm((self.n_heads, self.head_dim), dtype=dtype, device=device)
|
| 77 |
-
if mh_qknorm
|
| 78 |
-
else operations.LayerNorm(self.head_dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 79 |
-
)
|
| 80 |
-
self.k_norm1 = (
|
| 81 |
-
MultiHeadLayerNorm((self.n_heads, self.head_dim), dtype=dtype, device=device)
|
| 82 |
-
if mh_qknorm
|
| 83 |
-
else operations.LayerNorm(self.head_dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 84 |
-
)
|
| 85 |
-
|
| 86 |
-
#@torch.compile()
|
| 87 |
-
def forward(self, c):
|
| 88 |
-
|
| 89 |
-
bsz, seqlen1, _ = c.shape
|
| 90 |
-
|
| 91 |
-
q, k, v = self.w1q(c), self.w1k(c), self.w1v(c)
|
| 92 |
-
q = q.view(bsz, seqlen1, self.n_heads, self.head_dim)
|
| 93 |
-
k = k.view(bsz, seqlen1, self.n_heads, self.head_dim)
|
| 94 |
-
v = v.view(bsz, seqlen1, self.n_heads, self.head_dim)
|
| 95 |
-
q, k = self.q_norm1(q), self.k_norm1(k)
|
| 96 |
-
|
| 97 |
-
output = optimized_attention(q.permute(0, 2, 1, 3), k.permute(0, 2, 1, 3), v.permute(0, 2, 1, 3), self.n_heads, skip_reshape=True)
|
| 98 |
-
c = self.w1o(output)
|
| 99 |
-
return c
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
class DoubleAttention(nn.Module):
|
| 104 |
-
def __init__(self, dim, n_heads, mh_qknorm=False, dtype=None, device=None, operations=None):
|
| 105 |
-
super().__init__()
|
| 106 |
-
|
| 107 |
-
self.n_heads = n_heads
|
| 108 |
-
self.head_dim = dim // n_heads
|
| 109 |
-
|
| 110 |
-
# this is for cond
|
| 111 |
-
self.w1q = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 112 |
-
self.w1k = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 113 |
-
self.w1v = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 114 |
-
self.w1o = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 115 |
-
|
| 116 |
-
# this is for x
|
| 117 |
-
self.w2q = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 118 |
-
self.w2k = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 119 |
-
self.w2v = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 120 |
-
self.w2o = operations.Linear(dim, dim, bias=False, dtype=dtype, device=device)
|
| 121 |
-
|
| 122 |
-
self.q_norm1 = (
|
| 123 |
-
MultiHeadLayerNorm((self.n_heads, self.head_dim), dtype=dtype, device=device)
|
| 124 |
-
if mh_qknorm
|
| 125 |
-
else operations.LayerNorm(self.head_dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 126 |
-
)
|
| 127 |
-
self.k_norm1 = (
|
| 128 |
-
MultiHeadLayerNorm((self.n_heads, self.head_dim), dtype=dtype, device=device)
|
| 129 |
-
if mh_qknorm
|
| 130 |
-
else operations.LayerNorm(self.head_dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 131 |
-
)
|
| 132 |
-
|
| 133 |
-
self.q_norm2 = (
|
| 134 |
-
MultiHeadLayerNorm((self.n_heads, self.head_dim), dtype=dtype, device=device)
|
| 135 |
-
if mh_qknorm
|
| 136 |
-
else operations.LayerNorm(self.head_dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 137 |
-
)
|
| 138 |
-
self.k_norm2 = (
|
| 139 |
-
MultiHeadLayerNorm((self.n_heads, self.head_dim), dtype=dtype, device=device)
|
| 140 |
-
if mh_qknorm
|
| 141 |
-
else operations.LayerNorm(self.head_dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 142 |
-
)
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
#@torch.compile()
|
| 146 |
-
def forward(self, c, x):
|
| 147 |
-
|
| 148 |
-
bsz, seqlen1, _ = c.shape
|
| 149 |
-
bsz, seqlen2, _ = x.shape
|
| 150 |
-
|
| 151 |
-
cq, ck, cv = self.w1q(c), self.w1k(c), self.w1v(c)
|
| 152 |
-
cq = cq.view(bsz, seqlen1, self.n_heads, self.head_dim)
|
| 153 |
-
ck = ck.view(bsz, seqlen1, self.n_heads, self.head_dim)
|
| 154 |
-
cv = cv.view(bsz, seqlen1, self.n_heads, self.head_dim)
|
| 155 |
-
cq, ck = self.q_norm1(cq), self.k_norm1(ck)
|
| 156 |
-
|
| 157 |
-
xq, xk, xv = self.w2q(x), self.w2k(x), self.w2v(x)
|
| 158 |
-
xq = xq.view(bsz, seqlen2, self.n_heads, self.head_dim)
|
| 159 |
-
xk = xk.view(bsz, seqlen2, self.n_heads, self.head_dim)
|
| 160 |
-
xv = xv.view(bsz, seqlen2, self.n_heads, self.head_dim)
|
| 161 |
-
xq, xk = self.q_norm2(xq), self.k_norm2(xk)
|
| 162 |
-
|
| 163 |
-
# concat all
|
| 164 |
-
q, k, v = (
|
| 165 |
-
torch.cat([cq, xq], dim=1),
|
| 166 |
-
torch.cat([ck, xk], dim=1),
|
| 167 |
-
torch.cat([cv, xv], dim=1),
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
output = optimized_attention(q.permute(0, 2, 1, 3), k.permute(0, 2, 1, 3), v.permute(0, 2, 1, 3), self.n_heads, skip_reshape=True)
|
| 171 |
-
|
| 172 |
-
c, x = output.split([seqlen1, seqlen2], dim=1)
|
| 173 |
-
c = self.w1o(c)
|
| 174 |
-
x = self.w2o(x)
|
| 175 |
-
|
| 176 |
-
return c, x
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
class MMDiTBlock(nn.Module):
|
| 180 |
-
def __init__(self, dim, heads=8, global_conddim=1024, is_last=False, dtype=None, device=None, operations=None):
|
| 181 |
-
super().__init__()
|
| 182 |
-
|
| 183 |
-
self.normC1 = operations.LayerNorm(dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 184 |
-
self.normC2 = operations.LayerNorm(dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 185 |
-
if not is_last:
|
| 186 |
-
self.mlpC = MLP(dim, hidden_dim=dim * 4, dtype=dtype, device=device, operations=operations)
|
| 187 |
-
self.modC = nn.Sequential(
|
| 188 |
-
nn.SiLU(),
|
| 189 |
-
operations.Linear(global_conddim, 6 * dim, bias=False, dtype=dtype, device=device),
|
| 190 |
-
)
|
| 191 |
-
else:
|
| 192 |
-
self.modC = nn.Sequential(
|
| 193 |
-
nn.SiLU(),
|
| 194 |
-
operations.Linear(global_conddim, 2 * dim, bias=False, dtype=dtype, device=device),
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
self.normX1 = operations.LayerNorm(dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 198 |
-
self.normX2 = operations.LayerNorm(dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 199 |
-
self.mlpX = MLP(dim, hidden_dim=dim * 4, dtype=dtype, device=device, operations=operations)
|
| 200 |
-
self.modX = nn.Sequential(
|
| 201 |
-
nn.SiLU(),
|
| 202 |
-
operations.Linear(global_conddim, 6 * dim, bias=False, dtype=dtype, device=device),
|
| 203 |
-
)
|
| 204 |
-
|
| 205 |
-
self.attn = DoubleAttention(dim, heads, dtype=dtype, device=device, operations=operations)
|
| 206 |
-
self.is_last = is_last
|
| 207 |
-
|
| 208 |
-
#@torch.compile()
|
| 209 |
-
def forward(self, c, x, global_cond, **kwargs):
|
| 210 |
-
|
| 211 |
-
cres, xres = c, x
|
| 212 |
-
|
| 213 |
-
cshift_msa, cscale_msa, cgate_msa, cshift_mlp, cscale_mlp, cgate_mlp = (
|
| 214 |
-
self.modC(global_cond).chunk(6, dim=1)
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
c = modulate(self.normC1(c), cshift_msa, cscale_msa)
|
| 218 |
-
|
| 219 |
-
# xpath
|
| 220 |
-
xshift_msa, xscale_msa, xgate_msa, xshift_mlp, xscale_mlp, xgate_mlp = (
|
| 221 |
-
self.modX(global_cond).chunk(6, dim=1)
|
| 222 |
-
)
|
| 223 |
-
|
| 224 |
-
x = modulate(self.normX1(x), xshift_msa, xscale_msa)
|
| 225 |
-
|
| 226 |
-
# attention
|
| 227 |
-
c, x = self.attn(c, x)
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
c = self.normC2(cres + cgate_msa.unsqueeze(1) * c)
|
| 231 |
-
c = cgate_mlp.unsqueeze(1) * self.mlpC(modulate(c, cshift_mlp, cscale_mlp))
|
| 232 |
-
c = cres + c
|
| 233 |
-
|
| 234 |
-
x = self.normX2(xres + xgate_msa.unsqueeze(1) * x)
|
| 235 |
-
x = xgate_mlp.unsqueeze(1) * self.mlpX(modulate(x, xshift_mlp, xscale_mlp))
|
| 236 |
-
x = xres + x
|
| 237 |
-
|
| 238 |
-
return c, x
|
| 239 |
-
|
| 240 |
-
class DiTBlock(nn.Module):
|
| 241 |
-
# like MMDiTBlock, but it only has X
|
| 242 |
-
def __init__(self, dim, heads=8, global_conddim=1024, dtype=None, device=None, operations=None):
|
| 243 |
-
super().__init__()
|
| 244 |
-
|
| 245 |
-
self.norm1 = operations.LayerNorm(dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 246 |
-
self.norm2 = operations.LayerNorm(dim, elementwise_affine=False, dtype=dtype, device=device)
|
| 247 |
-
|
| 248 |
-
self.modCX = nn.Sequential(
|
| 249 |
-
nn.SiLU(),
|
| 250 |
-
operations.Linear(global_conddim, 6 * dim, bias=False, dtype=dtype, device=device),
|
| 251 |
-
)
|
| 252 |
-
|
| 253 |
-
self.attn = SingleAttention(dim, heads, dtype=dtype, device=device, operations=operations)
|
| 254 |
-
self.mlp = MLP(dim, hidden_dim=dim * 4, dtype=dtype, device=device, operations=operations)
|
| 255 |
-
|
| 256 |
-
#@torch.compile()
|
| 257 |
-
def forward(self, cx, global_cond, **kwargs):
|
| 258 |
-
cxres = cx
|
| 259 |
-
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.modCX(
|
| 260 |
-
global_cond
|
| 261 |
-
).chunk(6, dim=1)
|
| 262 |
-
cx = modulate(self.norm1(cx), shift_msa, scale_msa)
|
| 263 |
-
cx = self.attn(cx)
|
| 264 |
-
cx = self.norm2(cxres + gate_msa.unsqueeze(1) * cx)
|
| 265 |
-
mlpout = self.mlp(modulate(cx, shift_mlp, scale_mlp))
|
| 266 |
-
cx = gate_mlp.unsqueeze(1) * mlpout
|
| 267 |
-
|
| 268 |
-
cx = cxres + cx
|
| 269 |
-
|
| 270 |
-
return cx
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
class TimestepEmbedder(nn.Module):
|
| 275 |
-
def __init__(self, hidden_size, frequency_embedding_size=256, dtype=None, device=None, operations=None):
|
| 276 |
-
super().__init__()
|
| 277 |
-
self.mlp = nn.Sequential(
|
| 278 |
-
operations.Linear(frequency_embedding_size, hidden_size, dtype=dtype, device=device),
|
| 279 |
-
nn.SiLU(),
|
| 280 |
-
operations.Linear(hidden_size, hidden_size, dtype=dtype, device=device),
|
| 281 |
-
)
|
| 282 |
-
self.frequency_embedding_size = frequency_embedding_size
|
| 283 |
-
|
| 284 |
-
@staticmethod
|
| 285 |
-
def timestep_embedding(t, dim, max_period=10000):
|
| 286 |
-
half = dim // 2
|
| 287 |
-
freqs = 1000 * torch.exp(
|
| 288 |
-
-math.log(max_period) * torch.arange(start=0, end=half) / half
|
| 289 |
-
).to(t.device)
|
| 290 |
-
args = t[:, None] * freqs[None]
|
| 291 |
-
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 292 |
-
if dim % 2:
|
| 293 |
-
embedding = torch.cat(
|
| 294 |
-
[embedding, torch.zeros_like(embedding[:, :1])], dim=-1
|
| 295 |
-
)
|
| 296 |
-
return embedding
|
| 297 |
-
|
| 298 |
-
#@torch.compile()
|
| 299 |
-
def forward(self, t, dtype):
|
| 300 |
-
t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(dtype)
|
| 301 |
-
t_emb = self.mlp(t_freq)
|
| 302 |
-
return t_emb
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
class MMDiT(nn.Module):
|
| 306 |
-
def __init__(
|
| 307 |
-
self,
|
| 308 |
-
in_channels=4,
|
| 309 |
-
out_channels=4,
|
| 310 |
-
patch_size=2,
|
| 311 |
-
dim=3072,
|
| 312 |
-
n_layers=36,
|
| 313 |
-
n_double_layers=4,
|
| 314 |
-
n_heads=12,
|
| 315 |
-
global_conddim=3072,
|
| 316 |
-
cond_seq_dim=2048,
|
| 317 |
-
max_seq=32 * 32,
|
| 318 |
-
device=None,
|
| 319 |
-
dtype=None,
|
| 320 |
-
operations=None,
|
| 321 |
-
):
|
| 322 |
-
super().__init__()
|
| 323 |
-
self.dtype = dtype
|
| 324 |
-
|
| 325 |
-
self.t_embedder = TimestepEmbedder(global_conddim, dtype=dtype, device=device, operations=operations)
|
| 326 |
-
|
| 327 |
-
self.cond_seq_linear = operations.Linear(
|
| 328 |
-
cond_seq_dim, dim, bias=False, dtype=dtype, device=device
|
| 329 |
-
) # linear for something like text sequence.
|
| 330 |
-
self.init_x_linear = operations.Linear(
|
| 331 |
-
patch_size * patch_size * in_channels, dim, dtype=dtype, device=device
|
| 332 |
-
) # init linear for patchified image.
|
| 333 |
-
|
| 334 |
-
self.positional_encoding = nn.Parameter(torch.empty(1, max_seq, dim, dtype=dtype, device=device))
|
| 335 |
-
self.register_tokens = nn.Parameter(torch.empty(1, 8, dim, dtype=dtype, device=device))
|
| 336 |
-
|
| 337 |
-
self.double_layers = nn.ModuleList([])
|
| 338 |
-
self.single_layers = nn.ModuleList([])
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
for idx in range(n_double_layers):
|
| 342 |
-
self.double_layers.append(
|
| 343 |
-
MMDiTBlock(dim, n_heads, global_conddim, is_last=(idx == n_layers - 1), dtype=dtype, device=device, operations=operations)
|
| 344 |
-
)
|
| 345 |
-
|
| 346 |
-
for idx in range(n_double_layers, n_layers):
|
| 347 |
-
self.single_layers.append(
|
| 348 |
-
DiTBlock(dim, n_heads, global_conddim, dtype=dtype, device=device, operations=operations)
|
| 349 |
-
)
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
self.final_linear = operations.Linear(
|
| 353 |
-
dim, patch_size * patch_size * out_channels, bias=False, dtype=dtype, device=device
|
| 354 |
-
)
|
| 355 |
-
|
| 356 |
-
self.modF = nn.Sequential(
|
| 357 |
-
nn.SiLU(),
|
| 358 |
-
operations.Linear(global_conddim, 2 * dim, bias=False, dtype=dtype, device=device),
|
| 359 |
-
)
|
| 360 |
-
|
| 361 |
-
self.out_channels = out_channels
|
| 362 |
-
self.patch_size = patch_size
|
| 363 |
-
self.n_double_layers = n_double_layers
|
| 364 |
-
self.n_layers = n_layers
|
| 365 |
-
|
| 366 |
-
self.h_max = round(max_seq**0.5)
|
| 367 |
-
self.w_max = round(max_seq**0.5)
|
| 368 |
-
|
| 369 |
-
@torch.no_grad()
|
| 370 |
-
def extend_pe(self, init_dim=(16, 16), target_dim=(64, 64)):
|
| 371 |
-
# extend pe
|
| 372 |
-
pe_data = self.positional_encoding.data.squeeze(0)[: init_dim[0] * init_dim[1]]
|
| 373 |
-
|
| 374 |
-
pe_as_2d = pe_data.view(init_dim[0], init_dim[1], -1).permute(2, 0, 1)
|
| 375 |
-
|
| 376 |
-
# now we need to extend this to target_dim. for this we will use interpolation.
|
| 377 |
-
# we will use torch.nn.functional.interpolate
|
| 378 |
-
pe_as_2d = F.interpolate(
|
| 379 |
-
pe_as_2d.unsqueeze(0), size=target_dim, mode="bilinear"
|
| 380 |
-
)
|
| 381 |
-
pe_new = pe_as_2d.squeeze(0).permute(1, 2, 0).flatten(0, 1)
|
| 382 |
-
self.positional_encoding.data = pe_new.unsqueeze(0).contiguous()
|
| 383 |
-
self.h_max, self.w_max = target_dim
|
| 384 |
-
|
| 385 |
-
def pe_selection_index_based_on_dim(self, h, w):
|
| 386 |
-
h_p, w_p = h // self.patch_size, w // self.patch_size
|
| 387 |
-
original_pe_indexes = torch.arange(self.positional_encoding.shape[1])
|
| 388 |
-
original_pe_indexes = original_pe_indexes.view(self.h_max, self.w_max)
|
| 389 |
-
starth = self.h_max // 2 - h_p // 2
|
| 390 |
-
endh =starth + h_p
|
| 391 |
-
startw = self.w_max // 2 - w_p // 2
|
| 392 |
-
endw = startw + w_p
|
| 393 |
-
original_pe_indexes = original_pe_indexes[
|
| 394 |
-
starth:endh, startw:endw
|
| 395 |
-
]
|
| 396 |
-
return original_pe_indexes.flatten()
|
| 397 |
-
|
| 398 |
-
def unpatchify(self, x, h, w):
|
| 399 |
-
c = self.out_channels
|
| 400 |
-
p = self.patch_size
|
| 401 |
-
|
| 402 |
-
x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
|
| 403 |
-
x = torch.einsum("nhwpqc->nchpwq", x)
|
| 404 |
-
imgs = x.reshape(shape=(x.shape[0], c, h * p, w * p))
|
| 405 |
-
return imgs
|
| 406 |
-
|
| 407 |
-
def patchify(self, x):
|
| 408 |
-
B, C, H, W = x.size()
|
| 409 |
-
x = comfy.ldm.common_dit.pad_to_patch_size(x, (self.patch_size, self.patch_size))
|
| 410 |
-
x = x.view(
|
| 411 |
-
B,
|
| 412 |
-
C,
|
| 413 |
-
(H + 1) // self.patch_size,
|
| 414 |
-
self.patch_size,
|
| 415 |
-
(W + 1) // self.patch_size,
|
| 416 |
-
self.patch_size,
|
| 417 |
-
)
|
| 418 |
-
x = x.permute(0, 2, 4, 1, 3, 5).flatten(-3).flatten(1, 2)
|
| 419 |
-
return x
|
| 420 |
-
|
| 421 |
-
def apply_pos_embeds(self, x, h, w):
|
| 422 |
-
h = (h + 1) // self.patch_size
|
| 423 |
-
w = (w + 1) // self.patch_size
|
| 424 |
-
max_dim = max(h, w)
|
| 425 |
-
|
| 426 |
-
cur_dim = self.h_max
|
| 427 |
-
pos_encoding = comfy.ops.cast_to_input(self.positional_encoding.reshape(1, cur_dim, cur_dim, -1), x)
|
| 428 |
-
|
| 429 |
-
if max_dim > cur_dim:
|
| 430 |
-
pos_encoding = F.interpolate(pos_encoding.movedim(-1, 1), (max_dim, max_dim), mode="bilinear").movedim(1, -1)
|
| 431 |
-
cur_dim = max_dim
|
| 432 |
-
|
| 433 |
-
from_h = (cur_dim - h) // 2
|
| 434 |
-
from_w = (cur_dim - w) // 2
|
| 435 |
-
pos_encoding = pos_encoding[:,from_h:from_h+h,from_w:from_w+w]
|
| 436 |
-
return x + pos_encoding.reshape(1, -1, self.positional_encoding.shape[-1])
|
| 437 |
-
|
| 438 |
-
def forward(self, x, timestep, context, transformer_options={}, **kwargs):
|
| 439 |
-
patches_replace = transformer_options.get("patches_replace", {})
|
| 440 |
-
# patchify x, add PE
|
| 441 |
-
b, c, h, w = x.shape
|
| 442 |
-
|
| 443 |
-
# pe_indexes = self.pe_selection_index_based_on_dim(h, w)
|
| 444 |
-
# print(pe_indexes, pe_indexes.shape)
|
| 445 |
-
|
| 446 |
-
x = self.init_x_linear(self.patchify(x)) # B, T_x, D
|
| 447 |
-
x = self.apply_pos_embeds(x, h, w)
|
| 448 |
-
# x = x + self.positional_encoding[:, : x.size(1)].to(device=x.device, dtype=x.dtype)
|
| 449 |
-
# x = x + self.positional_encoding[:, pe_indexes].to(device=x.device, dtype=x.dtype)
|
| 450 |
-
|
| 451 |
-
# process conditions for MMDiT Blocks
|
| 452 |
-
c_seq = context # B, T_c, D_c
|
| 453 |
-
t = timestep
|
| 454 |
-
|
| 455 |
-
c = self.cond_seq_linear(c_seq) # B, T_c, D
|
| 456 |
-
c = torch.cat([comfy.ops.cast_to_input(self.register_tokens, c).repeat(c.size(0), 1, 1), c], dim=1)
|
| 457 |
-
|
| 458 |
-
global_cond = self.t_embedder(t, x.dtype) # B, D
|
| 459 |
-
|
| 460 |
-
blocks_replace = patches_replace.get("dit", {})
|
| 461 |
-
if len(self.double_layers) > 0:
|
| 462 |
-
for i, layer in enumerate(self.double_layers):
|
| 463 |
-
if ("double_block", i) in blocks_replace:
|
| 464 |
-
def block_wrap(args):
|
| 465 |
-
out = {}
|
| 466 |
-
out["txt"], out["img"] = layer(args["txt"],
|
| 467 |
-
args["img"],
|
| 468 |
-
args["vec"])
|
| 469 |
-
return out
|
| 470 |
-
out = blocks_replace[("double_block", i)]({"img": x, "txt": c, "vec": global_cond}, {"original_block": block_wrap})
|
| 471 |
-
c = out["txt"]
|
| 472 |
-
x = out["img"]
|
| 473 |
-
else:
|
| 474 |
-
c, x = layer(c, x, global_cond, **kwargs)
|
| 475 |
-
|
| 476 |
-
if len(self.single_layers) > 0:
|
| 477 |
-
c_len = c.size(1)
|
| 478 |
-
cx = torch.cat([c, x], dim=1)
|
| 479 |
-
for i, layer in enumerate(self.single_layers):
|
| 480 |
-
if ("single_block", i) in blocks_replace:
|
| 481 |
-
def block_wrap(args):
|
| 482 |
-
out = {}
|
| 483 |
-
out["img"] = layer(args["img"], args["vec"])
|
| 484 |
-
return out
|
| 485 |
-
|
| 486 |
-
out = blocks_replace[("single_block", i)]({"img": cx, "vec": global_cond}, {"original_block": block_wrap})
|
| 487 |
-
cx = out["img"]
|
| 488 |
-
else:
|
| 489 |
-
cx = layer(cx, global_cond, **kwargs)
|
| 490 |
-
|
| 491 |
-
x = cx[:, c_len:]
|
| 492 |
-
|
| 493 |
-
fshift, fscale = self.modF(global_cond).chunk(2, dim=1)
|
| 494 |
-
|
| 495 |
-
x = modulate(x, fshift, fscale)
|
| 496 |
-
x = self.final_linear(x)
|
| 497 |
-
x = self.unpatchify(x, (h + 1) // self.patch_size, (w + 1) // self.patch_size)[:,:,:h,:w]
|
| 498 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy/ldm/cascade/common.py
DELETED
|
@@ -1,154 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
This file is part of ComfyUI.
|
| 3 |
-
Copyright (C) 2024 Stability AI
|
| 4 |
-
|
| 5 |
-
This program is free software: you can redistribute it and/or modify
|
| 6 |
-
it under the terms of the GNU General Public License as published by
|
| 7 |
-
the Free Software Foundation, either version 3 of the License, or
|
| 8 |
-
(at your option) any later version.
|
| 9 |
-
|
| 10 |
-
This program is distributed in the hope that it will be useful,
|
| 11 |
-
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 12 |
-
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 13 |
-
GNU General Public License for more details.
|
| 14 |
-
|
| 15 |
-
You should have received a copy of the GNU General Public License
|
| 16 |
-
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 17 |
-
"""
|
| 18 |
-
|
| 19 |
-
import torch
|
| 20 |
-
import torch.nn as nn
|
| 21 |
-
from comfy.ldm.modules.attention import optimized_attention
|
| 22 |
-
import comfy.ops
|
| 23 |
-
|
| 24 |
-
class OptimizedAttention(nn.Module):
|
| 25 |
-
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
|
| 26 |
-
super().__init__()
|
| 27 |
-
self.heads = nhead
|
| 28 |
-
|
| 29 |
-
self.to_q = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
|
| 30 |
-
self.to_k = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
|
| 31 |
-
self.to_v = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
|
| 32 |
-
|
| 33 |
-
self.out_proj = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
|
| 34 |
-
|
| 35 |
-
def forward(self, q, k, v):
|
| 36 |
-
q = self.to_q(q)
|
| 37 |
-
k = self.to_k(k)
|
| 38 |
-
v = self.to_v(v)
|
| 39 |
-
|
| 40 |
-
out = optimized_attention(q, k, v, self.heads)
|
| 41 |
-
|
| 42 |
-
return self.out_proj(out)
|
| 43 |
-
|
| 44 |
-
class Attention2D(nn.Module):
|
| 45 |
-
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
|
| 46 |
-
super().__init__()
|
| 47 |
-
self.attn = OptimizedAttention(c, nhead, dtype=dtype, device=device, operations=operations)
|
| 48 |
-
# self.attn = nn.MultiheadAttention(c, nhead, dropout=dropout, bias=True, batch_first=True, dtype=dtype, device=device)
|
| 49 |
-
|
| 50 |
-
def forward(self, x, kv, self_attn=False):
|
| 51 |
-
orig_shape = x.shape
|
| 52 |
-
x = x.view(x.size(0), x.size(1), -1).permute(0, 2, 1) # Bx4xHxW -> Bx(HxW)x4
|
| 53 |
-
if self_attn:
|
| 54 |
-
kv = torch.cat([x, kv], dim=1)
|
| 55 |
-
# x = self.attn(x, kv, kv, need_weights=False)[0]
|
| 56 |
-
x = self.attn(x, kv, kv)
|
| 57 |
-
x = x.permute(0, 2, 1).view(*orig_shape)
|
| 58 |
-
return x
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def LayerNorm2d_op(operations):
|
| 62 |
-
class LayerNorm2d(operations.LayerNorm):
|
| 63 |
-
def __init__(self, *args, **kwargs):
|
| 64 |
-
super().__init__(*args, **kwargs)
|
| 65 |
-
|
| 66 |
-
def forward(self, x):
|
| 67 |
-
return super().forward(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
|
| 68 |
-
return LayerNorm2d
|
| 69 |
-
|
| 70 |
-
class GlobalResponseNorm(nn.Module):
|
| 71 |
-
"from https://github.com/facebookresearch/ConvNeXt-V2/blob/3608f67cc1dae164790c5d0aead7bf2d73d9719b/models/utils.py#L105"
|
| 72 |
-
def __init__(self, dim, dtype=None, device=None):
|
| 73 |
-
super().__init__()
|
| 74 |
-
self.gamma = nn.Parameter(torch.empty(1, 1, 1, dim, dtype=dtype, device=device))
|
| 75 |
-
self.beta = nn.Parameter(torch.empty(1, 1, 1, dim, dtype=dtype, device=device))
|
| 76 |
-
|
| 77 |
-
def forward(self, x):
|
| 78 |
-
Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
|
| 79 |
-
Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
|
| 80 |
-
return comfy.ops.cast_to_input(self.gamma, x) * (x * Nx) + comfy.ops.cast_to_input(self.beta, x) + x
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
class ResBlock(nn.Module):
|
| 84 |
-
def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0, dtype=None, device=None, operations=None): # , num_heads=4, expansion=2):
|
| 85 |
-
super().__init__()
|
| 86 |
-
self.depthwise = operations.Conv2d(c, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c, dtype=dtype, device=device)
|
| 87 |
-
# self.depthwise = SAMBlock(c, num_heads, expansion)
|
| 88 |
-
self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
|
| 89 |
-
self.channelwise = nn.Sequential(
|
| 90 |
-
operations.Linear(c + c_skip, c * 4, dtype=dtype, device=device),
|
| 91 |
-
nn.GELU(),
|
| 92 |
-
GlobalResponseNorm(c * 4, dtype=dtype, device=device),
|
| 93 |
-
nn.Dropout(dropout),
|
| 94 |
-
operations.Linear(c * 4, c, dtype=dtype, device=device)
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
-
def forward(self, x, x_skip=None):
|
| 98 |
-
x_res = x
|
| 99 |
-
x = self.norm(self.depthwise(x))
|
| 100 |
-
if x_skip is not None:
|
| 101 |
-
x = torch.cat([x, x_skip], dim=1)
|
| 102 |
-
x = self.channelwise(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
|
| 103 |
-
return x + x_res
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
class AttnBlock(nn.Module):
|
| 107 |
-
def __init__(self, c, c_cond, nhead, self_attn=True, dropout=0.0, dtype=None, device=None, operations=None):
|
| 108 |
-
super().__init__()
|
| 109 |
-
self.self_attn = self_attn
|
| 110 |
-
self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
|
| 111 |
-
self.attention = Attention2D(c, nhead, dropout, dtype=dtype, device=device, operations=operations)
|
| 112 |
-
self.kv_mapper = nn.Sequential(
|
| 113 |
-
nn.SiLU(),
|
| 114 |
-
operations.Linear(c_cond, c, dtype=dtype, device=device)
|
| 115 |
-
)
|
| 116 |
-
|
| 117 |
-
def forward(self, x, kv):
|
| 118 |
-
kv = self.kv_mapper(kv)
|
| 119 |
-
x = x + self.attention(self.norm(x), kv, self_attn=self.self_attn)
|
| 120 |
-
return x
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
class FeedForwardBlock(nn.Module):
|
| 124 |
-
def __init__(self, c, dropout=0.0, dtype=None, device=None, operations=None):
|
| 125 |
-
super().__init__()
|
| 126 |
-
self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
|
| 127 |
-
self.channelwise = nn.Sequential(
|
| 128 |
-
operations.Linear(c, c * 4, dtype=dtype, device=device),
|
| 129 |
-
nn.GELU(),
|
| 130 |
-
GlobalResponseNorm(c * 4, dtype=dtype, device=device),
|
| 131 |
-
nn.Dropout(dropout),
|
| 132 |
-
operations.Linear(c * 4, c, dtype=dtype, device=device)
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
-
def forward(self, x):
|
| 136 |
-
x = x + self.channelwise(self.norm(x).permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
|
| 137 |
-
return x
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
class TimestepBlock(nn.Module):
|
| 141 |
-
def __init__(self, c, c_timestep, conds=['sca'], dtype=None, device=None, operations=None):
|
| 142 |
-
super().__init__()
|
| 143 |
-
self.mapper = operations.Linear(c_timestep, c * 2, dtype=dtype, device=device)
|
| 144 |
-
self.conds = conds
|
| 145 |
-
for cname in conds:
|
| 146 |
-
setattr(self, f"mapper_{cname}", operations.Linear(c_timestep, c * 2, dtype=dtype, device=device))
|
| 147 |
-
|
| 148 |
-
def forward(self, x, t):
|
| 149 |
-
t = t.chunk(len(self.conds) + 1, dim=1)
|
| 150 |
-
a, b = self.mapper(t[0])[:, :, None, None].chunk(2, dim=1)
|
| 151 |
-
for i, c in enumerate(self.conds):
|
| 152 |
-
ac, bc = getattr(self, f"mapper_{c}")(t[i + 1])[:, :, None, None].chunk(2, dim=1)
|
| 153 |
-
a, b = a + ac, b + bc
|
| 154 |
-
return x * (1 + a) + b
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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