BrushNet_CA.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. from dataclasses import dataclass
  2. from typing import Any, Dict, List, Optional, Tuple, Union
  3. import torch
  4. from diffusers import UNet2DConditionModel
  5. from diffusers.configuration_utils import ConfigMixin, register_to_config
  6. from diffusers.models.attention_processor import (
  7. ADDED_KV_ATTENTION_PROCESSORS,
  8. CROSS_ATTENTION_PROCESSORS,
  9. AttentionProcessor,
  10. AttnAddedKVProcessor,
  11. AttnProcessor,
  12. )
  13. from diffusers.models.embeddings import (
  14. TextImageProjection,
  15. TextImageTimeEmbedding,
  16. TextTimeEmbedding,
  17. TimestepEmbedding,
  18. Timesteps,
  19. )
  20. from diffusers.models.modeling_utils import ModelMixin
  21. from diffusers.models.unets.unet_2d_blocks import (
  22. CrossAttnDownBlock2D,
  23. DownBlock2D,
  24. get_down_block,
  25. get_mid_block,
  26. get_up_block,
  27. )
  28. from diffusers.utils import BaseOutput, logging
  29. from torch import nn
  30. logger = logging.get_logger(__name__) # pylint: disable=invalid-name
  31. @dataclass
  32. class BrushNetOutput(BaseOutput):
  33. """
  34. The output of [`BrushNetModel`].
  35. Args:
  36. up_block_res_samples (`tuple[torch.Tensor]`):
  37. A tuple of upsample activations at different resolutions for each upsampling block. Each tensor should
  38. be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
  39. used to condition the original UNet's upsampling activations.
  40. down_block_res_samples (`tuple[torch.Tensor]`):
  41. A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
  42. be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
  43. used to condition the original UNet's downsampling activations.
  44. mid_down_block_re_sample (`torch.Tensor`):
  45. The activation of the midde block (the lowest sample resolution). Each tensor should be of shape
  46. `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
  47. Output can be used to condition the original UNet's middle block activation.
  48. """
  49. up_block_res_samples: Tuple[torch.Tensor]
  50. down_block_res_samples: Tuple[torch.Tensor]
  51. mid_block_res_sample: torch.Tensor
  52. class BrushNetModel(ModelMixin, ConfigMixin):
  53. """
  54. A BrushNet model.
  55. Args:
  56. in_channels (`int`, defaults to 4):
  57. The number of channels in the input sample.
  58. flip_sin_to_cos (`bool`, defaults to `True`):
  59. Whether to flip the sin to cos in the time embedding.
  60. freq_shift (`int`, defaults to 0):
  61. The frequency shift to apply to the time embedding.
  62. down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
  63. The tuple of downsample blocks to use.
  64. mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
  65. Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
  66. `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
  67. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
  68. The tuple of upsample blocks to use.
  69. only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
  70. block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
  71. The tuple of output channels for each block.
  72. layers_per_block (`int`, defaults to 2):
  73. The number of layers per block.
  74. downsample_padding (`int`, defaults to 1):
  75. The padding to use for the downsampling convolution.
  76. mid_block_scale_factor (`float`, defaults to 1):
  77. The scale factor to use for the mid block.
  78. act_fn (`str`, defaults to "silu"):
  79. The activation function to use.
  80. norm_num_groups (`int`, *optional*, defaults to 32):
  81. The number of groups to use for the normalization. If None, normalization and activation layers is skipped
  82. in post-processing.
  83. norm_eps (`float`, defaults to 1e-5):
  84. The epsilon to use for the normalization.
  85. cross_attention_dim (`int`, defaults to 1280):
  86. The dimension of the cross attention features.
  87. transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
  88. The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
  89. [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
  90. [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
  91. encoder_hid_dim (`int`, *optional*, defaults to None):
  92. If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
  93. dimension to `cross_attention_dim`.
  94. encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
  95. If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
  96. embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
  97. attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
  98. The dimension of the attention heads.
  99. use_linear_projection (`bool`, defaults to `False`):
  100. class_embed_type (`str`, *optional*, defaults to `None`):
  101. The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
  102. `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
  103. addition_embed_type (`str`, *optional*, defaults to `None`):
  104. Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
  105. "text". "text" will use the `TextTimeEmbedding` layer.
  106. num_class_embeds (`int`, *optional*, defaults to 0):
  107. Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
  108. class conditioning with `class_embed_type` equal to `None`.
  109. upcast_attention (`bool`, defaults to `False`):
  110. resnet_time_scale_shift (`str`, defaults to `"default"`):
  111. Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
  112. projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
  113. The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
  114. `class_embed_type="projection"`.
  115. brushnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
  116. The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
  117. conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
  118. The tuple of output channel for each block in the `conditioning_embedding` layer.
  119. global_pool_conditions (`bool`, defaults to `False`):
  120. TODO(Patrick) - unused parameter.
  121. addition_embed_type_num_heads (`int`, defaults to 64):
  122. The number of heads to use for the `TextTimeEmbedding` layer.
  123. """
  124. _supports_gradient_checkpointing = True
  125. @register_to_config
  126. def __init__(
  127. self,
  128. in_channels: int = 4,
  129. conditioning_channels: int = 5,
  130. flip_sin_to_cos: bool = True,
  131. freq_shift: int = 0,
  132. down_block_types: Tuple[str, ...] = (
  133. "CrossAttnDownBlock2D",
  134. "CrossAttnDownBlock2D",
  135. "CrossAttnDownBlock2D",
  136. "DownBlock2D",
  137. ),
  138. mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
  139. up_block_types: Tuple[str, ...] = (
  140. "UpBlock2D",
  141. "CrossAttnUpBlock2D",
  142. "CrossAttnUpBlock2D",
  143. "CrossAttnUpBlock2D",
  144. ),
  145. only_cross_attention: Union[bool, Tuple[bool]] = False,
  146. block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
  147. layers_per_block: int = 2,
  148. downsample_padding: int = 1,
  149. mid_block_scale_factor: float = 1,
  150. act_fn: str = "silu",
  151. norm_num_groups: Optional[int] = 32,
  152. norm_eps: float = 1e-5,
  153. cross_attention_dim: int = 1280,
  154. transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
  155. encoder_hid_dim: Optional[int] = None,
  156. encoder_hid_dim_type: Optional[str] = None,
  157. attention_head_dim: Union[int, Tuple[int, ...]] = 8,
  158. num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
  159. use_linear_projection: bool = False,
  160. class_embed_type: Optional[str] = None,
  161. addition_embed_type: Optional[str] = None,
  162. addition_time_embed_dim: Optional[int] = None,
  163. num_class_embeds: Optional[int] = None,
  164. upcast_attention: bool = False,
  165. resnet_time_scale_shift: str = "default",
  166. projection_class_embeddings_input_dim: Optional[int] = None,
  167. brushnet_conditioning_channel_order: str = "rgb",
  168. conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (
  169. 16,
  170. 32,
  171. 96,
  172. 256,
  173. ),
  174. global_pool_conditions: bool = False,
  175. addition_embed_type_num_heads: int = 64,
  176. ):
  177. super().__init__()
  178. # If `num_attention_heads` is not defined (which is the case for most models)
  179. # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
  180. # The reason for this behavior is to correct for incorrectly named variables that were introduced
  181. # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
  182. # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
  183. # which is why we correct for the naming here.
  184. num_attention_heads = num_attention_heads or attention_head_dim
  185. # Check inputs
  186. if len(down_block_types) != len(up_block_types):
  187. raise ValueError(
  188. f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
  189. )
  190. if len(block_out_channels) != len(down_block_types):
  191. raise ValueError(
  192. f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
  193. )
  194. if not isinstance(only_cross_attention, bool) and len(
  195. only_cross_attention
  196. ) != len(down_block_types):
  197. raise ValueError(
  198. f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
  199. )
  200. if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(
  201. down_block_types
  202. ):
  203. raise ValueError(
  204. f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
  205. )
  206. if isinstance(transformer_layers_per_block, int):
  207. transformer_layers_per_block = [transformer_layers_per_block] * len(
  208. down_block_types
  209. )
  210. # input
  211. conv_in_kernel = 3
  212. conv_in_padding = (conv_in_kernel - 1) // 2
  213. self.conv_in_condition = nn.Conv2d(
  214. in_channels + conditioning_channels,
  215. block_out_channels[0],
  216. kernel_size=conv_in_kernel,
  217. padding=conv_in_padding,
  218. )
  219. # time
  220. time_embed_dim = block_out_channels[0] * 4
  221. self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
  222. timestep_input_dim = block_out_channels[0]
  223. self.time_embedding = TimestepEmbedding(
  224. timestep_input_dim,
  225. time_embed_dim,
  226. act_fn=act_fn,
  227. )
  228. if encoder_hid_dim_type is None and encoder_hid_dim is not None:
  229. encoder_hid_dim_type = "text_proj"
  230. self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
  231. logger.info(
  232. "encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined."
  233. )
  234. if encoder_hid_dim is None and encoder_hid_dim_type is not None:
  235. raise ValueError(
  236. f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
  237. )
  238. if encoder_hid_dim_type == "text_proj":
  239. self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
  240. elif encoder_hid_dim_type == "text_image_proj":
  241. # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
  242. # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
  243. # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
  244. self.encoder_hid_proj = TextImageProjection(
  245. text_embed_dim=encoder_hid_dim,
  246. image_embed_dim=cross_attention_dim,
  247. cross_attention_dim=cross_attention_dim,
  248. )
  249. elif encoder_hid_dim_type is not None:
  250. raise ValueError(
  251. f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
  252. )
  253. else:
  254. self.encoder_hid_proj = None
  255. # class embedding
  256. if class_embed_type is None and num_class_embeds is not None:
  257. self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
  258. elif class_embed_type == "timestep":
  259. self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
  260. elif class_embed_type == "identity":
  261. self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
  262. elif class_embed_type == "projection":
  263. if projection_class_embeddings_input_dim is None:
  264. raise ValueError(
  265. "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
  266. )
  267. # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
  268. # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
  269. # 2. it projects from an arbitrary input dimension.
  270. #
  271. # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
  272. # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
  273. # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
  274. self.class_embedding = TimestepEmbedding(
  275. projection_class_embeddings_input_dim, time_embed_dim
  276. )
  277. else:
  278. self.class_embedding = None
  279. if addition_embed_type == "text":
  280. if encoder_hid_dim is not None:
  281. text_time_embedding_from_dim = encoder_hid_dim
  282. else:
  283. text_time_embedding_from_dim = cross_attention_dim
  284. self.add_embedding = TextTimeEmbedding(
  285. text_time_embedding_from_dim,
  286. time_embed_dim,
  287. num_heads=addition_embed_type_num_heads,
  288. )
  289. elif addition_embed_type == "text_image":
  290. # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
  291. # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
  292. # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
  293. self.add_embedding = TextImageTimeEmbedding(
  294. text_embed_dim=cross_attention_dim,
  295. image_embed_dim=cross_attention_dim,
  296. time_embed_dim=time_embed_dim,
  297. )
  298. elif addition_embed_type == "text_time":
  299. self.add_time_proj = Timesteps(
  300. addition_time_embed_dim, flip_sin_to_cos, freq_shift
  301. )
  302. self.add_embedding = TimestepEmbedding(
  303. projection_class_embeddings_input_dim, time_embed_dim
  304. )
  305. elif addition_embed_type is not None:
  306. raise ValueError(
  307. f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'."
  308. )
  309. self.down_blocks = nn.ModuleList([])
  310. self.brushnet_down_blocks = nn.ModuleList([])
  311. if isinstance(only_cross_attention, bool):
  312. only_cross_attention = [only_cross_attention] * len(down_block_types)
  313. if isinstance(attention_head_dim, int):
  314. attention_head_dim = (attention_head_dim,) * len(down_block_types)
  315. if isinstance(num_attention_heads, int):
  316. num_attention_heads = (num_attention_heads,) * len(down_block_types)
  317. # down
  318. output_channel = block_out_channels[0]
  319. brushnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
  320. brushnet_block = zero_module(brushnet_block)
  321. self.brushnet_down_blocks.append(brushnet_block)
  322. for i, down_block_type in enumerate(down_block_types):
  323. input_channel = output_channel
  324. output_channel = block_out_channels[i]
  325. is_final_block = i == len(block_out_channels) - 1
  326. down_block = get_down_block(
  327. down_block_type,
  328. num_layers=layers_per_block,
  329. transformer_layers_per_block=transformer_layers_per_block[i],
  330. in_channels=input_channel,
  331. out_channels=output_channel,
  332. temb_channels=time_embed_dim,
  333. add_downsample=not is_final_block,
  334. resnet_eps=norm_eps,
  335. resnet_act_fn=act_fn,
  336. resnet_groups=norm_num_groups,
  337. cross_attention_dim=cross_attention_dim,
  338. num_attention_heads=num_attention_heads[i],
  339. attention_head_dim=attention_head_dim[i]
  340. if attention_head_dim[i] is not None
  341. else output_channel,
  342. downsample_padding=downsample_padding,
  343. use_linear_projection=use_linear_projection,
  344. only_cross_attention=only_cross_attention[i],
  345. upcast_attention=upcast_attention,
  346. resnet_time_scale_shift=resnet_time_scale_shift,
  347. )
  348. self.down_blocks.append(down_block)
  349. for _ in range(layers_per_block):
  350. brushnet_block = nn.Conv2d(
  351. output_channel, output_channel, kernel_size=1
  352. )
  353. brushnet_block = zero_module(brushnet_block)
  354. self.brushnet_down_blocks.append(brushnet_block)
  355. if not is_final_block:
  356. brushnet_block = nn.Conv2d(
  357. output_channel, output_channel, kernel_size=1
  358. )
  359. brushnet_block = zero_module(brushnet_block)
  360. self.brushnet_down_blocks.append(brushnet_block)
  361. # mid
  362. mid_block_channel = block_out_channels[-1]
  363. brushnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
  364. brushnet_block = zero_module(brushnet_block)
  365. self.brushnet_mid_block = brushnet_block
  366. self.mid_block = get_mid_block(
  367. mid_block_type,
  368. transformer_layers_per_block=transformer_layers_per_block[-1],
  369. in_channels=mid_block_channel,
  370. temb_channels=time_embed_dim,
  371. resnet_eps=norm_eps,
  372. resnet_act_fn=act_fn,
  373. output_scale_factor=mid_block_scale_factor,
  374. resnet_time_scale_shift=resnet_time_scale_shift,
  375. cross_attention_dim=cross_attention_dim,
  376. num_attention_heads=num_attention_heads[-1],
  377. resnet_groups=norm_num_groups,
  378. use_linear_projection=use_linear_projection,
  379. upcast_attention=upcast_attention,
  380. )
  381. # count how many layers upsample the images
  382. self.num_upsamplers = 0
  383. # up
  384. reversed_block_out_channels = list(reversed(block_out_channels))
  385. reversed_num_attention_heads = list(reversed(num_attention_heads))
  386. reversed_transformer_layers_per_block = list(
  387. reversed(transformer_layers_per_block)
  388. )
  389. only_cross_attention = list(reversed(only_cross_attention))
  390. output_channel = reversed_block_out_channels[0]
  391. self.up_blocks = nn.ModuleList([])
  392. self.brushnet_up_blocks = nn.ModuleList([])
  393. for i, up_block_type in enumerate(up_block_types):
  394. is_final_block = i == len(block_out_channels) - 1
  395. prev_output_channel = output_channel
  396. output_channel = reversed_block_out_channels[i]
  397. input_channel = reversed_block_out_channels[
  398. min(i + 1, len(block_out_channels) - 1)
  399. ]
  400. # add upsample block for all BUT final layer
  401. if not is_final_block:
  402. add_upsample = True
  403. self.num_upsamplers += 1
  404. else:
  405. add_upsample = False
  406. up_block = get_up_block(
  407. up_block_type,
  408. num_layers=layers_per_block + 1,
  409. transformer_layers_per_block=reversed_transformer_layers_per_block[i],
  410. in_channels=input_channel,
  411. out_channels=output_channel,
  412. prev_output_channel=prev_output_channel,
  413. temb_channels=time_embed_dim,
  414. add_upsample=add_upsample,
  415. resnet_eps=norm_eps,
  416. resnet_act_fn=act_fn,
  417. resolution_idx=i,
  418. resnet_groups=norm_num_groups,
  419. cross_attention_dim=cross_attention_dim,
  420. num_attention_heads=reversed_num_attention_heads[i],
  421. use_linear_projection=use_linear_projection,
  422. only_cross_attention=only_cross_attention[i],
  423. upcast_attention=upcast_attention,
  424. resnet_time_scale_shift=resnet_time_scale_shift,
  425. attention_head_dim=attention_head_dim[i]
  426. if attention_head_dim[i] is not None
  427. else output_channel,
  428. )
  429. self.up_blocks.append(up_block)
  430. prev_output_channel = output_channel
  431. for _ in range(layers_per_block + 1):
  432. brushnet_block = nn.Conv2d(
  433. output_channel, output_channel, kernel_size=1
  434. )
  435. brushnet_block = zero_module(brushnet_block)
  436. self.brushnet_up_blocks.append(brushnet_block)
  437. if not is_final_block:
  438. brushnet_block = nn.Conv2d(
  439. output_channel, output_channel, kernel_size=1
  440. )
  441. brushnet_block = zero_module(brushnet_block)
  442. self.brushnet_up_blocks.append(brushnet_block)
  443. @classmethod
  444. def from_unet(
  445. cls,
  446. unet: UNet2DConditionModel,
  447. brushnet_conditioning_channel_order: str = "rgb",
  448. conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (
  449. 16,
  450. 32,
  451. 96,
  452. 256,
  453. ),
  454. load_weights_from_unet: bool = True,
  455. conditioning_channels: int = 5,
  456. ):
  457. r"""
  458. Instantiate a [`BrushNetModel`] from [`UNet2DConditionModel`].
  459. Parameters:
  460. unet (`UNet2DConditionModel`):
  461. The UNet model weights to copy to the [`BrushNetModel`]. All configuration options are also copied
  462. where applicable.
  463. """
  464. transformer_layers_per_block = (
  465. unet.config.transformer_layers_per_block
  466. if "transformer_layers_per_block" in unet.config
  467. else 1
  468. )
  469. encoder_hid_dim = (
  470. unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
  471. )
  472. encoder_hid_dim_type = (
  473. unet.config.encoder_hid_dim_type
  474. if "encoder_hid_dim_type" in unet.config
  475. else None
  476. )
  477. addition_embed_type = (
  478. unet.config.addition_embed_type
  479. if "addition_embed_type" in unet.config
  480. else None
  481. )
  482. addition_time_embed_dim = (
  483. unet.config.addition_time_embed_dim
  484. if "addition_time_embed_dim" in unet.config
  485. else None
  486. )
  487. brushnet = cls(
  488. in_channels=unet.config.in_channels,
  489. conditioning_channels=conditioning_channels,
  490. flip_sin_to_cos=unet.config.flip_sin_to_cos,
  491. freq_shift=unet.config.freq_shift,
  492. # down_block_types=['DownBlock2D','DownBlock2D','DownBlock2D','DownBlock2D'],
  493. down_block_types=[
  494. "CrossAttnDownBlock2D",
  495. "CrossAttnDownBlock2D",
  496. "CrossAttnDownBlock2D",
  497. "DownBlock2D",
  498. ],
  499. # mid_block_type='MidBlock2D',
  500. mid_block_type="UNetMidBlock2DCrossAttn",
  501. # up_block_types=['UpBlock2D','UpBlock2D','UpBlock2D','UpBlock2D'],
  502. up_block_types=[
  503. "UpBlock2D",
  504. "CrossAttnUpBlock2D",
  505. "CrossAttnUpBlock2D",
  506. "CrossAttnUpBlock2D",
  507. ],
  508. only_cross_attention=unet.config.only_cross_attention,
  509. block_out_channels=unet.config.block_out_channels,
  510. layers_per_block=unet.config.layers_per_block,
  511. downsample_padding=unet.config.downsample_padding,
  512. mid_block_scale_factor=unet.config.mid_block_scale_factor,
  513. act_fn=unet.config.act_fn,
  514. norm_num_groups=unet.config.norm_num_groups,
  515. norm_eps=unet.config.norm_eps,
  516. cross_attention_dim=unet.config.cross_attention_dim,
  517. transformer_layers_per_block=transformer_layers_per_block,
  518. encoder_hid_dim=encoder_hid_dim,
  519. encoder_hid_dim_type=encoder_hid_dim_type,
  520. attention_head_dim=unet.config.attention_head_dim,
  521. num_attention_heads=unet.config.num_attention_heads,
  522. use_linear_projection=unet.config.use_linear_projection,
  523. class_embed_type=unet.config.class_embed_type,
  524. addition_embed_type=addition_embed_type,
  525. addition_time_embed_dim=addition_time_embed_dim,
  526. num_class_embeds=unet.config.num_class_embeds,
  527. upcast_attention=unet.config.upcast_attention,
  528. resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
  529. projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
  530. brushnet_conditioning_channel_order=brushnet_conditioning_channel_order,
  531. conditioning_embedding_out_channels=conditioning_embedding_out_channels,
  532. )
  533. if load_weights_from_unet:
  534. conv_in_condition_weight = torch.zeros_like(
  535. brushnet.conv_in_condition.weight
  536. )
  537. conv_in_condition_weight[:, :4, ...] = unet.conv_in.weight
  538. conv_in_condition_weight[:, 4:8, ...] = unet.conv_in.weight
  539. brushnet.conv_in_condition.weight = torch.nn.Parameter(
  540. conv_in_condition_weight
  541. )
  542. brushnet.conv_in_condition.bias = unet.conv_in.bias
  543. brushnet.time_proj.load_state_dict(unet.time_proj.state_dict())
  544. brushnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
  545. if brushnet.class_embedding:
  546. brushnet.class_embedding.load_state_dict(
  547. unet.class_embedding.state_dict()
  548. )
  549. brushnet.down_blocks.load_state_dict(
  550. unet.down_blocks.state_dict(), strict=False
  551. )
  552. brushnet.mid_block.load_state_dict(
  553. unet.mid_block.state_dict(), strict=False
  554. )
  555. brushnet.up_blocks.load_state_dict(
  556. unet.up_blocks.state_dict(), strict=False
  557. )
  558. return brushnet.to(unet.dtype)
  559. @property
  560. # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
  561. def attn_processors(self) -> Dict[str, AttentionProcessor]:
  562. r"""
  563. Returns:
  564. `dict` of attention processors: A dictionary containing all attention processors used in the model with
  565. indexed by its weight name.
  566. """
  567. # set recursively
  568. processors = {}
  569. def fn_recursive_add_processors(
  570. name: str,
  571. module: torch.nn.Module,
  572. processors: Dict[str, AttentionProcessor],
  573. ):
  574. if hasattr(module, "get_processor"):
  575. processors[f"{name}.processor"] = module.get_processor(
  576. return_deprecated_lora=True
  577. )
  578. for sub_name, child in module.named_children():
  579. fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
  580. return processors
  581. for name, module in self.named_children():
  582. fn_recursive_add_processors(name, module, processors)
  583. return processors
  584. # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
  585. def set_attn_processor(
  586. self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]
  587. ):
  588. r"""
  589. Sets the attention processor to use to compute attention.
  590. Parameters:
  591. processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
  592. The instantiated processor class or a dictionary of processor classes that will be set as the processor
  593. for **all** `Attention` layers.
  594. If `processor` is a dict, the key needs to define the path to the corresponding cross attention
  595. processor. This is strongly recommended when setting trainable attention processors.
  596. """
  597. count = len(self.attn_processors.keys())
  598. if isinstance(processor, dict) and len(processor) != count:
  599. raise ValueError(
  600. f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
  601. f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
  602. )
  603. def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
  604. if hasattr(module, "set_processor"):
  605. if not isinstance(processor, dict):
  606. module.set_processor(processor)
  607. else:
  608. module.set_processor(processor.pop(f"{name}.processor"))
  609. for sub_name, child in module.named_children():
  610. fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
  611. for name, module in self.named_children():
  612. fn_recursive_attn_processor(name, module, processor)
  613. # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
  614. def set_default_attn_processor(self):
  615. """
  616. Disables custom attention processors and sets the default attention implementation.
  617. """
  618. if all(
  619. proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS
  620. for proc in self.attn_processors.values()
  621. ):
  622. processor = AttnAddedKVProcessor()
  623. elif all(
  624. proc.__class__ in CROSS_ATTENTION_PROCESSORS
  625. for proc in self.attn_processors.values()
  626. ):
  627. processor = AttnProcessor()
  628. else:
  629. raise ValueError(
  630. f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
  631. )
  632. self.set_attn_processor(processor)
  633. # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
  634. def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
  635. r"""
  636. Enable sliced attention computation.
  637. When this option is enabled, the attention module splits the input tensor in slices to compute attention in
  638. several steps. This is useful for saving some memory in exchange for a small decrease in speed.
  639. Args:
  640. slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
  641. When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
  642. `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
  643. provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
  644. must be a multiple of `slice_size`.
  645. """
  646. sliceable_head_dims = []
  647. def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
  648. if hasattr(module, "set_attention_slice"):
  649. sliceable_head_dims.append(module.sliceable_head_dim)
  650. for child in module.children():
  651. fn_recursive_retrieve_sliceable_dims(child)
  652. # retrieve number of attention layers
  653. for module in self.children():
  654. fn_recursive_retrieve_sliceable_dims(module)
  655. num_sliceable_layers = len(sliceable_head_dims)
  656. if slice_size == "auto":
  657. # half the attention head size is usually a good trade-off between
  658. # speed and memory
  659. slice_size = [dim // 2 for dim in sliceable_head_dims]
  660. elif slice_size == "max":
  661. # make smallest slice possible
  662. slice_size = num_sliceable_layers * [1]
  663. slice_size = (
  664. num_sliceable_layers * [slice_size]
  665. if not isinstance(slice_size, list)
  666. else slice_size
  667. )
  668. if len(slice_size) != len(sliceable_head_dims):
  669. raise ValueError(
  670. f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
  671. f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
  672. )
  673. for i in range(len(slice_size)):
  674. size = slice_size[i]
  675. dim = sliceable_head_dims[i]
  676. if size is not None and size > dim:
  677. raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
  678. # Recursively walk through all the children.
  679. # Any children which exposes the set_attention_slice method
  680. # gets the message
  681. def fn_recursive_set_attention_slice(
  682. module: torch.nn.Module, slice_size: List[int]
  683. ):
  684. if hasattr(module, "set_attention_slice"):
  685. module.set_attention_slice(slice_size.pop())
  686. for child in module.children():
  687. fn_recursive_set_attention_slice(child, slice_size)
  688. reversed_slice_size = list(reversed(slice_size))
  689. for module in self.children():
  690. fn_recursive_set_attention_slice(module, reversed_slice_size)
  691. def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
  692. if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
  693. module.gradient_checkpointing = value
  694. def forward(
  695. self,
  696. sample: torch.FloatTensor,
  697. timestep: Union[torch.Tensor, float, int],
  698. encoder_hidden_states: torch.Tensor,
  699. brushnet_cond: torch.FloatTensor,
  700. conditioning_scale: float = 1.0,
  701. class_labels: Optional[torch.Tensor] = None,
  702. timestep_cond: Optional[torch.Tensor] = None,
  703. attention_mask: Optional[torch.Tensor] = None,
  704. added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
  705. cross_attention_kwargs: Optional[Dict[str, Any]] = None,
  706. guess_mode: bool = False,
  707. return_dict: bool = True,
  708. ) -> Union[BrushNetOutput, Tuple[Tuple[torch.FloatTensor, ...], torch.FloatTensor]]:
  709. """
  710. The [`BrushNetModel`] forward method.
  711. Args:
  712. sample (`torch.FloatTensor`):
  713. The noisy input tensor.
  714. timestep (`Union[torch.Tensor, float, int]`):
  715. The number of timesteps to denoise an input.
  716. encoder_hidden_states (`torch.Tensor`):
  717. The encoder hidden states.
  718. brushnet_cond (`torch.FloatTensor`):
  719. The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
  720. conditioning_scale (`float`, defaults to `1.0`):
  721. The scale factor for BrushNet outputs.
  722. class_labels (`torch.Tensor`, *optional*, defaults to `None`):
  723. Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
  724. timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
  725. Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
  726. timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
  727. embeddings.
  728. attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
  729. An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
  730. is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
  731. negative values to the attention scores corresponding to "discard" tokens.
  732. added_cond_kwargs (`dict`):
  733. Additional conditions for the Stable Diffusion XL UNet.
  734. cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
  735. A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
  736. guess_mode (`bool`, defaults to `False`):
  737. In this mode, the BrushNet encoder tries its best to recognize the input content of the input even if
  738. you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
  739. return_dict (`bool`, defaults to `True`):
  740. Whether or not to return a [`~models.brushnet.BrushNetOutput`] instead of a plain tuple.
  741. Returns:
  742. [`~models.brushnet.BrushNetOutput`] **or** `tuple`:
  743. If `return_dict` is `True`, a [`~models.brushnet.BrushNetOutput`] is returned, otherwise a tuple is
  744. returned where the first element is the sample tensor.
  745. """
  746. # check channel order
  747. channel_order = self.config.brushnet_conditioning_channel_order
  748. if channel_order == "rgb":
  749. # in rgb order by default
  750. ...
  751. elif channel_order == "bgr":
  752. brushnet_cond = torch.flip(brushnet_cond, dims=[1])
  753. else:
  754. raise ValueError(
  755. f"unknown `brushnet_conditioning_channel_order`: {channel_order}"
  756. )
  757. # prepare attention_mask
  758. if attention_mask is not None:
  759. attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
  760. attention_mask = attention_mask.unsqueeze(1)
  761. # 1. time
  762. timesteps = timestep
  763. if not torch.is_tensor(timesteps):
  764. # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
  765. # This would be a good case for the `match` statement (Python 3.10+)
  766. is_mps = sample.device.type == "mps"
  767. if isinstance(timestep, float):
  768. dtype = torch.float32 if is_mps else torch.float64
  769. else:
  770. dtype = torch.int32 if is_mps else torch.int64
  771. timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
  772. elif len(timesteps.shape) == 0:
  773. timesteps = timesteps[None].to(sample.device)
  774. # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
  775. timesteps = timesteps.expand(sample.shape[0])
  776. t_emb = self.time_proj(timesteps)
  777. # timesteps does not contain any weights and will always return f32 tensors
  778. # but time_embedding might actually be running in fp16. so we need to cast here.
  779. # there might be better ways to encapsulate this.
  780. t_emb = t_emb.to(dtype=sample.dtype)
  781. emb = self.time_embedding(t_emb, timestep_cond)
  782. aug_emb = None
  783. if self.class_embedding is not None:
  784. if class_labels is None:
  785. raise ValueError(
  786. "class_labels should be provided when num_class_embeds > 0"
  787. )
  788. if self.config.class_embed_type == "timestep":
  789. class_labels = self.time_proj(class_labels)
  790. class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
  791. emb = emb + class_emb
  792. if self.config.addition_embed_type is not None:
  793. if self.config.addition_embed_type == "text":
  794. aug_emb = self.add_embedding(encoder_hidden_states)
  795. elif self.config.addition_embed_type == "text_time":
  796. if "text_embeds" not in added_cond_kwargs:
  797. raise ValueError(
  798. f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
  799. )
  800. text_embeds = added_cond_kwargs.get("text_embeds")
  801. if "time_ids" not in added_cond_kwargs:
  802. raise ValueError(
  803. f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
  804. )
  805. time_ids = added_cond_kwargs.get("time_ids")
  806. time_embeds = self.add_time_proj(time_ids.flatten())
  807. time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
  808. add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
  809. add_embeds = add_embeds.to(emb.dtype)
  810. aug_emb = self.add_embedding(add_embeds)
  811. emb = emb + aug_emb if aug_emb is not None else emb
  812. # 2. pre-process
  813. brushnet_cond = torch.concat([sample, brushnet_cond], 1)
  814. sample = self.conv_in_condition(brushnet_cond)
  815. # 3. down
  816. down_block_res_samples = (sample,)
  817. for downsample_block in self.down_blocks:
  818. if (
  819. hasattr(downsample_block, "has_cross_attention")
  820. and downsample_block.has_cross_attention
  821. ):
  822. sample, res_samples = downsample_block(
  823. hidden_states=sample,
  824. temb=emb,
  825. encoder_hidden_states=encoder_hidden_states,
  826. attention_mask=attention_mask,
  827. cross_attention_kwargs=cross_attention_kwargs,
  828. )
  829. else:
  830. sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
  831. down_block_res_samples += res_samples
  832. # 4. PaintingNet down blocks
  833. brushnet_down_block_res_samples = ()
  834. for down_block_res_sample, brushnet_down_block in zip(
  835. down_block_res_samples, self.brushnet_down_blocks
  836. ):
  837. down_block_res_sample = brushnet_down_block(down_block_res_sample)
  838. brushnet_down_block_res_samples = brushnet_down_block_res_samples + (
  839. down_block_res_sample,
  840. )
  841. # 5. mid
  842. if self.mid_block is not None:
  843. if (
  844. hasattr(self.mid_block, "has_cross_attention")
  845. and self.mid_block.has_cross_attention
  846. ):
  847. sample = self.mid_block(
  848. sample,
  849. emb,
  850. encoder_hidden_states=encoder_hidden_states,
  851. attention_mask=attention_mask,
  852. cross_attention_kwargs=cross_attention_kwargs,
  853. )
  854. else:
  855. sample = self.mid_block(sample, emb)
  856. # 6. BrushNet mid blocks
  857. brushnet_mid_block_res_sample = self.brushnet_mid_block(sample)
  858. # 7. up
  859. up_block_res_samples = ()
  860. for i, upsample_block in enumerate(self.up_blocks):
  861. is_final_block = i == len(self.up_blocks) - 1
  862. res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
  863. down_block_res_samples = down_block_res_samples[
  864. : -len(upsample_block.resnets)
  865. ]
  866. # if we have not reached the final block and need to forward the
  867. # upsample size, we do it here
  868. if not is_final_block:
  869. upsample_size = down_block_res_samples[-1].shape[2:]
  870. if (
  871. hasattr(upsample_block, "has_cross_attention")
  872. and upsample_block.has_cross_attention
  873. ):
  874. sample, up_res_samples = upsample_block(
  875. hidden_states=sample,
  876. temb=emb,
  877. res_hidden_states_tuple=res_samples,
  878. encoder_hidden_states=encoder_hidden_states,
  879. cross_attention_kwargs=cross_attention_kwargs,
  880. upsample_size=upsample_size,
  881. attention_mask=attention_mask,
  882. return_res_samples=True,
  883. )
  884. else:
  885. sample, up_res_samples = upsample_block(
  886. hidden_states=sample,
  887. temb=emb,
  888. res_hidden_states_tuple=res_samples,
  889. upsample_size=upsample_size,
  890. return_res_samples=True,
  891. )
  892. up_block_res_samples += up_res_samples
  893. # 8. BrushNet up blocks
  894. brushnet_up_block_res_samples = ()
  895. for up_block_res_sample, brushnet_up_block in zip(
  896. up_block_res_samples, self.brushnet_up_blocks
  897. ):
  898. up_block_res_sample = brushnet_up_block(up_block_res_sample)
  899. brushnet_up_block_res_samples = brushnet_up_block_res_samples + (
  900. up_block_res_sample,
  901. )
  902. # 6. scaling
  903. if guess_mode and not self.config.global_pool_conditions:
  904. scales = torch.logspace(
  905. -1,
  906. 0,
  907. len(brushnet_down_block_res_samples)
  908. + 1
  909. + len(brushnet_up_block_res_samples),
  910. device=sample.device,
  911. ) # 0.1 to 1.0
  912. scales = scales * conditioning_scale
  913. brushnet_down_block_res_samples = [
  914. sample * scale
  915. for sample, scale in zip(
  916. brushnet_down_block_res_samples,
  917. scales[: len(brushnet_down_block_res_samples)],
  918. )
  919. ]
  920. brushnet_mid_block_res_sample = (
  921. brushnet_mid_block_res_sample
  922. * scales[len(brushnet_down_block_res_samples)]
  923. )
  924. brushnet_up_block_res_samples = [
  925. sample * scale
  926. for sample, scale in zip(
  927. brushnet_up_block_res_samples,
  928. scales[len(brushnet_down_block_res_samples) + 1 :],
  929. )
  930. ]
  931. else:
  932. brushnet_down_block_res_samples = [
  933. sample * conditioning_scale
  934. for sample in brushnet_down_block_res_samples
  935. ]
  936. brushnet_mid_block_res_sample = (
  937. brushnet_mid_block_res_sample * conditioning_scale
  938. )
  939. brushnet_up_block_res_samples = [
  940. sample * conditioning_scale for sample in brushnet_up_block_res_samples
  941. ]
  942. if self.config.global_pool_conditions:
  943. brushnet_down_block_res_samples = [
  944. torch.mean(sample, dim=(2, 3), keepdim=True)
  945. for sample in brushnet_down_block_res_samples
  946. ]
  947. brushnet_mid_block_res_sample = torch.mean(
  948. brushnet_mid_block_res_sample, dim=(2, 3), keepdim=True
  949. )
  950. brushnet_up_block_res_samples = [
  951. torch.mean(sample, dim=(2, 3), keepdim=True)
  952. for sample in brushnet_up_block_res_samples
  953. ]
  954. if not return_dict:
  955. return (
  956. brushnet_down_block_res_samples,
  957. brushnet_mid_block_res_sample,
  958. brushnet_up_block_res_samples,
  959. )
  960. return BrushNetOutput(
  961. down_block_res_samples=brushnet_down_block_res_samples,
  962. mid_block_res_sample=brushnet_mid_block_res_sample,
  963. up_block_res_samples=brushnet_up_block_res_samples,
  964. )
  965. def zero_module(module):
  966. for p in module.parameters():
  967. nn.init.zeros_(p)
  968. return module