resnet.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from einops import rearrange
  6. class InflatedConv3d(nn.Conv2d):
  7. def forward(self, x):
  8. video_length = x.shape[2]
  9. x = rearrange(x, "b c f h w -> (b f) c h w")
  10. x = super().forward(x)
  11. x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
  12. return x
  13. class InflatedGroupNorm(nn.GroupNorm):
  14. def forward(self, x):
  15. video_length = x.shape[2]
  16. x = rearrange(x, "b c f h w -> (b f) c h w")
  17. x = super().forward(x)
  18. x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
  19. return x
  20. class Upsample3D(nn.Module):
  21. def __init__(self, channels, use_conv=False, use_conv_transpose=False, out_channels=None, name="conv"):
  22. super().__init__()
  23. self.channels = channels
  24. self.out_channels = out_channels or channels
  25. self.use_conv = use_conv
  26. self.use_conv_transpose = use_conv_transpose
  27. self.name = name
  28. conv = None
  29. if use_conv_transpose:
  30. raise NotImplementedError
  31. elif use_conv:
  32. self.conv = InflatedConv3d(self.channels, self.out_channels, 3, padding=1)
  33. def forward(self, hidden_states, output_size=None):
  34. assert hidden_states.shape[1] == self.channels
  35. if self.use_conv_transpose:
  36. raise NotImplementedError
  37. # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
  38. dtype = hidden_states.dtype
  39. if dtype == torch.bfloat16:
  40. hidden_states = hidden_states.to(torch.float32)
  41. # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
  42. if hidden_states.shape[0] >= 64:
  43. hidden_states = hidden_states.contiguous()
  44. # if `output_size` is passed we force the interpolation output
  45. # size and do not make use of `scale_factor=2`
  46. if output_size is None:
  47. hidden_states = F.interpolate(hidden_states, scale_factor=[1.0, 2.0, 2.0], mode="nearest")
  48. else:
  49. hidden_states = F.interpolate(hidden_states, size=output_size, mode="nearest")
  50. # If the input is bfloat16, we cast back to bfloat16
  51. if dtype == torch.bfloat16:
  52. hidden_states = hidden_states.to(dtype)
  53. # if self.use_conv:
  54. # if self.name == "conv":
  55. # hidden_states = self.conv(hidden_states)
  56. # else:
  57. # hidden_states = self.Conv2d_0(hidden_states)
  58. hidden_states = self.conv(hidden_states)
  59. return hidden_states
  60. class Downsample3D(nn.Module):
  61. def __init__(self, channels, use_conv=False, out_channels=None, padding=1, name="conv"):
  62. super().__init__()
  63. self.channels = channels
  64. self.out_channels = out_channels or channels
  65. self.use_conv = use_conv
  66. self.padding = padding
  67. stride = 2
  68. self.name = name
  69. if use_conv:
  70. self.conv = InflatedConv3d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
  71. else:
  72. raise NotImplementedError
  73. def forward(self, hidden_states):
  74. assert hidden_states.shape[1] == self.channels
  75. if self.use_conv and self.padding == 0:
  76. raise NotImplementedError
  77. assert hidden_states.shape[1] == self.channels
  78. hidden_states = self.conv(hidden_states)
  79. return hidden_states
  80. class ResnetBlock3D(nn.Module):
  81. def __init__(
  82. self,
  83. *,
  84. in_channels,
  85. out_channels=None,
  86. conv_shortcut=False,
  87. dropout=0.0,
  88. temb_channels=512,
  89. groups=32,
  90. groups_out=None,
  91. pre_norm=True,
  92. eps=1e-6,
  93. non_linearity="swish",
  94. time_embedding_norm="default",
  95. output_scale_factor=1.0,
  96. use_in_shortcut=None,
  97. use_inflated_groupnorm=None,
  98. ):
  99. super().__init__()
  100. self.pre_norm = pre_norm
  101. self.pre_norm = True
  102. self.in_channels = in_channels
  103. out_channels = in_channels if out_channels is None else out_channels
  104. self.out_channels = out_channels
  105. self.use_conv_shortcut = conv_shortcut
  106. self.time_embedding_norm = time_embedding_norm
  107. self.output_scale_factor = output_scale_factor
  108. if groups_out is None:
  109. groups_out = groups
  110. assert use_inflated_groupnorm != None
  111. if use_inflated_groupnorm:
  112. self.norm1 = InflatedGroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
  113. else:
  114. self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
  115. self.conv1 = InflatedConv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
  116. if temb_channels is not None:
  117. if self.time_embedding_norm == "default":
  118. time_emb_proj_out_channels = out_channels
  119. elif self.time_embedding_norm == "scale_shift":
  120. time_emb_proj_out_channels = out_channels * 2
  121. else:
  122. raise ValueError(f"unknown time_embedding_norm : {self.time_embedding_norm} ")
  123. self.time_emb_proj = torch.nn.Linear(temb_channels, time_emb_proj_out_channels)
  124. else:
  125. self.time_emb_proj = None
  126. if use_inflated_groupnorm:
  127. self.norm2 = InflatedGroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
  128. else:
  129. self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
  130. self.dropout = torch.nn.Dropout(dropout)
  131. self.conv2 = InflatedConv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
  132. if non_linearity == "swish":
  133. self.nonlinearity = lambda x: F.silu(x)
  134. elif non_linearity == "mish":
  135. self.nonlinearity = Mish()
  136. elif non_linearity == "silu":
  137. self.nonlinearity = nn.SiLU()
  138. self.use_in_shortcut = self.in_channels != self.out_channels if use_in_shortcut is None else use_in_shortcut
  139. self.conv_shortcut = None
  140. if self.use_in_shortcut:
  141. self.conv_shortcut = InflatedConv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
  142. def forward(self, input_tensor, temb):
  143. hidden_states = input_tensor
  144. hidden_states = self.norm1(hidden_states)
  145. hidden_states = self.nonlinearity(hidden_states)
  146. hidden_states = self.conv1(hidden_states)
  147. if temb is not None:
  148. temb = self.time_emb_proj(self.nonlinearity(temb))[:, :, None, None, None]
  149. if temb is not None and self.time_embedding_norm == "default":
  150. hidden_states = hidden_states + temb
  151. hidden_states = self.norm2(hidden_states)
  152. if temb is not None and self.time_embedding_norm == "scale_shift":
  153. scale, shift = torch.chunk(temb, 2, dim=1)
  154. hidden_states = hidden_states * (1 + scale) + shift
  155. hidden_states = self.nonlinearity(hidden_states)
  156. hidden_states = self.dropout(hidden_states)
  157. hidden_states = self.conv2(hidden_states)
  158. if self.conv_shortcut is not None:
  159. input_tensor = self.conv_shortcut(input_tensor)
  160. output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
  161. return output_tensor
  162. class Mish(torch.nn.Module):
  163. def forward(self, hidden_states):
  164. return hidden_states * torch.tanh(torch.nn.functional.softplus(hidden_states))