unet.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py
  2. from dataclasses import dataclass
  3. from typing import List, Optional, Tuple, Union
  4. import os
  5. import json
  6. import pdb
  7. import torch
  8. import torch.nn as nn
  9. import torch.utils.checkpoint
  10. from diffusers.configuration_utils import ConfigMixin, register_to_config
  11. from diffusers.modeling_utils import ModelMixin
  12. from diffusers.utils import BaseOutput, logging
  13. from diffusers.models.embeddings import TimestepEmbedding, Timesteps
  14. from .unet_blocks import (
  15. CrossAttnDownBlock3D,
  16. CrossAttnUpBlock3D,
  17. DownBlock3D,
  18. UNetMidBlock3DCrossAttn,
  19. UpBlock3D,
  20. get_down_block,
  21. get_up_block,
  22. )
  23. from .resnet import InflatedConv3d, InflatedGroupNorm
  24. logger = logging.get_logger(__name__) # pylint: disable=invalid-name
  25. @dataclass
  26. class UNet3DConditionOutput(BaseOutput):
  27. sample: torch.FloatTensor
  28. class UNet3DConditionModel(ModelMixin, ConfigMixin):
  29. _supports_gradient_checkpointing = True
  30. @register_to_config
  31. def __init__(
  32. self,
  33. sample_size: Optional[int] = None,
  34. in_channels: int = 4,
  35. out_channels: int = 4,
  36. center_input_sample: bool = False,
  37. flip_sin_to_cos: bool = True,
  38. freq_shift: int = 0,
  39. down_block_types: Tuple[str] = (
  40. "CrossAttnDownBlock3D",
  41. "CrossAttnDownBlock3D",
  42. "CrossAttnDownBlock3D",
  43. "DownBlock3D",
  44. ),
  45. mid_block_type: str = "UNetMidBlock3DCrossAttn",
  46. up_block_types: Tuple[str] = (
  47. "UpBlock3D",
  48. "CrossAttnUpBlock3D",
  49. "CrossAttnUpBlock3D",
  50. "CrossAttnUpBlock3D"
  51. ),
  52. only_cross_attention: Union[bool, Tuple[bool]] = False,
  53. block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
  54. layers_per_block: int = 2,
  55. downsample_padding: int = 1,
  56. mid_block_scale_factor: float = 1,
  57. act_fn: str = "silu",
  58. norm_num_groups: int = 32,
  59. norm_eps: float = 1e-5,
  60. cross_attention_dim: int = 1280,
  61. attention_head_dim: Union[int, Tuple[int]] = 8,
  62. dual_cross_attention: bool = False,
  63. use_linear_projection: bool = False,
  64. class_embed_type: Optional[str] = None,
  65. num_class_embeds: Optional[int] = None,
  66. upcast_attention: bool = False,
  67. resnet_time_scale_shift: str = "default",
  68. use_inflated_groupnorm=False,
  69. # Additional
  70. use_motion_module = False,
  71. motion_module_resolutions = ( 1,2,4,8 ),
  72. motion_module_mid_block = False,
  73. motion_module_decoder_only = False,
  74. motion_module_type = None,
  75. motion_module_kwargs = {},
  76. unet_use_cross_frame_attention = None,
  77. unet_use_temporal_attention = None,
  78. ):
  79. super().__init__()
  80. self.sample_size = sample_size
  81. time_embed_dim = block_out_channels[0] * 4
  82. # input
  83. self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
  84. # time
  85. self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
  86. timestep_input_dim = block_out_channels[0]
  87. self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
  88. # class embedding
  89. if class_embed_type is None and num_class_embeds is not None:
  90. self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
  91. elif class_embed_type == "timestep":
  92. self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
  93. elif class_embed_type == "identity":
  94. self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
  95. else:
  96. self.class_embedding = None
  97. self.down_blocks = nn.ModuleList([])
  98. self.mid_block = None
  99. self.up_blocks = nn.ModuleList([])
  100. if isinstance(only_cross_attention, bool):
  101. only_cross_attention = [only_cross_attention] * len(down_block_types)
  102. if isinstance(attention_head_dim, int):
  103. attention_head_dim = (attention_head_dim,) * len(down_block_types)
  104. # down
  105. output_channel = block_out_channels[0]
  106. for i, down_block_type in enumerate(down_block_types):
  107. res = 2 ** i
  108. input_channel = output_channel
  109. output_channel = block_out_channels[i]
  110. is_final_block = i == len(block_out_channels) - 1
  111. down_block = get_down_block(
  112. down_block_type,
  113. num_layers=layers_per_block,
  114. in_channels=input_channel,
  115. out_channels=output_channel,
  116. temb_channels=time_embed_dim,
  117. add_downsample=not is_final_block,
  118. resnet_eps=norm_eps,
  119. resnet_act_fn=act_fn,
  120. resnet_groups=norm_num_groups,
  121. cross_attention_dim=cross_attention_dim,
  122. attn_num_head_channels=attention_head_dim[i],
  123. downsample_padding=downsample_padding,
  124. dual_cross_attention=dual_cross_attention,
  125. use_linear_projection=use_linear_projection,
  126. only_cross_attention=only_cross_attention[i],
  127. upcast_attention=upcast_attention,
  128. resnet_time_scale_shift=resnet_time_scale_shift,
  129. unet_use_cross_frame_attention=unet_use_cross_frame_attention,
  130. unet_use_temporal_attention=unet_use_temporal_attention,
  131. use_inflated_groupnorm=use_inflated_groupnorm,
  132. use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only),
  133. motion_module_type=motion_module_type,
  134. motion_module_kwargs=motion_module_kwargs,
  135. )
  136. self.down_blocks.append(down_block)
  137. # mid
  138. if mid_block_type == "UNetMidBlock3DCrossAttn":
  139. self.mid_block = UNetMidBlock3DCrossAttn(
  140. in_channels=block_out_channels[-1],
  141. temb_channels=time_embed_dim,
  142. resnet_eps=norm_eps,
  143. resnet_act_fn=act_fn,
  144. output_scale_factor=mid_block_scale_factor,
  145. resnet_time_scale_shift=resnet_time_scale_shift,
  146. cross_attention_dim=cross_attention_dim,
  147. attn_num_head_channels=attention_head_dim[-1],
  148. resnet_groups=norm_num_groups,
  149. dual_cross_attention=dual_cross_attention,
  150. use_linear_projection=use_linear_projection,
  151. upcast_attention=upcast_attention,
  152. unet_use_cross_frame_attention=unet_use_cross_frame_attention,
  153. unet_use_temporal_attention=unet_use_temporal_attention,
  154. use_inflated_groupnorm=use_inflated_groupnorm,
  155. use_motion_module=use_motion_module and motion_module_mid_block,
  156. motion_module_type=motion_module_type,
  157. motion_module_kwargs=motion_module_kwargs,
  158. )
  159. else:
  160. raise ValueError(f"unknown mid_block_type : {mid_block_type}")
  161. # count how many layers upsample the videos
  162. self.num_upsamplers = 0
  163. # up
  164. reversed_block_out_channels = list(reversed(block_out_channels))
  165. reversed_attention_head_dim = list(reversed(attention_head_dim))
  166. only_cross_attention = list(reversed(only_cross_attention))
  167. output_channel = reversed_block_out_channels[0]
  168. for i, up_block_type in enumerate(up_block_types):
  169. res = 2 ** (3 - i)
  170. is_final_block = i == len(block_out_channels) - 1
  171. prev_output_channel = output_channel
  172. output_channel = reversed_block_out_channels[i]
  173. input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
  174. # add upsample block for all BUT final layer
  175. if not is_final_block:
  176. add_upsample = True
  177. self.num_upsamplers += 1
  178. else:
  179. add_upsample = False
  180. up_block = get_up_block(
  181. up_block_type,
  182. num_layers=layers_per_block + 1,
  183. in_channels=input_channel,
  184. out_channels=output_channel,
  185. prev_output_channel=prev_output_channel,
  186. temb_channels=time_embed_dim,
  187. add_upsample=add_upsample,
  188. resnet_eps=norm_eps,
  189. resnet_act_fn=act_fn,
  190. resnet_groups=norm_num_groups,
  191. cross_attention_dim=cross_attention_dim,
  192. attn_num_head_channels=reversed_attention_head_dim[i],
  193. dual_cross_attention=dual_cross_attention,
  194. use_linear_projection=use_linear_projection,
  195. only_cross_attention=only_cross_attention[i],
  196. upcast_attention=upcast_attention,
  197. resnet_time_scale_shift=resnet_time_scale_shift,
  198. unet_use_cross_frame_attention=unet_use_cross_frame_attention,
  199. unet_use_temporal_attention=unet_use_temporal_attention,
  200. use_inflated_groupnorm=use_inflated_groupnorm,
  201. use_motion_module=use_motion_module and (res in motion_module_resolutions),
  202. motion_module_type=motion_module_type,
  203. motion_module_kwargs=motion_module_kwargs,
  204. )
  205. self.up_blocks.append(up_block)
  206. prev_output_channel = output_channel
  207. # out
  208. if use_inflated_groupnorm:
  209. self.conv_norm_out = InflatedGroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)
  210. else:
  211. self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)
  212. self.conv_act = nn.SiLU()
  213. self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
  214. def set_attention_slice(self, slice_size):
  215. r"""
  216. Enable sliced attention computation.
  217. When this option is enabled, the attention module will split the input tensor in slices, to compute attention
  218. in several steps. This is useful to save some memory in exchange for a small speed decrease.
  219. Args:
  220. slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
  221. When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
  222. `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
  223. provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
  224. must be a multiple of `slice_size`.
  225. """
  226. sliceable_head_dims = []
  227. def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
  228. if hasattr(module, "set_attention_slice"):
  229. sliceable_head_dims.append(module.sliceable_head_dim)
  230. for child in module.children():
  231. fn_recursive_retrieve_slicable_dims(child)
  232. # retrieve number of attention layers
  233. for module in self.children():
  234. fn_recursive_retrieve_slicable_dims(module)
  235. num_slicable_layers = len(sliceable_head_dims)
  236. if slice_size == "auto":
  237. # half the attention head size is usually a good trade-off between
  238. # speed and memory
  239. slice_size = [dim // 2 for dim in sliceable_head_dims]
  240. elif slice_size == "max":
  241. # make smallest slice possible
  242. slice_size = num_slicable_layers * [1]
  243. slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
  244. if len(slice_size) != len(sliceable_head_dims):
  245. raise ValueError(
  246. f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
  247. f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
  248. )
  249. for i in range(len(slice_size)):
  250. size = slice_size[i]
  251. dim = sliceable_head_dims[i]
  252. if size is not None and size > dim:
  253. raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
  254. # Recursively walk through all the children.
  255. # Any children which exposes the set_attention_slice method
  256. # gets the message
  257. def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
  258. if hasattr(module, "set_attention_slice"):
  259. module.set_attention_slice(slice_size.pop())
  260. for child in module.children():
  261. fn_recursive_set_attention_slice(child, slice_size)
  262. reversed_slice_size = list(reversed(slice_size))
  263. for module in self.children():
  264. fn_recursive_set_attention_slice(module, reversed_slice_size)
  265. def _set_gradient_checkpointing(self, module, value=False):
  266. if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
  267. module.gradient_checkpointing = value
  268. def forward(
  269. self,
  270. sample: torch.FloatTensor,
  271. timestep: Union[torch.Tensor, float, int],
  272. encoder_hidden_states: torch.Tensor,
  273. class_labels: Optional[torch.Tensor] = None,
  274. attention_mask: Optional[torch.Tensor] = None,
  275. return_dict: bool = True,
  276. ) -> Union[UNet3DConditionOutput, Tuple]:
  277. r"""
  278. Args:
  279. sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
  280. timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
  281. encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
  282. return_dict (`bool`, *optional*, defaults to `True`):
  283. Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
  284. Returns:
  285. [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
  286. [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
  287. returning a tuple, the first element is the sample tensor.
  288. """
  289. # By default samples have to be AT least a multiple of the overall upsampling factor.
  290. # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
  291. # However, the upsampling interpolation output size can be forced to fit any upsampling size
  292. # on the fly if necessary.
  293. default_overall_up_factor = 2**self.num_upsamplers
  294. # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
  295. forward_upsample_size = False
  296. upsample_size = None
  297. if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
  298. logger.info("Forward upsample size to force interpolation output size.")
  299. forward_upsample_size = True
  300. # prepare attention_mask
  301. if attention_mask is not None:
  302. attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
  303. attention_mask = attention_mask.unsqueeze(1)
  304. # center input if necessary
  305. if self.config.center_input_sample:
  306. sample = 2 * sample - 1.0
  307. # time
  308. timesteps = timestep
  309. if not torch.is_tensor(timesteps):
  310. # This would be a good case for the `match` statement (Python 3.10+)
  311. is_mps = sample.device.type == "mps"
  312. if isinstance(timestep, float):
  313. dtype = torch.float32 if is_mps else torch.float64
  314. else:
  315. dtype = torch.int32 if is_mps else torch.int64
  316. timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
  317. elif len(timesteps.shape) == 0:
  318. timesteps = timesteps[None].to(sample.device)
  319. # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
  320. timesteps = timesteps.expand(sample.shape[0])
  321. t_emb = self.time_proj(timesteps)
  322. # timesteps does not contain any weights and will always return f32 tensors
  323. # but time_embedding might actually be running in fp16. so we need to cast here.
  324. # there might be better ways to encapsulate this.
  325. t_emb = t_emb.to(dtype=self.dtype)
  326. emb = self.time_embedding(t_emb)
  327. if self.class_embedding is not None:
  328. if class_labels is None:
  329. raise ValueError("class_labels should be provided when num_class_embeds > 0")
  330. if self.config.class_embed_type == "timestep":
  331. class_labels = self.time_proj(class_labels)
  332. class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
  333. emb = emb + class_emb
  334. # pre-process
  335. sample = self.conv_in(sample)
  336. # down
  337. down_block_res_samples = (sample,)
  338. for downsample_block in self.down_blocks:
  339. if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
  340. sample, res_samples = downsample_block(
  341. hidden_states=sample,
  342. temb=emb,
  343. encoder_hidden_states=encoder_hidden_states,
  344. attention_mask=attention_mask,
  345. )
  346. else:
  347. sample, res_samples = downsample_block(hidden_states=sample, temb=emb, encoder_hidden_states=encoder_hidden_states)
  348. down_block_res_samples += res_samples
  349. # mid
  350. sample = self.mid_block(
  351. sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
  352. )
  353. # up
  354. for i, upsample_block in enumerate(self.up_blocks):
  355. is_final_block = i == len(self.up_blocks) - 1
  356. res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
  357. down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
  358. # if we have not reached the final block and need to forward the
  359. # upsample size, we do it here
  360. if not is_final_block and forward_upsample_size:
  361. upsample_size = down_block_res_samples[-1].shape[2:]
  362. if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
  363. sample = upsample_block(
  364. hidden_states=sample,
  365. temb=emb,
  366. res_hidden_states_tuple=res_samples,
  367. encoder_hidden_states=encoder_hidden_states,
  368. upsample_size=upsample_size,
  369. attention_mask=attention_mask,
  370. )
  371. else:
  372. sample = upsample_block(
  373. hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size, encoder_hidden_states=encoder_hidden_states,
  374. )
  375. # post-process
  376. sample = self.conv_norm_out(sample)
  377. sample = self.conv_act(sample)
  378. sample = self.conv_out(sample)
  379. if not return_dict:
  380. return (sample,)
  381. return UNet3DConditionOutput(sample=sample)
  382. @classmethod
  383. def from_pretrained_2d(cls, pretrained_model_path, subfolder=None, unet_additional_kwargs=None):
  384. if subfolder is not None:
  385. pretrained_model_path = os.path.join(pretrained_model_path, subfolder)
  386. print(f"loaded temporal unet's pretrained weights from {pretrained_model_path} ...")
  387. config_file = os.path.join(pretrained_model_path, 'config.json')
  388. if not os.path.isfile(config_file):
  389. raise RuntimeError(f"{config_file} does not exist")
  390. with open(config_file, "r") as f:
  391. config = json.load(f)
  392. config["_class_name"] = cls.__name__
  393. config["down_block_types"] = [
  394. "CrossAttnDownBlock3D",
  395. "CrossAttnDownBlock3D",
  396. "CrossAttnDownBlock3D",
  397. "DownBlock3D"
  398. ]
  399. config["up_block_types"] = [
  400. "UpBlock3D",
  401. "CrossAttnUpBlock3D",
  402. "CrossAttnUpBlock3D",
  403. "CrossAttnUpBlock3D"
  404. ]
  405. from diffusers.utils import WEIGHTS_NAME
  406. model = cls.from_config(config, **unet_additional_kwargs)
  407. model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)
  408. if not os.path.isfile(model_file):
  409. raise RuntimeError(f"{model_file} does not exist")
  410. state_dict = torch.load(model_file, map_location="cpu")
  411. m, u = model.load_state_dict(state_dict, strict=False)
  412. print(f"### missing keys: {len(m)}; \n### unexpected keys: {len(u)};")
  413. # print(f"### missing keys:\n{m}\n### unexpected keys:\n{u}\n")
  414. params = [p.numel() if "temporal" in n else 0 for n, p in model.named_parameters()]
  415. print(f"### Temporal Module Parameters: {sum(params) / 1e6} M")
  416. return model