motion_module.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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=(
  76. "Temporal_Self",
  77. "Temporal_Self",
  78. ),
  79. dropout=0.0,
  80. norm_num_groups=32,
  81. cross_attention_dim=768,
  82. activation_fn="geglu",
  83. attention_bias=False,
  84. upcast_attention=False,
  85. cross_frame_attention_mode=None,
  86. temporal_position_encoding=False,
  87. temporal_position_encoding_max_len=24,
  88. ):
  89. super().__init__()
  90. inner_dim = num_attention_heads * attention_head_dim
  91. self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
  92. self.proj_in = nn.Linear(in_channels, inner_dim)
  93. self.transformer_blocks = nn.ModuleList(
  94. [
  95. TemporalTransformerBlock(
  96. dim=inner_dim,
  97. num_attention_heads=num_attention_heads,
  98. attention_head_dim=attention_head_dim,
  99. attention_block_types=attention_block_types,
  100. dropout=dropout,
  101. norm_num_groups=norm_num_groups,
  102. cross_attention_dim=cross_attention_dim,
  103. activation_fn=activation_fn,
  104. attention_bias=attention_bias,
  105. upcast_attention=upcast_attention,
  106. cross_frame_attention_mode=cross_frame_attention_mode,
  107. temporal_position_encoding=temporal_position_encoding,
  108. temporal_position_encoding_max_len=temporal_position_encoding_max_len,
  109. )
  110. for d in range(num_layers)
  111. ]
  112. )
  113. self.proj_out = nn.Linear(inner_dim, in_channels)
  114. def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None):
  115. assert hidden_states.dim() == 5, f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
  116. video_length = hidden_states.shape[2]
  117. hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
  118. batch, channel, height, weight = hidden_states.shape
  119. residual = hidden_states
  120. hidden_states = self.norm(hidden_states)
  121. inner_dim = hidden_states.shape[1]
  122. hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
  123. hidden_states = self.proj_in(hidden_states)
  124. # Transformer Blocks
  125. for block in self.transformer_blocks:
  126. hidden_states = block(hidden_states, encoder_hidden_states=encoder_hidden_states, video_length=video_length)
  127. # output
  128. hidden_states = self.proj_out(hidden_states)
  129. hidden_states = hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
  130. output = hidden_states + residual
  131. output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length)
  132. return output
  133. class TemporalTransformerBlock(nn.Module):
  134. def __init__(
  135. self,
  136. dim,
  137. num_attention_heads,
  138. attention_head_dim,
  139. attention_block_types = ( "Temporal_Self", "Temporal_Self", ),
  140. dropout = 0.0,
  141. norm_num_groups = 32,
  142. cross_attention_dim = 768,
  143. activation_fn = "geglu",
  144. attention_bias = False,
  145. upcast_attention = False,
  146. cross_frame_attention_mode = None,
  147. temporal_position_encoding = False,
  148. temporal_position_encoding_max_len = 24,
  149. ):
  150. super().__init__()
  151. attention_blocks = []
  152. norms = []
  153. for block_name in attention_block_types:
  154. attention_blocks.append(
  155. VersatileAttention(
  156. attention_mode=block_name.split("_")[0],
  157. cross_attention_dim=cross_attention_dim if block_name.endswith("_Cross") else None,
  158. query_dim=dim,
  159. heads=num_attention_heads,
  160. dim_head=attention_head_dim,
  161. dropout=dropout,
  162. bias=attention_bias,
  163. upcast_attention=upcast_attention,
  164. cross_frame_attention_mode=cross_frame_attention_mode,
  165. temporal_position_encoding=temporal_position_encoding,
  166. temporal_position_encoding_max_len=temporal_position_encoding_max_len,
  167. )
  168. )
  169. norms.append(nn.LayerNorm(dim))
  170. self.attention_blocks = nn.ModuleList(attention_blocks)
  171. self.norms = nn.ModuleList(norms)
  172. self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
  173. self.ff_norm = nn.LayerNorm(dim)
  174. def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None):
  175. for attention_block, norm in zip(self.attention_blocks, self.norms):
  176. norm_hidden_states = norm(hidden_states)
  177. hidden_states = attention_block(
  178. norm_hidden_states,
  179. encoder_hidden_states=encoder_hidden_states if attention_block.is_cross_attention else None,
  180. video_length=video_length,
  181. ) + hidden_states
  182. hidden_states = self.ff(self.ff_norm(hidden_states)) + hidden_states
  183. output = hidden_states
  184. return output
  185. class PositionalEncoding(nn.Module):
  186. def __init__(self, d_model: int, dropout: float = 0., max_len: int = 24):
  187. super().__init__()
  188. self.dropout = nn.Dropout(p=dropout)
  189. # print(f"d_model: {d_model}")
  190. position = torch.arange(max_len).unsqueeze(1)
  191. div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
  192. pe = torch.zeros(1, max_len, d_model)
  193. pe[0, :, 0::2] = torch.sin(position * div_term)
  194. pe[0, :, 1::2] = torch.cos(position * div_term)
  195. self.register_buffer('pe', pe)
  196. def forward(self, x):
  197. x = x + self.pe[:, :x.size(1)]
  198. return self.dropout(x)
  199. class VersatileAttention(CrossAttention):
  200. def __init__(
  201. self,
  202. attention_mode=None,
  203. cross_frame_attention_mode=None,
  204. temporal_position_encoding=False,
  205. temporal_position_encoding_max_len=24,
  206. *args, **kwargs
  207. ):
  208. super().__init__(*args, **kwargs)
  209. assert attention_mode == "Temporal"
  210. self.attention_mode = attention_mode
  211. self.is_cross_attention = kwargs["cross_attention_dim"] is not None
  212. self.pos_encoder = PositionalEncoding(
  213. kwargs["query_dim"],
  214. dropout=0.,
  215. max_len=temporal_position_encoding_max_len
  216. ) if (temporal_position_encoding and attention_mode == "Temporal") else None
  217. def extra_repr(self):
  218. return f"(Module Info) Attention_Mode: {self.attention_mode}, Is_Cross_Attention: {self.is_cross_attention}"
  219. def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None):
  220. batch_size, sequence_length, _ = hidden_states.shape
  221. if self.attention_mode == "Temporal":
  222. d = hidden_states.shape[1]
  223. hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) f c", f=video_length)
  224. if self.pos_encoder is not None:
  225. hidden_states = self.pos_encoder(hidden_states)
  226. 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
  227. else:
  228. raise NotImplementedError
  229. encoder_hidden_states = encoder_hidden_states
  230. if self.group_norm is not None:
  231. hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
  232. query = self.to_q(hidden_states)
  233. dim = query.shape[-1]
  234. query = self.reshape_heads_to_batch_dim(query)
  235. if self.added_kv_proj_dim is not None:
  236. raise NotImplementedError
  237. encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
  238. key = self.to_k(encoder_hidden_states)
  239. value = self.to_v(encoder_hidden_states)
  240. key = self.reshape_heads_to_batch_dim(key)
  241. value = self.reshape_heads_to_batch_dim(value)
  242. if attention_mask is not None:
  243. if attention_mask.shape[-1] != query.shape[1]:
  244. target_length = query.shape[1]
  245. attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
  246. attention_mask = attention_mask.repeat_interleave(self.heads, dim=0)
  247. # attention, what we cannot get enough of
  248. if self._use_memory_efficient_attention_xformers:
  249. hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
  250. # Some versions of xformers return output in fp32, cast it back to the dtype of the input
  251. hidden_states = hidden_states.to(query.dtype)
  252. else:
  253. if self._slice_size is None or query.shape[0] // self._slice_size == 1:
  254. hidden_states = self._attention(query, key, value, attention_mask)
  255. else:
  256. hidden_states = self._sliced_attention(query, key, value, sequence_length, dim, attention_mask)
  257. # linear proj
  258. hidden_states = self.to_out[0](hidden_states)
  259. # dropout
  260. hidden_states = self.to_out[1](hidden_states)
  261. if self.attention_mode == "Temporal":
  262. hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
  263. return hidden_states