decoder.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Tuple, Optional, Dict, Any
  15. import torch
  16. import torch.nn as nn
  17. import torch.nn.functional as F
  18. from einops import pack, rearrange, repeat
  19. from diffusers.models.attention_processor import Attention, AttnProcessor2_0, inspect, logger, deprecate
  20. from cosyvoice.utils.common import mask_to_bias
  21. from cosyvoice.utils.mask import add_optional_chunk_mask
  22. from matcha.models.components.decoder import SinusoidalPosEmb, Block1D, ResnetBlock1D, Downsample1D, TimestepEmbedding, Upsample1D
  23. from matcha.models.components.transformer import BasicTransformerBlock, maybe_allow_in_graph
  24. class Transpose(torch.nn.Module):
  25. def __init__(self, dim0: int, dim1: int):
  26. super().__init__()
  27. self.dim0 = dim0
  28. self.dim1 = dim1
  29. def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor]:
  30. x = torch.transpose(x, self.dim0, self.dim1)
  31. return x
  32. class CausalConv1d(torch.nn.Conv1d):
  33. def __init__(
  34. self,
  35. in_channels: int,
  36. out_channels: int,
  37. kernel_size: int,
  38. stride: int = 1,
  39. dilation: int = 1,
  40. groups: int = 1,
  41. bias: bool = True,
  42. padding_mode: str = 'zeros',
  43. device=None,
  44. dtype=None
  45. ) -> None:
  46. super(CausalConv1d, self).__init__(in_channels, out_channels,
  47. kernel_size, stride,
  48. padding=0, dilation=dilation,
  49. groups=groups, bias=bias,
  50. padding_mode=padding_mode,
  51. device=device, dtype=dtype)
  52. assert stride == 1
  53. self.causal_padding = kernel_size - 1
  54. def forward(self, x: torch.Tensor, cache: torch.Tensor=torch.zeros(0, 0, 0)) -> Tuple[torch.Tensor, torch.Tensor]:
  55. if cache.size(2) == 0:
  56. x = F.pad(x, (self.causal_padding, 0), value=0.0)
  57. else:
  58. assert cache.size(2) == self.causal_padding
  59. x = torch.concat([cache, x], dim=2)
  60. cache = x[:, :, -self.causal_padding:]
  61. x = super(CausalConv1d, self).forward(x)
  62. return x, cache
  63. class CausalBlock1D(Block1D):
  64. def __init__(self, dim: int, dim_out: int):
  65. super(CausalBlock1D, self).__init__(dim, dim_out)
  66. self.block = torch.nn.Sequential(
  67. CausalConv1d(dim, dim_out, 3),
  68. Transpose(1, 2),
  69. nn.LayerNorm(dim_out),
  70. Transpose(1, 2),
  71. nn.Mish(),
  72. )
  73. def forward(self, x: torch.Tensor, mask: torch.Tensor, cache: torch.Tensor=torch.zeros(0, 0, 0)) -> Tuple[torch.Tensor, torch.Tensor]:
  74. output, cache = self.block[0](x * mask, cache)
  75. for i in range(1, len(self.block)):
  76. output = self.block[i](output)
  77. return output * mask, cache
  78. class CausalResnetBlock1D(ResnetBlock1D):
  79. def __init__(self, dim: int, dim_out: int, time_emb_dim: int, groups: int = 8):
  80. super(CausalResnetBlock1D, self).__init__(dim, dim_out, time_emb_dim, groups)
  81. self.block1 = CausalBlock1D(dim, dim_out)
  82. self.block2 = CausalBlock1D(dim_out, dim_out)
  83. def forward(self, x: torch.Tensor, mask: torch.Tensor, time_emb: torch.Tensor, block1_cache: torch.Tensor=torch.zeros(0, 0, 0), block2_cache: torch.Tensor=torch.zeros(0, 0, 0)) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  84. h, block1_cache = self.block1(x, mask, block1_cache)
  85. h += self.mlp(time_emb).unsqueeze(-1)
  86. h, block2_cache = self.block2(h, mask, block2_cache)
  87. output = h + self.res_conv(x * mask)
  88. return output, block1_cache, block2_cache
  89. class CausalAttnProcessor2_0(AttnProcessor2_0):
  90. r"""
  91. Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
  92. """
  93. def __init__(self):
  94. super(CausalAttnProcessor2_0, self).__init__()
  95. def __call__(
  96. self,
  97. attn: Attention,
  98. hidden_states: torch.FloatTensor,
  99. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  100. attention_mask: Optional[torch.FloatTensor] = None,
  101. temb: Optional[torch.FloatTensor] = None,
  102. cache: torch.Tensor = torch.zeros(0, 0, 0, 0),
  103. *args,
  104. **kwargs,
  105. ) -> Tuple[torch.FloatTensor, torch.Tensor]:
  106. if len(args) > 0 or kwargs.get("scale", None) is not None:
  107. deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
  108. deprecate("scale", "1.0.0", deprecation_message)
  109. residual = hidden_states
  110. if attn.spatial_norm is not None:
  111. hidden_states = attn.spatial_norm(hidden_states, temb)
  112. input_ndim = hidden_states.ndim
  113. if input_ndim == 4:
  114. batch_size, channel, height, width = hidden_states.shape
  115. hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
  116. batch_size, sequence_length, _ = (
  117. hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
  118. )
  119. if attention_mask is not None:
  120. # NOTE do not use attn.prepare_attention_mask as we have already provided the correct attention_mask
  121. # scaled_dot_product_attention expects attention_mask shape to be
  122. # (batch, heads, source_length, target_length)
  123. attention_mask = attention_mask.unsqueeze(dim=1).repeat(1, attn.heads, 1, 1)
  124. if attn.group_norm is not None:
  125. hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
  126. query = attn.to_q(hidden_states)
  127. if encoder_hidden_states is None:
  128. encoder_hidden_states = hidden_states
  129. elif attn.norm_cross:
  130. encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
  131. key_cache = attn.to_k(encoder_hidden_states)
  132. value_cache = attn.to_v(encoder_hidden_states)
  133. # NOTE here we judge cache.size(0) instead of cache.size(1), because init_cache has size (2, 0, 512, 2)
  134. if cache.size(0) != 0:
  135. key = torch.concat([cache[:, :, :, 0], key_cache], dim=1)
  136. value = torch.concat([cache[:, :, :, 1], value_cache], dim=1)
  137. else:
  138. key, value = key_cache, value_cache
  139. cache = torch.stack([key_cache, value_cache], dim=3)
  140. inner_dim = key.shape[-1]
  141. head_dim = inner_dim // attn.heads
  142. query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
  143. key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
  144. value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
  145. # the output of sdp = (batch, num_heads, seq_len, head_dim)
  146. # TODO: add support for attn.scale when we move to Torch 2.1
  147. hidden_states = F.scaled_dot_product_attention(
  148. query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
  149. )
  150. hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
  151. hidden_states = hidden_states.to(query.dtype)
  152. # linear proj
  153. hidden_states = attn.to_out[0](hidden_states)
  154. # dropout
  155. hidden_states = attn.to_out[1](hidden_states)
  156. if input_ndim == 4:
  157. hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
  158. if attn.residual_connection:
  159. hidden_states = hidden_states + residual
  160. hidden_states = hidden_states / attn.rescale_output_factor
  161. return hidden_states, cache
  162. @maybe_allow_in_graph
  163. class CausalAttention(Attention):
  164. def __init__(
  165. self,
  166. query_dim: int,
  167. cross_attention_dim: Optional[int] = None,
  168. heads: int = 8,
  169. dim_head: int = 64,
  170. dropout: float = 0.0,
  171. bias: bool = False,
  172. upcast_attention: bool = False,
  173. upcast_softmax: bool = False,
  174. cross_attention_norm: Optional[str] = None,
  175. cross_attention_norm_num_groups: int = 32,
  176. added_kv_proj_dim: Optional[int] = None,
  177. norm_num_groups: Optional[int] = None,
  178. spatial_norm_dim: Optional[int] = None,
  179. out_bias: bool = True,
  180. scale_qk: bool = True,
  181. only_cross_attention: bool = False,
  182. eps: float = 1e-5,
  183. rescale_output_factor: float = 1.0,
  184. residual_connection: bool = False,
  185. _from_deprecated_attn_block: bool = False,
  186. processor: Optional["AttnProcessor2_0"] = None,
  187. out_dim: int = None,
  188. ):
  189. super(CausalAttention, self).__init__(query_dim, cross_attention_dim, heads, dim_head, dropout, bias, upcast_attention, upcast_softmax, cross_attention_norm, cross_attention_norm_num_groups,
  190. added_kv_proj_dim, norm_num_groups, spatial_norm_dim, out_bias, scale_qk, only_cross_attention, eps, rescale_output_factor, residual_connection, _from_deprecated_attn_block, processor, out_dim)
  191. processor = CausalAttnProcessor2_0()
  192. self.set_processor(processor)
  193. def forward(
  194. self,
  195. hidden_states: torch.FloatTensor,
  196. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  197. attention_mask: Optional[torch.FloatTensor] = None,
  198. cache: torch.Tensor = torch.zeros(0, 0, 0, 0),
  199. **cross_attention_kwargs,
  200. ) -> Tuple[torch.Tensor, torch.Tensor]:
  201. r"""
  202. The forward method of the `Attention` class.
  203. Args:
  204. hidden_states (`torch.Tensor`):
  205. The hidden states of the query.
  206. encoder_hidden_states (`torch.Tensor`, *optional*):
  207. The hidden states of the encoder.
  208. attention_mask (`torch.Tensor`, *optional*):
  209. The attention mask to use. If `None`, no mask is applied.
  210. **cross_attention_kwargs:
  211. Additional keyword arguments to pass along to the cross attention.
  212. Returns:
  213. `torch.Tensor`: The output of the attention layer.
  214. """
  215. # The `Attention` class can call different attention processors / attention functions
  216. # here we simply pass along all tensors to the selected processor class
  217. # For standard processors that are defined here, `**cross_attention_kwargs` is empty
  218. attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys())
  219. unused_kwargs = [k for k, _ in cross_attention_kwargs.items() if k not in attn_parameters]
  220. if len(unused_kwargs) > 0:
  221. logger.warning(
  222. f"cross_attention_kwargs {unused_kwargs} are not expected by {self.processor.__class__.__name__} and will be ignored."
  223. )
  224. cross_attention_kwargs = {k: w for k, w in cross_attention_kwargs.items() if k in attn_parameters}
  225. return self.processor(
  226. self,
  227. hidden_states,
  228. encoder_hidden_states=encoder_hidden_states,
  229. attention_mask=attention_mask,
  230. cache=cache,
  231. **cross_attention_kwargs,
  232. )
  233. @maybe_allow_in_graph
  234. class CausalBasicTransformerBlock(BasicTransformerBlock):
  235. def __init__(
  236. self,
  237. dim: int,
  238. num_attention_heads: int,
  239. attention_head_dim: int,
  240. dropout=0.0,
  241. cross_attention_dim: Optional[int] = None,
  242. activation_fn: str = "geglu",
  243. num_embeds_ada_norm: Optional[int] = None,
  244. attention_bias: bool = False,
  245. only_cross_attention: bool = False,
  246. double_self_attention: bool = False,
  247. upcast_attention: bool = False,
  248. norm_elementwise_affine: bool = True,
  249. norm_type: str = "layer_norm",
  250. final_dropout: bool = False,
  251. ):
  252. super(CausalBasicTransformerBlock, self).__init__(dim, num_attention_heads, attention_head_dim, dropout, cross_attention_dim, activation_fn, num_embeds_ada_norm,
  253. attention_bias, only_cross_attention, double_self_attention, upcast_attention, norm_elementwise_affine, norm_type, final_dropout)
  254. self.attn1 = CausalAttention(
  255. query_dim=dim,
  256. heads=num_attention_heads,
  257. dim_head=attention_head_dim,
  258. dropout=dropout,
  259. bias=attention_bias,
  260. cross_attention_dim=cross_attention_dim if only_cross_attention else None,
  261. upcast_attention=upcast_attention,
  262. )
  263. def forward(
  264. self,
  265. hidden_states: torch.FloatTensor,
  266. attention_mask: Optional[torch.FloatTensor] = None,
  267. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  268. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  269. timestep: Optional[torch.LongTensor] = None,
  270. cross_attention_kwargs: Dict[str, Any] = None,
  271. class_labels: Optional[torch.LongTensor] = None,
  272. cache: torch.Tensor = torch.zeros(0, 0, 0, 0),
  273. ) -> Tuple[torch.Tensor, torch.Tensor]:
  274. # Notice that normalization is always applied before the real computation in the following blocks.
  275. # 1. Self-Attention
  276. if self.use_ada_layer_norm:
  277. norm_hidden_states = self.norm1(hidden_states, timestep)
  278. elif self.use_ada_layer_norm_zero:
  279. norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
  280. hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
  281. )
  282. else:
  283. norm_hidden_states = self.norm1(hidden_states)
  284. cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
  285. attn_output, cache = self.attn1(
  286. norm_hidden_states,
  287. encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
  288. attention_mask=encoder_attention_mask if self.only_cross_attention else attention_mask,
  289. cache=cache,
  290. **cross_attention_kwargs,
  291. )
  292. if self.use_ada_layer_norm_zero:
  293. attn_output = gate_msa.unsqueeze(1) * attn_output
  294. hidden_states = attn_output + hidden_states
  295. # 2. Cross-Attention
  296. if self.attn2 is not None:
  297. norm_hidden_states = (
  298. self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
  299. )
  300. attn_output = self.attn2(
  301. norm_hidden_states,
  302. encoder_hidden_states=encoder_hidden_states,
  303. attention_mask=encoder_attention_mask,
  304. **cross_attention_kwargs,
  305. )
  306. hidden_states = attn_output + hidden_states
  307. # 3. Feed-forward
  308. norm_hidden_states = self.norm3(hidden_states)
  309. if self.use_ada_layer_norm_zero:
  310. norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
  311. if self._chunk_size is not None:
  312. # "feed_forward_chunk_size" can be used to save memory
  313. if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
  314. raise ValueError(
  315. f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
  316. )
  317. num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
  318. ff_output = torch.cat(
  319. [self.ff(hid_slice) for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)],
  320. dim=self._chunk_dim,
  321. )
  322. else:
  323. ff_output = self.ff(norm_hidden_states)
  324. if self.use_ada_layer_norm_zero:
  325. ff_output = gate_mlp.unsqueeze(1) * ff_output
  326. hidden_states = ff_output + hidden_states
  327. return hidden_states, cache
  328. class ConditionalDecoder(nn.Module):
  329. def __init__(
  330. self,
  331. in_channels,
  332. out_channels,
  333. channels=(256, 256),
  334. dropout=0.05,
  335. attention_head_dim=64,
  336. n_blocks=1,
  337. num_mid_blocks=2,
  338. num_heads=4,
  339. act_fn="snake",
  340. ):
  341. """
  342. This decoder requires an input with the same shape of the target. So, if your text content
  343. is shorter or longer than the outputs, please re-sampling it before feeding to the decoder.
  344. """
  345. super().__init__()
  346. channels = tuple(channels)
  347. self.in_channels = in_channels
  348. self.out_channels = out_channels
  349. self.time_embeddings = SinusoidalPosEmb(in_channels)
  350. time_embed_dim = channels[0] * 4
  351. self.time_mlp = TimestepEmbedding(
  352. in_channels=in_channels,
  353. time_embed_dim=time_embed_dim,
  354. act_fn="silu",
  355. )
  356. self.down_blocks = nn.ModuleList([])
  357. self.mid_blocks = nn.ModuleList([])
  358. self.up_blocks = nn.ModuleList([])
  359. output_channel = in_channels
  360. for i in range(len(channels)): # pylint: disable=consider-using-enumerate
  361. input_channel = output_channel
  362. output_channel = channels[i]
  363. is_last = i == len(channels) - 1
  364. resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
  365. transformer_blocks = nn.ModuleList(
  366. [
  367. BasicTransformerBlock(
  368. dim=output_channel,
  369. num_attention_heads=num_heads,
  370. attention_head_dim=attention_head_dim,
  371. dropout=dropout,
  372. activation_fn=act_fn,
  373. )
  374. for _ in range(n_blocks)
  375. ]
  376. )
  377. downsample = (
  378. Downsample1D(output_channel) if not is_last else nn.Conv1d(output_channel, output_channel, 3, padding=1)
  379. )
  380. self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
  381. for _ in range(num_mid_blocks):
  382. input_channel = channels[-1]
  383. out_channels = channels[-1]
  384. resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
  385. transformer_blocks = nn.ModuleList(
  386. [
  387. BasicTransformerBlock(
  388. dim=output_channel,
  389. num_attention_heads=num_heads,
  390. attention_head_dim=attention_head_dim,
  391. dropout=dropout,
  392. activation_fn=act_fn,
  393. )
  394. for _ in range(n_blocks)
  395. ]
  396. )
  397. self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
  398. channels = channels[::-1] + (channels[0],)
  399. for i in range(len(channels) - 1):
  400. input_channel = channels[i] * 2
  401. output_channel = channels[i + 1]
  402. is_last = i == len(channels) - 2
  403. resnet = ResnetBlock1D(
  404. dim=input_channel,
  405. dim_out=output_channel,
  406. time_emb_dim=time_embed_dim,
  407. )
  408. transformer_blocks = nn.ModuleList(
  409. [
  410. BasicTransformerBlock(
  411. dim=output_channel,
  412. num_attention_heads=num_heads,
  413. attention_head_dim=attention_head_dim,
  414. dropout=dropout,
  415. activation_fn=act_fn,
  416. )
  417. for _ in range(n_blocks)
  418. ]
  419. )
  420. upsample = (
  421. Upsample1D(output_channel, use_conv_transpose=True)
  422. if not is_last
  423. else nn.Conv1d(output_channel, output_channel, 3, padding=1)
  424. )
  425. self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
  426. self.final_block = Block1D(channels[-1], channels[-1])
  427. self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
  428. self.initialize_weights()
  429. def initialize_weights(self):
  430. for m in self.modules():
  431. if isinstance(m, nn.Conv1d):
  432. nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
  433. if m.bias is not None:
  434. nn.init.constant_(m.bias, 0)
  435. elif isinstance(m, nn.GroupNorm):
  436. nn.init.constant_(m.weight, 1)
  437. nn.init.constant_(m.bias, 0)
  438. elif isinstance(m, nn.Linear):
  439. nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
  440. if m.bias is not None:
  441. nn.init.constant_(m.bias, 0)
  442. def forward(self, x, mask, mu, t, spks=None, cond=None):
  443. """Forward pass of the UNet1DConditional model.
  444. Args:
  445. x (torch.Tensor): shape (batch_size, in_channels, time)
  446. mask (_type_): shape (batch_size, 1, time)
  447. t (_type_): shape (batch_size)
  448. spks (_type_, optional): shape: (batch_size, condition_channels). Defaults to None.
  449. cond (_type_, optional): placeholder for future use. Defaults to None.
  450. Raises:
  451. ValueError: _description_
  452. ValueError: _description_
  453. Returns:
  454. _type_: _description_
  455. """
  456. t = self.time_embeddings(t).to(t.dtype)
  457. t = self.time_mlp(t)
  458. x = pack([x, mu], "b * t")[0]
  459. if spks is not None:
  460. spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
  461. x = pack([x, spks], "b * t")[0]
  462. if cond is not None:
  463. x = pack([x, cond], "b * t")[0]
  464. hiddens = []
  465. masks = [mask]
  466. for resnet, transformer_blocks, downsample in self.down_blocks:
  467. mask_down = masks[-1]
  468. x = resnet(x, mask_down, t)
  469. x = rearrange(x, "b c t -> b t c").contiguous()
  470. attn_mask = (torch.matmul(mask_down.transpose(1, 2).contiguous(), mask_down) == 1)
  471. attn_mask = mask_to_bias(attn_mask, x.dtype)
  472. for transformer_block in transformer_blocks:
  473. x = transformer_block(
  474. hidden_states=x,
  475. attention_mask=attn_mask,
  476. timestep=t,
  477. )
  478. x = rearrange(x, "b t c -> b c t").contiguous()
  479. hiddens.append(x) # Save hidden states for skip connections
  480. x = downsample(x * mask_down)
  481. masks.append(mask_down[:, :, ::2])
  482. masks = masks[:-1]
  483. mask_mid = masks[-1]
  484. for resnet, transformer_blocks in self.mid_blocks:
  485. x = resnet(x, mask_mid, t)
  486. x = rearrange(x, "b c t -> b t c").contiguous()
  487. attn_mask = (torch.matmul(mask_mid.transpose(1, 2).contiguous(), mask_mid) == 1)
  488. attn_mask = mask_to_bias(attn_mask, x.dtype)
  489. for transformer_block in transformer_blocks:
  490. x = transformer_block(
  491. hidden_states=x,
  492. attention_mask=attn_mask,
  493. timestep=t,
  494. )
  495. x = rearrange(x, "b t c -> b c t").contiguous()
  496. for resnet, transformer_blocks, upsample in self.up_blocks:
  497. mask_up = masks.pop()
  498. skip = hiddens.pop()
  499. x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
  500. x = resnet(x, mask_up, t)
  501. x = rearrange(x, "b c t -> b t c").contiguous()
  502. attn_mask = (torch.matmul(mask_up.transpose(1, 2).contiguous(), mask_up) == 1)
  503. attn_mask = mask_to_bias(attn_mask, x.dtype)
  504. for transformer_block in transformer_blocks:
  505. x = transformer_block(
  506. hidden_states=x,
  507. attention_mask=attn_mask,
  508. timestep=t,
  509. )
  510. x = rearrange(x, "b t c -> b c t").contiguous()
  511. x = upsample(x * mask_up)
  512. x = self.final_block(x, mask_up)
  513. output = self.final_proj(x * mask_up)
  514. return output * mask
  515. class CausalConditionalDecoder(ConditionalDecoder):
  516. def __init__(
  517. self,
  518. in_channels,
  519. out_channels,
  520. channels=(256, 256),
  521. dropout=0.05,
  522. attention_head_dim=64,
  523. n_blocks=1,
  524. num_mid_blocks=2,
  525. num_heads=4,
  526. act_fn="snake",
  527. static_chunk_size=50,
  528. num_decoding_left_chunks=2,
  529. ):
  530. """
  531. This decoder requires an input with the same shape of the target. So, if your text content
  532. is shorter or longer than the outputs, please re-sampling it before feeding to the decoder.
  533. """
  534. torch.nn.Module.__init__(self)
  535. channels = tuple(channels)
  536. self.in_channels = in_channels
  537. self.out_channels = out_channels
  538. self.time_embeddings = SinusoidalPosEmb(in_channels)
  539. time_embed_dim = channels[0] * 4
  540. self.time_mlp = TimestepEmbedding(
  541. in_channels=in_channels,
  542. time_embed_dim=time_embed_dim,
  543. act_fn="silu",
  544. )
  545. self.static_chunk_size = static_chunk_size
  546. self.num_decoding_left_chunks = num_decoding_left_chunks
  547. self.down_blocks = nn.ModuleList([])
  548. self.mid_blocks = nn.ModuleList([])
  549. self.up_blocks = nn.ModuleList([])
  550. output_channel = in_channels
  551. for i in range(len(channels)): # pylint: disable=consider-using-enumerate
  552. input_channel = output_channel
  553. output_channel = channels[i]
  554. is_last = i == len(channels) - 1
  555. resnet = CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
  556. transformer_blocks = nn.ModuleList(
  557. [
  558. CausalBasicTransformerBlock(
  559. dim=output_channel,
  560. num_attention_heads=num_heads,
  561. attention_head_dim=attention_head_dim,
  562. dropout=dropout,
  563. activation_fn=act_fn,
  564. )
  565. for _ in range(n_blocks)
  566. ]
  567. )
  568. downsample = (
  569. Downsample1D(output_channel) if not is_last else CausalConv1d(output_channel, output_channel, 3)
  570. )
  571. self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
  572. for _ in range(num_mid_blocks):
  573. input_channel = channels[-1]
  574. out_channels = channels[-1]
  575. resnet = CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
  576. transformer_blocks = nn.ModuleList(
  577. [
  578. CausalBasicTransformerBlock(
  579. dim=output_channel,
  580. num_attention_heads=num_heads,
  581. attention_head_dim=attention_head_dim,
  582. dropout=dropout,
  583. activation_fn=act_fn,
  584. )
  585. for _ in range(n_blocks)
  586. ]
  587. )
  588. self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
  589. channels = channels[::-1] + (channels[0],)
  590. for i in range(len(channels) - 1):
  591. input_channel = channels[i] * 2
  592. output_channel = channels[i + 1]
  593. is_last = i == len(channels) - 2
  594. resnet = CausalResnetBlock1D(
  595. dim=input_channel,
  596. dim_out=output_channel,
  597. time_emb_dim=time_embed_dim,
  598. )
  599. transformer_blocks = nn.ModuleList(
  600. [
  601. CausalBasicTransformerBlock(
  602. dim=output_channel,
  603. num_attention_heads=num_heads,
  604. attention_head_dim=attention_head_dim,
  605. dropout=dropout,
  606. activation_fn=act_fn,
  607. )
  608. for _ in range(n_blocks)
  609. ]
  610. )
  611. upsample = (
  612. Upsample1D(output_channel, use_conv_transpose=True)
  613. if not is_last
  614. else CausalConv1d(output_channel, output_channel, 3)
  615. )
  616. self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
  617. self.final_block = CausalBlock1D(channels[-1], channels[-1])
  618. self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
  619. self.initialize_weights()
  620. def forward(self, x, mask, mu, t, spks=None, cond=None):
  621. """Forward pass of the UNet1DConditional model.
  622. Args:
  623. x (torch.Tensor): shape (batch_size, in_channels, time)
  624. mask (_type_): shape (batch_size, 1, time)
  625. t (_type_): shape (batch_size)
  626. spks (_type_, optional): shape: (batch_size, condition_channels). Defaults to None.
  627. cond (_type_, optional): placeholder for future use. Defaults to None.
  628. Raises:
  629. ValueError: _description_
  630. ValueError: _description_
  631. Returns:
  632. _type_: _description_
  633. """
  634. t = self.time_embeddings(t).to(t.dtype)
  635. t = self.time_mlp(t)
  636. x = pack([x, mu], "b * t")[0]
  637. if spks is not None:
  638. spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
  639. x = pack([x, spks], "b * t")[0]
  640. if cond is not None:
  641. x = pack([x, cond], "b * t")[0]
  642. hiddens = []
  643. masks = [mask]
  644. for resnet, transformer_blocks, downsample in self.down_blocks:
  645. mask_down = masks[-1]
  646. x, _, _ = resnet(x, mask_down, t)
  647. x = rearrange(x, "b c t -> b t c").contiguous()
  648. attn_mask = add_optional_chunk_mask(x, mask_down.bool(), False, False, 0, self.static_chunk_size, self.num_decoding_left_chunks)
  649. attn_mask = mask_to_bias(attn_mask, x.dtype)
  650. for transformer_block in transformer_blocks:
  651. x, _ = transformer_block(
  652. hidden_states=x,
  653. attention_mask=attn_mask,
  654. timestep=t,
  655. )
  656. x = rearrange(x, "b t c -> b c t").contiguous()
  657. hiddens.append(x) # Save hidden states for skip connections
  658. x, _ = downsample(x * mask_down)
  659. masks.append(mask_down[:, :, ::2])
  660. masks = masks[:-1]
  661. mask_mid = masks[-1]
  662. for resnet, transformer_blocks in self.mid_blocks:
  663. x, _, _ = resnet(x, mask_mid, t)
  664. x = rearrange(x, "b c t -> b t c").contiguous()
  665. attn_mask = add_optional_chunk_mask(x, mask_mid.bool(), False, False, 0, self.static_chunk_size, self.num_decoding_left_chunks)
  666. attn_mask = mask_to_bias(attn_mask, x.dtype)
  667. for transformer_block in transformer_blocks:
  668. x, _ = transformer_block(
  669. hidden_states=x,
  670. attention_mask=attn_mask,
  671. timestep=t,
  672. )
  673. x = rearrange(x, "b t c -> b c t").contiguous()
  674. for resnet, transformer_blocks, upsample in self.up_blocks:
  675. mask_up = masks.pop()
  676. skip = hiddens.pop()
  677. x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
  678. x, _, _ = resnet(x, mask_up, t)
  679. x = rearrange(x, "b c t -> b t c").contiguous()
  680. attn_mask = add_optional_chunk_mask(x, mask_up.bool(), False, False, 0, self.static_chunk_size, self.num_decoding_left_chunks)
  681. attn_mask = mask_to_bias(attn_mask, x.dtype)
  682. for transformer_block in transformer_blocks:
  683. x, _ = transformer_block(
  684. hidden_states=x,
  685. attention_mask=attn_mask,
  686. timestep=t,
  687. )
  688. x = rearrange(x, "b t c -> b c t").contiguous()
  689. x, _ = upsample(x * mask_up)
  690. x, _ = self.final_block(x, mask_up)
  691. output = self.final_proj(x * mask_up)
  692. return output * mask
  693. def forward_chunk(self, x, mask, mu, t, spks=None, cond=None,
  694. down_blocks_conv_cache: torch.Tensor = torch.zeros(0, 0, 0, 0),
  695. down_blocks_kv_cache: torch.Tensor = torch.zeros(0, 0, 0, 0, 0, 0),
  696. mid_blocks_conv_cache: torch.Tensor = torch.zeros(0, 0, 0, 0),
  697. mid_blocks_kv_cache: torch.Tensor = torch.zeros(0, 0, 0, 0, 0, 0),
  698. up_blocks_conv_cache: torch.Tensor = torch.zeros(0, 0, 0, 0),
  699. up_blocks_kv_cache: torch.Tensor = torch.zeros(0, 0, 0, 0, 0, 0),
  700. final_blocks_conv_cache: torch.Tensor = torch.zeros(0, 0, 0)
  701. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
  702. """Forward pass of the UNet1DConditional model.
  703. Args:
  704. x (torch.Tensor): shape (batch_size, in_channels, time)
  705. mask (_type_): shape (batch_size, 1, time)
  706. t (_type_): shape (batch_size)
  707. spks (_type_, optional): shape: (batch_size, condition_channels). Defaults to None.
  708. cond (_type_, optional): placeholder for future use. Defaults to None.
  709. Raises:
  710. ValueError: _description_
  711. ValueError: _description_
  712. Returns:
  713. _type_: _description_
  714. """
  715. t = self.time_embeddings(t).to(t.dtype)
  716. t = self.time_mlp(t)
  717. x = pack([x, mu], "b * t")[0]
  718. if spks is not None:
  719. spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
  720. x = pack([x, spks], "b * t")[0]
  721. if cond is not None:
  722. x = pack([x, cond], "b * t")[0]
  723. hiddens = []
  724. masks = [mask]
  725. down_blocks_kv_cache_new = torch.zeros(1, 4, 2, x.size(2), 512, 2).to(x.device)
  726. mid_blocks_kv_cache_new = torch.zeros(12, 4, 2, x.size(2), 512, 2).to(x.device)
  727. up_blocks_kv_cache_new = torch.zeros(1, 4, 2, x.size(2), 512, 2).to(x.device)
  728. for index, (resnet, transformer_blocks, downsample) in enumerate(self.down_blocks):
  729. mask_down = masks[-1]
  730. x, down_blocks_conv_cache[index][:, :320], down_blocks_conv_cache[index][:, 320: 576] = resnet(x, mask_down, t, down_blocks_conv_cache[index][:, :320], down_blocks_conv_cache[index][:, 320: 576])
  731. x = rearrange(x, "b c t -> b t c").contiguous()
  732. attn_mask = torch.ones(x.size(0), x.size(1), x.size(1) + down_blocks_kv_cache.size(3), device=x.device).bool()
  733. attn_mask = mask_to_bias(attn_mask, x.dtype)
  734. for i, transformer_block in enumerate(transformer_blocks):
  735. x, down_blocks_kv_cache_new[index, i] = transformer_block(
  736. hidden_states=x,
  737. attention_mask=attn_mask,
  738. timestep=t,
  739. cache=down_blocks_kv_cache[index, i],
  740. )
  741. x = rearrange(x, "b t c -> b c t").contiguous()
  742. hiddens.append(x) # Save hidden states for skip connections
  743. x, down_blocks_conv_cache[index][:, 576:] = downsample(x * mask_down, down_blocks_conv_cache[index][:, 576:])
  744. masks.append(mask_down[:, :, ::2])
  745. masks = masks[:-1]
  746. mask_mid = masks[-1]
  747. for index, (resnet, transformer_blocks) in enumerate(self.mid_blocks):
  748. x, mid_blocks_conv_cache[index][:, :256], mid_blocks_conv_cache[index][:, 256:] = resnet(x, mask_mid, t, mid_blocks_conv_cache[index][:, :256], mid_blocks_conv_cache[index][:, 256:])
  749. x = rearrange(x, "b c t -> b t c").contiguous()
  750. attn_mask = torch.ones(x.size(0), x.size(1), x.size(1) + mid_blocks_kv_cache.size(3), device=x.device).bool()
  751. attn_mask = mask_to_bias(attn_mask, x.dtype)
  752. for i, transformer_block in enumerate(transformer_blocks):
  753. x, mid_blocks_kv_cache_new[index, i] = transformer_block(
  754. hidden_states=x,
  755. attention_mask=attn_mask,
  756. timestep=t,
  757. cache=mid_blocks_kv_cache[index, i]
  758. )
  759. x = rearrange(x, "b t c -> b c t").contiguous()
  760. for index, (resnet, transformer_blocks, upsample) in enumerate(self.up_blocks):
  761. mask_up = masks.pop()
  762. skip = hiddens.pop()
  763. x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
  764. x, up_blocks_conv_cache[index][:, :512], up_blocks_conv_cache[index][:, 512: 768] = resnet(x, mask_up, t, up_blocks_conv_cache[index][:, :512], up_blocks_conv_cache[index][:, 512: 768])
  765. x = rearrange(x, "b c t -> b t c").contiguous()
  766. attn_mask = torch.ones(x.size(0), x.size(1), x.size(1) + up_blocks_kv_cache.size(3), device=x.device).bool()
  767. attn_mask = mask_to_bias(attn_mask, x.dtype)
  768. for i, transformer_block in enumerate(transformer_blocks):
  769. x, up_blocks_kv_cache_new[index, i] = transformer_block(
  770. hidden_states=x,
  771. attention_mask=attn_mask,
  772. timestep=t,
  773. cache=up_blocks_kv_cache[index, i]
  774. )
  775. x = rearrange(x, "b t c -> b c t").contiguous()
  776. x, up_blocks_conv_cache[index][:, 768:] = upsample(x * mask_up, up_blocks_conv_cache[index][:, 768:])
  777. x, final_blocks_conv_cache = self.final_block(x, mask_up, final_blocks_conv_cache)
  778. output = self.final_proj(x * mask_up)
  779. return output * mask, down_blocks_conv_cache, down_blocks_kv_cache_new, mid_blocks_conv_cache, mid_blocks_kv_cache_new, up_blocks_conv_cache, up_blocks_kv_cache_new, final_blocks_conv_cache