motion_module.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. from dataclasses import dataclass
  2. from typing import List, Optional, Tuple, Union
  3. import torch
  4. import numpy as np
  5. import torch.nn.functional as F
  6. from torch import nn
  7. import torchvision
  8. from diffusers.configuration_utils import ConfigMixin, register_to_config
  9. from diffusers.modeling_utils import ModelMixin
  10. from diffusers.utils import BaseOutput
  11. from diffusers.utils.import_utils import is_xformers_available
  12. from diffusers.models.attention import CrossAttention, FeedForward
  13. from einops import rearrange, repeat
  14. import math
  15. def zero_module(module):
  16. # Zero out the parameters of a module and return it.
  17. for p in module.parameters():
  18. p.detach().zero_()
  19. return module
  20. @dataclass
  21. class TemporalTransformer3DModelOutput(BaseOutput):
  22. sample: torch.FloatTensor
  23. if is_xformers_available():
  24. import xformers
  25. import xformers.ops
  26. else:
  27. xformers = None
  28. def get_motion_module(
  29. in_channels,
  30. motion_module_type: str,
  31. motion_module_kwargs: dict
  32. ):
  33. if motion_module_type == "Vanilla":
  34. return VanillaTemporalModule(in_channels=in_channels, **motion_module_kwargs,)
  35. else:
  36. raise ValueError
  37. class VanillaTemporalModule(nn.Module):
  38. def __init__(
  39. self,
  40. in_channels,
  41. num_attention_heads = 8,
  42. num_transformer_block = 2,
  43. attention_block_types =( "Temporal_Self", "Temporal_Self" ),
  44. cross_frame_attention_mode = None,
  45. temporal_position_encoding = False,
  46. temporal_position_encoding_max_len = 24,
  47. temporal_attention_dim_div = 1,
  48. zero_initialize = True,
  49. ):
  50. super().__init__()
  51. self.temporal_transformer = TemporalTransformer3DModel(
  52. in_channels=in_channels,
  53. num_attention_heads=num_attention_heads,
  54. attention_head_dim=in_channels // num_attention_heads // temporal_attention_dim_div,
  55. num_layers=num_transformer_block,
  56. attention_block_types=attention_block_types,
  57. cross_frame_attention_mode=cross_frame_attention_mode,
  58. temporal_position_encoding=temporal_position_encoding,
  59. temporal_position_encoding_max_len=temporal_position_encoding_max_len,
  60. )
  61. if zero_initialize:
  62. self.temporal_transformer.proj_out = zero_module(self.temporal_transformer.proj_out)
  63. def forward(self, input_tensor, temb, encoder_hidden_states, attention_mask=None, anchor_frame_idx=None):
  64. hidden_states = input_tensor
  65. hidden_states = self.temporal_transformer(hidden_states, encoder_hidden_states, attention_mask)
  66. output = hidden_states
  67. return output
  68. class TemporalTransformer3DModel(nn.Module):
  69. def __init__(
  70. self,
  71. in_channels,
  72. num_attention_heads,
  73. attention_head_dim,
  74. num_layers,
  75. attention_block_types = ( "Temporal_Self", "Temporal_Self", ),
  76. dropout = 0.0,
  77. norm_num_groups = 32,
  78. cross_attention_dim = 768,
  79. activation_fn = "geglu",
  80. attention_bias = False,
  81. upcast_attention = False,
  82. cross_frame_attention_mode = None,
  83. temporal_position_encoding = False,
  84. temporal_position_encoding_max_len = 24,
  85. ):
  86. super().__init__()
  87. inner_dim = num_attention_heads * attention_head_dim
  88. self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
  89. self.proj_in = nn.Linear(in_channels, inner_dim)
  90. self.transformer_blocks = nn.ModuleList(
  91. [
  92. TemporalTransformerBlock(
  93. dim=inner_dim,
  94. num_attention_heads=num_attention_heads,
  95. attention_head_dim=attention_head_dim,
  96. attention_block_types=attention_block_types,
  97. dropout=dropout,
  98. norm_num_groups=norm_num_groups,
  99. cross_attention_dim=cross_attention_dim,
  100. activation_fn=activation_fn,
  101. attention_bias=attention_bias,
  102. upcast_attention=upcast_attention,
  103. cross_frame_attention_mode=cross_frame_attention_mode,
  104. temporal_position_encoding=temporal_position_encoding,
  105. temporal_position_encoding_max_len=temporal_position_encoding_max_len,
  106. )
  107. for d in range(num_layers)
  108. ]
  109. )
  110. self.proj_out = nn.Linear(inner_dim, in_channels)
  111. def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None):
  112. assert hidden_states.dim() == 5, f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
  113. video_length = hidden_states.shape[2]
  114. hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
  115. batch, channel, height, weight = hidden_states.shape
  116. residual = hidden_states
  117. hidden_states = self.norm(hidden_states)
  118. inner_dim = hidden_states.shape[1]
  119. hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
  120. hidden_states = self.proj_in(hidden_states)
  121. # Transformer Blocks
  122. for block in self.transformer_blocks:
  123. hidden_states = block(hidden_states, encoder_hidden_states=encoder_hidden_states, video_length=video_length)
  124. # output
  125. hidden_states = self.proj_out(hidden_states)
  126. hidden_states = hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
  127. output = hidden_states + residual
  128. output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length)
  129. return output
  130. class TemporalTransformerBlock(nn.Module):
  131. def __init__(
  132. self,
  133. dim,
  134. num_attention_heads,
  135. attention_head_dim,
  136. attention_block_types = ( "Temporal_Self", "Temporal_Self", ),
  137. dropout = 0.0,
  138. norm_num_groups = 32,
  139. cross_attention_dim = 768,
  140. activation_fn = "geglu",
  141. attention_bias = False,
  142. upcast_attention = False,
  143. cross_frame_attention_mode = None,
  144. temporal_position_encoding = False,
  145. temporal_position_encoding_max_len = 24,
  146. ):
  147. super().__init__()
  148. attention_blocks = []
  149. norms = []
  150. for block_name in attention_block_types:
  151. attention_blocks.append(
  152. VersatileAttention(
  153. attention_mode=block_name.split("_")[0],
  154. cross_attention_dim=cross_attention_dim if block_name.endswith("_Cross") else None,
  155. query_dim=dim,
  156. heads=num_attention_heads,
  157. dim_head=attention_head_dim,
  158. dropout=dropout,
  159. bias=attention_bias,
  160. upcast_attention=upcast_attention,
  161. cross_frame_attention_mode=cross_frame_attention_mode,
  162. temporal_position_encoding=temporal_position_encoding,
  163. temporal_position_encoding_max_len=temporal_position_encoding_max_len,
  164. )
  165. )
  166. norms.append(nn.LayerNorm(dim))
  167. self.attention_blocks = nn.ModuleList(attention_blocks)
  168. self.norms = nn.ModuleList(norms)
  169. self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
  170. self.ff_norm = nn.LayerNorm(dim)
  171. def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None):
  172. for attention_block, norm in zip(self.attention_blocks, self.norms):
  173. norm_hidden_states = norm(hidden_states)
  174. hidden_states = attention_block(
  175. norm_hidden_states,
  176. encoder_hidden_states=encoder_hidden_states if attention_block.is_cross_attention else None,
  177. video_length=video_length,
  178. ) + hidden_states
  179. hidden_states = self.ff(self.ff_norm(hidden_states)) + hidden_states
  180. output = hidden_states
  181. return output
  182. class PositionalEncoding(nn.Module):
  183. def __init__(
  184. self,
  185. d_model,
  186. dropout = 0.,
  187. max_len = 24
  188. ):
  189. super().__init__()
  190. self.dropout = nn.Dropout(p=dropout)
  191. position = torch.arange(max_len).unsqueeze(1)
  192. div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
  193. pe = torch.zeros(1, max_len, d_model)
  194. pe[0, :, 0::2] = torch.sin(position * div_term)
  195. pe[0, :, 1::2] = torch.cos(position * div_term)
  196. self.register_buffer('pe', pe)
  197. def forward(self, x):
  198. x = x + self.pe[:, :x.size(1)]
  199. return self.dropout(x)
  200. class VersatileAttention(CrossAttention):
  201. def __init__(
  202. self,
  203. attention_mode = None,
  204. cross_frame_attention_mode = None,
  205. temporal_position_encoding = False,
  206. temporal_position_encoding_max_len = 24,
  207. *args, **kwargs
  208. ):
  209. super().__init__(*args, **kwargs)
  210. assert attention_mode == "Temporal"
  211. self.attention_mode = attention_mode
  212. self.is_cross_attention = kwargs["cross_attention_dim"] is not None
  213. self.pos_encoder = PositionalEncoding(
  214. kwargs["query_dim"],
  215. dropout=0.,
  216. max_len=temporal_position_encoding_max_len
  217. ) if (temporal_position_encoding and attention_mode == "Temporal") else None
  218. def extra_repr(self):
  219. return f"(Module Info) Attention_Mode: {self.attention_mode}, Is_Cross_Attention: {self.is_cross_attention}"
  220. def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None):
  221. batch_size, sequence_length, _ = hidden_states.shape
  222. if self.attention_mode == "Temporal":
  223. d = hidden_states.shape[1]
  224. hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) f c", f=video_length)
  225. if self.pos_encoder is not None:
  226. hidden_states = self.pos_encoder(hidden_states)
  227. encoder_hidden_states = repeat(encoder_hidden_states, "b n c -> (b d) n c", d=d) if encoder_hidden_states is not None else encoder_hidden_states
  228. else:
  229. raise NotImplementedError
  230. encoder_hidden_states = encoder_hidden_states
  231. if self.group_norm is not None:
  232. hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
  233. query = self.to_q(hidden_states)
  234. dim = query.shape[-1]
  235. query = self.reshape_heads_to_batch_dim(query)
  236. if self.added_kv_proj_dim is not None:
  237. raise NotImplementedError
  238. encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
  239. key = self.to_k(encoder_hidden_states)
  240. value = self.to_v(encoder_hidden_states)
  241. key = self.reshape_heads_to_batch_dim(key)
  242. value = self.reshape_heads_to_batch_dim(value)
  243. if attention_mask is not None:
  244. if attention_mask.shape[-1] != query.shape[1]:
  245. target_length = query.shape[1]
  246. attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
  247. attention_mask = attention_mask.repeat_interleave(self.heads, dim=0)
  248. # attention, what we cannot get enough of
  249. if self._use_memory_efficient_attention_xformers:
  250. hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
  251. # Some versions of xformers return output in fp32, cast it back to the dtype of the input
  252. hidden_states = hidden_states.to(query.dtype)
  253. else:
  254. if self._slice_size is None or query.shape[0] // self._slice_size == 1:
  255. hidden_states = self._attention(query, key, value, attention_mask)
  256. else:
  257. hidden_states = self._sliced_attention(query, key, value, sequence_length, dim, attention_mask)
  258. # linear proj
  259. hidden_states = self.to_out[0](hidden_states)
  260. # dropout
  261. hidden_states = self.to_out[1](hidden_states)
  262. if self.attention_mode == "Temporal":
  263. hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
  264. return hidden_states