|
| 1 | +import math |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch import nn |
| 5 | + |
| 6 | + |
| 7 | +# unet_grad_tts.py |
| 8 | +# TODO(Patrick) - weird linear attention layer. Check with: https://github.com/huawei-noah/Speech-Backbones/issues/15 |
| 9 | +class LinearAttention(torch.nn.Module): |
| 10 | + def __init__(self, dim, heads=4, dim_head=32): |
| 11 | + super(LinearAttention, self).__init__() |
| 12 | + self.heads = heads |
| 13 | + self.dim_head = dim_head |
| 14 | + hidden_dim = dim_head * heads |
| 15 | + self.to_qkv = torch.nn.Conv2d(dim, hidden_dim * 3, 1, bias=False) |
| 16 | + self.to_out = torch.nn.Conv2d(hidden_dim, dim, 1) |
| 17 | + |
| 18 | + def forward(self, x): |
| 19 | + b, c, h, w = x.shape |
| 20 | + qkv = self.to_qkv(x) |
| 21 | + q, k, v = ( |
| 22 | + qkv.reshape(b, 3, self.heads, self.dim_head, h, w) |
| 23 | + .permute(1, 0, 2, 3, 4, 5) |
| 24 | + .reshape(3, b, self.heads, self.dim_head, -1) |
| 25 | + ) |
| 26 | + k = k.softmax(dim=-1) |
| 27 | + context = torch.einsum("bhdn,bhen->bhde", k, v) |
| 28 | + out = torch.einsum("bhde,bhdn->bhen", context, q) |
| 29 | + out = out.reshape(b, self.heads, self.dim_head, h, w).reshape(b, self.heads * self.dim_head, h, w) |
| 30 | + return self.to_out(out) |
| 31 | + |
| 32 | + |
| 33 | +# the main attention block that is used for all models |
| 34 | +class AttentionBlock(nn.Module): |
| 35 | + """ |
| 36 | + An attention block that allows spatial positions to attend to each other. |
| 37 | +
|
| 38 | + Originally ported from here, but adapted to the N-d case. |
| 39 | + https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. |
| 40 | + """ |
| 41 | + |
| 42 | + def __init__( |
| 43 | + self, |
| 44 | + channels, |
| 45 | + num_heads=1, |
| 46 | + num_head_channels=-1, |
| 47 | + num_groups=32, |
| 48 | + use_checkpoint=False, |
| 49 | + encoder_channels=None, |
| 50 | + use_new_attention_order=False, # TODO(Patrick) -> is never used, maybe delete? |
| 51 | + overwrite_qkv=False, |
| 52 | + overwrite_linear=False, |
| 53 | + rescale_output_factor=1.0, |
| 54 | + ): |
| 55 | + super().__init__() |
| 56 | + self.channels = channels |
| 57 | + if num_head_channels == -1: |
| 58 | + self.num_heads = num_heads |
| 59 | + else: |
| 60 | + assert ( |
| 61 | + channels % num_head_channels == 0 |
| 62 | + ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" |
| 63 | + self.num_heads = channels // num_head_channels |
| 64 | + |
| 65 | + self.use_checkpoint = use_checkpoint |
| 66 | + self.norm = nn.GroupNorm(num_channels=channels, num_groups=num_groups, eps=1e-5, affine=True) |
| 67 | + self.qkv = nn.Conv1d(channels, channels * 3, 1) |
| 68 | + self.n_heads = self.num_heads |
| 69 | + self.rescale_output_factor = rescale_output_factor |
| 70 | + |
| 71 | + if encoder_channels is not None: |
| 72 | + self.encoder_kv = nn.Conv1d(encoder_channels, channels * 2, 1) |
| 73 | + |
| 74 | + self.proj_out = zero_module(nn.Conv1d(channels, channels, 1)) |
| 75 | + |
| 76 | + self.overwrite_qkv = overwrite_qkv |
| 77 | + if overwrite_qkv: |
| 78 | + in_channels = channels |
| 79 | + self.norm = nn.GroupNorm(num_channels=channels, num_groups=num_groups, eps=1e-6) |
| 80 | + self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) |
| 81 | + self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) |
| 82 | + self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) |
| 83 | + self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) |
| 84 | + |
| 85 | + self.overwrite_linear = overwrite_linear |
| 86 | + if self.overwrite_linear: |
| 87 | + num_groups = min(channels // 4, 32) |
| 88 | + self.norm = nn.GroupNorm(num_channels=channels, num_groups=num_groups, eps=1e-6) |
| 89 | + self.NIN_0 = NIN(channels, channels) |
| 90 | + self.NIN_1 = NIN(channels, channels) |
| 91 | + self.NIN_2 = NIN(channels, channels) |
| 92 | + self.NIN_3 = NIN(channels, channels) |
| 93 | + |
| 94 | + self.GroupNorm_0 = nn.GroupNorm(num_groups=num_groups, num_channels=channels, eps=1e-6) |
| 95 | + |
| 96 | + self.is_overwritten = False |
| 97 | + |
| 98 | + def set_weights(self, module): |
| 99 | + if self.overwrite_qkv: |
| 100 | + qkv_weight = torch.cat([module.q.weight.data, module.k.weight.data, module.v.weight.data], dim=0)[ |
| 101 | + :, :, :, 0 |
| 102 | + ] |
| 103 | + qkv_bias = torch.cat([module.q.bias.data, module.k.bias.data, module.v.bias.data], dim=0) |
| 104 | + |
| 105 | + self.qkv.weight.data = qkv_weight |
| 106 | + self.qkv.bias.data = qkv_bias |
| 107 | + |
| 108 | + proj_out = zero_module(nn.Conv1d(self.channels, self.channels, 1)) |
| 109 | + proj_out.weight.data = module.proj_out.weight.data[:, :, :, 0] |
| 110 | + proj_out.bias.data = module.proj_out.bias.data |
| 111 | + |
| 112 | + self.proj_out = proj_out |
| 113 | + elif self.overwrite_linear: |
| 114 | + self.qkv.weight.data = torch.concat( |
| 115 | + [self.NIN_0.W.data.T, self.NIN_1.W.data.T, self.NIN_2.W.data.T], dim=0 |
| 116 | + )[:, :, None] |
| 117 | + self.qkv.bias.data = torch.concat([self.NIN_0.b.data, self.NIN_1.b.data, self.NIN_2.b.data], dim=0) |
| 118 | + |
| 119 | + self.proj_out.weight.data = self.NIN_3.W.data.T[:, :, None] |
| 120 | + self.proj_out.bias.data = self.NIN_3.b.data |
| 121 | + |
| 122 | + self.norm.weight.data = self.GroupNorm_0.weight.data |
| 123 | + self.norm.bias.data = self.GroupNorm_0.bias.data |
| 124 | + |
| 125 | + def forward(self, x, encoder_out=None): |
| 126 | + if (self.overwrite_qkv or self.overwrite_linear) and not self.is_overwritten: |
| 127 | + self.set_weights(self) |
| 128 | + self.is_overwritten = True |
| 129 | + |
| 130 | + b, c, *spatial = x.shape |
| 131 | + hid_states = self.norm(x).view(b, c, -1) |
| 132 | + |
| 133 | + qkv = self.qkv(hid_states) |
| 134 | + bs, width, length = qkv.shape |
| 135 | + assert width % (3 * self.n_heads) == 0 |
| 136 | + ch = width // (3 * self.n_heads) |
| 137 | + q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) |
| 138 | + |
| 139 | + if encoder_out is not None: |
| 140 | + encoder_kv = self.encoder_kv(encoder_out) |
| 141 | + assert encoder_kv.shape[1] == self.n_heads * ch * 2 |
| 142 | + ek, ev = encoder_kv.reshape(bs * self.n_heads, ch * 2, -1).split(ch, dim=1) |
| 143 | + k = torch.cat([ek, k], dim=-1) |
| 144 | + v = torch.cat([ev, v], dim=-1) |
| 145 | + |
| 146 | + scale = 1 / math.sqrt(math.sqrt(ch)) |
| 147 | + weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards |
| 148 | + weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) |
| 149 | + |
| 150 | + a = torch.einsum("bts,bcs->bct", weight, v) |
| 151 | + h = a.reshape(bs, -1, length) |
| 152 | + |
| 153 | + h = self.proj_out(h) |
| 154 | + h = h.reshape(b, c, *spatial) |
| 155 | + |
| 156 | + result = x + h |
| 157 | + |
| 158 | + result = result / self.rescale_output_factor |
| 159 | + |
| 160 | + return result |
| 161 | + |
| 162 | + |
| 163 | +# unet_score_estimation.py |
| 164 | +# class AttnBlockpp(nn.Module): |
| 165 | +# """Channel-wise self-attention block. Modified from DDPM.""" |
| 166 | +# |
| 167 | +# def __init__( |
| 168 | +# self, |
| 169 | +# channels, |
| 170 | +# skip_rescale=False, |
| 171 | +# init_scale=0.0, |
| 172 | +# num_heads=1, |
| 173 | +# num_head_channels=-1, |
| 174 | +# use_checkpoint=False, |
| 175 | +# encoder_channels=None, |
| 176 | +# use_new_attention_order=False, # TODO(Patrick) -> is never used, maybe delete? |
| 177 | +# overwrite_qkv=False, |
| 178 | +# overwrite_from_grad_tts=False, |
| 179 | +# ): |
| 180 | +# super().__init__() |
| 181 | +# num_groups = min(channels // 4, 32) |
| 182 | +# self.GroupNorm_0 = nn.GroupNorm(num_groups=num_groups, num_channels=channels, eps=1e-6) |
| 183 | +# self.NIN_0 = NIN(channels, channels) |
| 184 | +# self.NIN_1 = NIN(channels, channels) |
| 185 | +# self.NIN_2 = NIN(channels, channels) |
| 186 | +# self.NIN_3 = NIN(channels, channels, init_scale=init_scale) |
| 187 | +# self.skip_rescale = skip_rescale |
| 188 | +# |
| 189 | +# self.channels = channels |
| 190 | +# if num_head_channels == -1: |
| 191 | +# self.num_heads = num_heads |
| 192 | +# else: |
| 193 | +# assert ( |
| 194 | +# channels % num_head_channels == 0 |
| 195 | +# ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" |
| 196 | +# self.num_heads = channels // num_head_channels |
| 197 | +# |
| 198 | +# self.use_checkpoint = use_checkpoint |
| 199 | +# self.norm = nn.GroupNorm(num_channels=channels, num_groups=num_groups, eps=1e-6) |
| 200 | +# self.qkv = nn.Conv1d(channels, channels * 3, 1) |
| 201 | +# self.n_heads = self.num_heads |
| 202 | +# |
| 203 | +# self.proj_out = zero_module(nn.Conv1d(channels, channels, 1)) |
| 204 | +# |
| 205 | +# self.is_weight_set = False |
| 206 | +# |
| 207 | +# def set_weights(self): |
| 208 | +# self.qkv.weight.data = torch.concat([self.NIN_0.W.data.T, self.NIN_1.W.data.T, self.NIN_2.W.data.T], dim=0)[:, :, None] |
| 209 | +# self.qkv.bias.data = torch.concat([self.NIN_0.b.data, self.NIN_1.b.data, self.NIN_2.b.data], dim=0) |
| 210 | +# |
| 211 | +# self.proj_out.weight.data = self.NIN_3.W.data.T[:, :, None] |
| 212 | +# self.proj_out.bias.data = self.NIN_3.b.data |
| 213 | +# |
| 214 | +# self.norm.weight.data = self.GroupNorm_0.weight.data |
| 215 | +# self.norm.bias.data = self.GroupNorm_0.bias.data |
| 216 | +# |
| 217 | +# def forward(self, x): |
| 218 | +# if not self.is_weight_set: |
| 219 | +# self.set_weights() |
| 220 | +# self.is_weight_set = True |
| 221 | +# |
| 222 | +# B, C, H, W = x.shape |
| 223 | +# h = self.GroupNorm_0(x) |
| 224 | +# q = self.NIN_0(h) |
| 225 | +# k = self.NIN_1(h) |
| 226 | +# v = self.NIN_2(h) |
| 227 | +# |
| 228 | +# w = torch.einsum("bchw,bcij->bhwij", q, k) * (int(C) ** (-0.5)) |
| 229 | +# w = torch.reshape(w, (B, H, W, H * W)) |
| 230 | +# w = F.softmax(w, dim=-1) |
| 231 | +# w = torch.reshape(w, (B, H, W, H, W)) |
| 232 | +# h = torch.einsum("bhwij,bcij->bchw", w, v) |
| 233 | +# h = self.NIN_3(h) |
| 234 | +# |
| 235 | +# if not self.skip_rescale: |
| 236 | +# result = x + h |
| 237 | +# else: |
| 238 | +# result = (x + h) / np.sqrt(2.0) |
| 239 | +# |
| 240 | +# result = self.forward_2(x) |
| 241 | +# |
| 242 | +# return result |
| 243 | +# |
| 244 | +# def forward_2(self, x, encoder_out=None): |
| 245 | +# b, c, *spatial = x.shape |
| 246 | +# hid_states = self.norm(x).view(b, c, -1) |
| 247 | +# |
| 248 | +# qkv = self.qkv(hid_states) |
| 249 | +# bs, width, length = qkv.shape |
| 250 | +# assert width % (3 * self.n_heads) == 0 |
| 251 | +# ch = width // (3 * self.n_heads) |
| 252 | +# q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) |
| 253 | +# |
| 254 | +# if encoder_out is not None: |
| 255 | +# encoder_kv = self.encoder_kv(encoder_out) |
| 256 | +# assert encoder_kv.shape[1] == self.n_heads * ch * 2 |
| 257 | +# ek, ev = encoder_kv.reshape(bs * self.n_heads, ch * 2, -1).split(ch, dim=1) |
| 258 | +# k = torch.cat([ek, k], dim=-1) |
| 259 | +# v = torch.cat([ev, v], dim=-1) |
| 260 | +# |
| 261 | +# scale = 1 / math.sqrt(math.sqrt(ch)) |
| 262 | +# weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards |
| 263 | +# weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) |
| 264 | +# |
| 265 | +# a = torch.einsum("bts,bcs->bct", weight, v) |
| 266 | +# h = a.reshape(bs, -1, length) |
| 267 | +# |
| 268 | +# h = self.proj_out(h) |
| 269 | +# h = h.reshape(b, c, *spatial) |
| 270 | +# |
| 271 | +# return (x + h) / np.sqrt(2.0) |
| 272 | + |
| 273 | + |
| 274 | +# TODO(Patrick) - this can and should be removed |
| 275 | +def zero_module(module): |
| 276 | + """ |
| 277 | + Zero out the parameters of a module and return it. |
| 278 | + """ |
| 279 | + for p in module.parameters(): |
| 280 | + p.detach().zero_() |
| 281 | + return module |
| 282 | + |
| 283 | + |
| 284 | +# TODO(Patrick) - remove once all weights have been converted -> not needed anymore then |
| 285 | +class NIN(nn.Module): |
| 286 | + def __init__(self, in_dim, num_units, init_scale=0.1): |
| 287 | + super().__init__() |
| 288 | + self.W = nn.Parameter(torch.zeros(in_dim, num_units), requires_grad=True) |
| 289 | + self.b = nn.Parameter(torch.zeros(num_units), requires_grad=True) |
0 commit comments