resnet.py 6.8 KB

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