|
| 1 | +import math |
| 2 | +from dataclasses import dataclass |
| 3 | + |
| 4 | +import torch |
| 5 | +from einops import rearrange |
| 6 | +from torch import Tensor, nn |
| 7 | + |
| 8 | +from .math import attention, rope |
| 9 | +import comfy.ops |
| 10 | + |
| 11 | + |
| 12 | +class EmbedND(nn.Module): |
| 13 | + def __init__(self, dim: int, theta: int, axes_dim: list[int]): |
| 14 | + super().__init__() |
| 15 | + self.dim = dim |
| 16 | + self.theta = theta |
| 17 | + self.axes_dim = axes_dim |
| 18 | + |
| 19 | + def forward(self, ids: Tensor) -> Tensor: |
| 20 | + n_axes = ids.shape[-1] |
| 21 | + emb = torch.cat( |
| 22 | + [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)], |
| 23 | + dim=-3, |
| 24 | + ) |
| 25 | + |
| 26 | + return emb.unsqueeze(1) |
| 27 | + |
| 28 | + |
| 29 | +def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0): |
| 30 | + """ |
| 31 | + Create sinusoidal timestep embeddings. |
| 32 | + :param t: a 1-D Tensor of N indices, one per batch element. |
| 33 | + These may be fractional. |
| 34 | + :param dim: the dimension of the output. |
| 35 | + :param max_period: controls the minimum frequency of the embeddings. |
| 36 | + :return: an (N, D) Tensor of positional embeddings. |
| 37 | + """ |
| 38 | + t = time_factor * t |
| 39 | + half = dim // 2 |
| 40 | + freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to( |
| 41 | + t.device |
| 42 | + ) |
| 43 | + |
| 44 | + args = t[:, None].float() * freqs[None] |
| 45 | + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) |
| 46 | + if dim % 2: |
| 47 | + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) |
| 48 | + if torch.is_floating_point(t): |
| 49 | + embedding = embedding.to(t) |
| 50 | + return embedding |
| 51 | + |
| 52 | + |
| 53 | +class MLPEmbedder(nn.Module): |
| 54 | + def __init__(self, in_dim: int, hidden_dim: int, dtype=None, device=None, operations=None): |
| 55 | + super().__init__() |
| 56 | + self.in_layer = operations.Linear(in_dim, hidden_dim, bias=True, dtype=dtype, device=device) |
| 57 | + self.silu = nn.SiLU() |
| 58 | + self.out_layer = operations.Linear(hidden_dim, hidden_dim, bias=True, dtype=dtype, device=device) |
| 59 | + |
| 60 | + def forward(self, x: Tensor) -> Tensor: |
| 61 | + return self.out_layer(self.silu(self.in_layer(x))) |
| 62 | + |
| 63 | + |
| 64 | +class RMSNorm(torch.nn.Module): |
| 65 | + def __init__(self, dim: int, dtype=None, device=None, operations=None): |
| 66 | + super().__init__() |
| 67 | + self.scale = nn.Parameter(torch.empty((dim), dtype=dtype, device=device)) |
| 68 | + |
| 69 | + def forward(self, x: Tensor): |
| 70 | + x_dtype = x.dtype |
| 71 | + x = x.float() |
| 72 | + rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6) |
| 73 | + return (x * rrms).to(dtype=x_dtype) * comfy.ops.cast_to(self.scale, dtype=x_dtype, device=x.device) |
| 74 | + |
| 75 | + |
| 76 | +class QKNorm(torch.nn.Module): |
| 77 | + def __init__(self, dim: int, dtype=None, device=None, operations=None): |
| 78 | + super().__init__() |
| 79 | + self.query_norm = RMSNorm(dim, dtype=dtype, device=device, operations=operations) |
| 80 | + self.key_norm = RMSNorm(dim, dtype=dtype, device=device, operations=operations) |
| 81 | + |
| 82 | + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]: |
| 83 | + q = self.query_norm(q) |
| 84 | + k = self.key_norm(k) |
| 85 | + return q.to(v), k.to(v) |
| 86 | + |
| 87 | + |
| 88 | +class SelfAttention(nn.Module): |
| 89 | + def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False, dtype=None, device=None, operations=None): |
| 90 | + super().__init__() |
| 91 | + self.num_heads = num_heads |
| 92 | + head_dim = dim // num_heads |
| 93 | + |
| 94 | + self.qkv = operations.Linear(dim, dim * 3, bias=qkv_bias, dtype=dtype, device=device) |
| 95 | + self.norm = QKNorm(head_dim, dtype=dtype, device=device, operations=operations) |
| 96 | + self.proj = operations.Linear(dim, dim, dtype=dtype, device=device) |
| 97 | + |
| 98 | + def forward(self, x: Tensor, pe: Tensor) -> Tensor: |
| 99 | + qkv = self.qkv(x) |
| 100 | + q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) |
| 101 | + q, k = self.norm(q, k, v) |
| 102 | + x = attention(q, k, v, pe=pe) |
| 103 | + x = self.proj(x) |
| 104 | + return x |
| 105 | + |
| 106 | + |
| 107 | +@dataclass |
| 108 | +class ModulationOut: |
| 109 | + shift: Tensor |
| 110 | + scale: Tensor |
| 111 | + gate: Tensor |
| 112 | + |
| 113 | + |
| 114 | +class Modulation(nn.Module): |
| 115 | + def __init__(self, dim: int, double: bool, dtype=None, device=None, operations=None): |
| 116 | + super().__init__() |
| 117 | + self.is_double = double |
| 118 | + self.multiplier = 6 if double else 3 |
| 119 | + self.lin = operations.Linear(dim, self.multiplier * dim, bias=True, dtype=dtype, device=device) |
| 120 | + |
| 121 | + def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]: |
| 122 | + out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1) |
| 123 | + |
| 124 | + return ( |
| 125 | + ModulationOut(*out[:3]), |
| 126 | + ModulationOut(*out[3:]) if self.is_double else None, |
| 127 | + ) |
| 128 | + |
| 129 | + |
| 130 | +class DoubleStreamBlock(nn.Module): |
| 131 | + def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False, dtype=None, device=None, operations=None): |
| 132 | + super().__init__() |
| 133 | + |
| 134 | + mlp_hidden_dim = int(hidden_size * mlp_ratio) |
| 135 | + self.num_heads = num_heads |
| 136 | + self.hidden_size = hidden_size |
| 137 | + self.img_mod = Modulation(hidden_size, double=True, dtype=dtype, device=device, operations=operations) |
| 138 | + self.img_norm1 = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device) |
| 139 | + self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, dtype=dtype, device=device, operations=operations) |
| 140 | + |
| 141 | + self.img_norm2 = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device) |
| 142 | + self.img_mlp = nn.Sequential( |
| 143 | + operations.Linear(hidden_size, mlp_hidden_dim, bias=True, dtype=dtype, device=device), |
| 144 | + nn.GELU(approximate="tanh"), |
| 145 | + operations.Linear(mlp_hidden_dim, hidden_size, bias=True, dtype=dtype, device=device), |
| 146 | + ) |
| 147 | + |
| 148 | + self.txt_mod = Modulation(hidden_size, double=True, dtype=dtype, device=device, operations=operations) |
| 149 | + self.txt_norm1 = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device) |
| 150 | + self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, dtype=dtype, device=device, operations=operations) |
| 151 | + |
| 152 | + self.txt_norm2 = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device) |
| 153 | + self.txt_mlp = nn.Sequential( |
| 154 | + operations.Linear(hidden_size, mlp_hidden_dim, bias=True, dtype=dtype, device=device), |
| 155 | + nn.GELU(approximate="tanh"), |
| 156 | + operations.Linear(mlp_hidden_dim, hidden_size, bias=True, dtype=dtype, device=device), |
| 157 | + ) |
| 158 | + |
| 159 | + def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]: |
| 160 | + img_mod1, img_mod2 = self.img_mod(vec) |
| 161 | + txt_mod1, txt_mod2 = self.txt_mod(vec) |
| 162 | + |
| 163 | + # prepare image for attention |
| 164 | + img_modulated = self.img_norm1(img) |
| 165 | + img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift |
| 166 | + img_qkv = self.img_attn.qkv(img_modulated) |
| 167 | + img_q, img_k, img_v = rearrange(img_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) |
| 168 | + img_q, img_k = self.img_attn.norm(img_q, img_k, img_v) |
| 169 | + |
| 170 | + # prepare txt for attention |
| 171 | + txt_modulated = self.txt_norm1(txt) |
| 172 | + txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift |
| 173 | + txt_qkv = self.txt_attn.qkv(txt_modulated) |
| 174 | + txt_q, txt_k, txt_v = rearrange(txt_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) |
| 175 | + txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v) |
| 176 | + |
| 177 | + # run actual attention |
| 178 | + q = torch.cat((txt_q, img_q), dim=2) |
| 179 | + k = torch.cat((txt_k, img_k), dim=2) |
| 180 | + v = torch.cat((txt_v, img_v), dim=2) |
| 181 | + |
| 182 | + attn = attention(q, k, v, pe=pe) |
| 183 | + txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :] |
| 184 | + |
| 185 | + # calculate the img bloks |
| 186 | + img = img + img_mod1.gate * self.img_attn.proj(img_attn) |
| 187 | + img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift) |
| 188 | + |
| 189 | + # calculate the txt bloks |
| 190 | + txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn) |
| 191 | + txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift) |
| 192 | + return img, txt |
| 193 | + |
| 194 | + |
| 195 | +class SingleStreamBlock(nn.Module): |
| 196 | + """ |
| 197 | + A DiT block with parallel linear layers as described in |
| 198 | + https://arxiv.org/abs/2302.05442 and adapted modulation interface. |
| 199 | + """ |
| 200 | + |
| 201 | + def __init__( |
| 202 | + self, |
| 203 | + hidden_size: int, |
| 204 | + num_heads: int, |
| 205 | + mlp_ratio: float = 4.0, |
| 206 | + qk_scale: float | None = None, |
| 207 | + dtype=None, |
| 208 | + device=None, |
| 209 | + operations=None |
| 210 | + ): |
| 211 | + super().__init__() |
| 212 | + self.hidden_dim = hidden_size |
| 213 | + self.num_heads = num_heads |
| 214 | + head_dim = hidden_size // num_heads |
| 215 | + self.scale = qk_scale or head_dim**-0.5 |
| 216 | + |
| 217 | + self.mlp_hidden_dim = int(hidden_size * mlp_ratio) |
| 218 | + # qkv and mlp_in |
| 219 | + self.linear1 = operations.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim, dtype=dtype, device=device) |
| 220 | + # proj and mlp_out |
| 221 | + self.linear2 = operations.Linear(hidden_size + self.mlp_hidden_dim, hidden_size, dtype=dtype, device=device) |
| 222 | + |
| 223 | + self.norm = QKNorm(head_dim, dtype=dtype, device=device, operations=operations) |
| 224 | + |
| 225 | + self.hidden_size = hidden_size |
| 226 | + self.pre_norm = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device) |
| 227 | + |
| 228 | + self.mlp_act = nn.GELU(approximate="tanh") |
| 229 | + self.modulation = Modulation(hidden_size, double=False, dtype=dtype, device=device, operations=operations) |
| 230 | + |
| 231 | + def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor: |
| 232 | + mod, _ = self.modulation(vec) |
| 233 | + x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift |
| 234 | + qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1) |
| 235 | + |
| 236 | + q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) |
| 237 | + q, k = self.norm(q, k, v) |
| 238 | + |
| 239 | + # compute attention |
| 240 | + attn = attention(q, k, v, pe=pe) |
| 241 | + # compute activation in mlp stream, cat again and run second linear layer |
| 242 | + output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2)) |
| 243 | + return x + mod.gate * output |
| 244 | + |
| 245 | + |
| 246 | +class LastLayer(nn.Module): |
| 247 | + def __init__(self, hidden_size: int, patch_size: int, out_channels: int, dtype=None, device=None, operations=None): |
| 248 | + super().__init__() |
| 249 | + self.norm_final = operations.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device) |
| 250 | + self.linear = operations.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True, dtype=dtype, device=device) |
| 251 | + self.adaLN_modulation = nn.Sequential(nn.SiLU(), operations.Linear(hidden_size, 2 * hidden_size, bias=True, dtype=dtype, device=device)) |
| 252 | + |
| 253 | + def forward(self, x: Tensor, vec: Tensor) -> Tensor: |
| 254 | + shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1) |
| 255 | + x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :] |
| 256 | + x = self.linear(x) |
| 257 | + return x |
0 commit comments