brushnet.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. from dataclasses import dataclass
  2. from typing import Any, Dict, List, Optional, Tuple, Union
  3. import torch
  4. from diffusers.configuration_utils import ConfigMixin, register_to_config
  5. from diffusers.models.attention_processor import (
  6. ADDED_KV_ATTENTION_PROCESSORS,
  7. CROSS_ATTENTION_PROCESSORS,
  8. AttentionProcessor,
  9. AttnAddedKVProcessor,
  10. AttnProcessor,
  11. )
  12. from diffusers.models.embeddings import (
  13. TextImageProjection,
  14. TextImageTimeEmbedding,
  15. TextTimeEmbedding,
  16. TimestepEmbedding,
  17. Timesteps,
  18. )
  19. from diffusers.models.modeling_utils import ModelMixin
  20. from diffusers.models.unets.unet_2d_blocks import (
  21. CrossAttnDownBlock2D,
  22. DownBlock2D,
  23. get_down_block,
  24. get_up_block,
  25. )
  26. from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel
  27. from diffusers.utils import BaseOutput, logging
  28. from torch import nn
  29. from .unet_2d_blocks import MidBlock2D
  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. "DownBlock2D",
  134. "DownBlock2D",
  135. "DownBlock2D",
  136. "DownBlock2D",
  137. ),
  138. mid_block_type: Optional[str] = "UNetMidBlock2D",
  139. up_block_types: Tuple[str, ...] = (
  140. "UpBlock2D",
  141. "UpBlock2D",
  142. "UpBlock2D",
  143. "UpBlock2D",
  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 = MidBlock2D(
  367. in_channels=mid_block_channel,
  368. temb_channels=time_embed_dim,
  369. dropout=0.0,
  370. resnet_eps=norm_eps,
  371. resnet_act_fn=act_fn,
  372. output_scale_factor=mid_block_scale_factor,
  373. resnet_time_scale_shift=resnet_time_scale_shift,
  374. resnet_groups=norm_num_groups,
  375. use_linear_projection=use_linear_projection,
  376. )
  377. # count how many layers upsample the images
  378. self.num_upsamplers = 0
  379. # up
  380. reversed_block_out_channels = list(reversed(block_out_channels))
  381. reversed_num_attention_heads = list(reversed(num_attention_heads))
  382. reversed_transformer_layers_per_block = list(
  383. reversed(transformer_layers_per_block)
  384. )
  385. only_cross_attention = list(reversed(only_cross_attention))
  386. output_channel = reversed_block_out_channels[0]
  387. self.up_blocks = nn.ModuleList([])
  388. self.brushnet_up_blocks = nn.ModuleList([])
  389. for i, up_block_type in enumerate(up_block_types):
  390. is_final_block = i == len(block_out_channels) - 1
  391. prev_output_channel = output_channel
  392. output_channel = reversed_block_out_channels[i]
  393. input_channel = reversed_block_out_channels[
  394. min(i + 1, len(block_out_channels) - 1)
  395. ]
  396. # add upsample block for all BUT final layer
  397. if not is_final_block:
  398. add_upsample = True
  399. self.num_upsamplers += 1
  400. else:
  401. add_upsample = False
  402. up_block = get_up_block(
  403. up_block_type,
  404. num_layers=layers_per_block + 1,
  405. transformer_layers_per_block=reversed_transformer_layers_per_block[i],
  406. in_channels=input_channel,
  407. out_channels=output_channel,
  408. prev_output_channel=prev_output_channel,
  409. temb_channels=time_embed_dim,
  410. add_upsample=add_upsample,
  411. resnet_eps=norm_eps,
  412. resnet_act_fn=act_fn,
  413. resolution_idx=i,
  414. resnet_groups=norm_num_groups,
  415. cross_attention_dim=cross_attention_dim,
  416. num_attention_heads=reversed_num_attention_heads[i],
  417. use_linear_projection=use_linear_projection,
  418. only_cross_attention=only_cross_attention[i],
  419. upcast_attention=upcast_attention,
  420. resnet_time_scale_shift=resnet_time_scale_shift,
  421. attention_head_dim=attention_head_dim[i]
  422. if attention_head_dim[i] is not None
  423. else output_channel,
  424. )
  425. self.up_blocks.append(up_block)
  426. prev_output_channel = output_channel
  427. for _ in range(layers_per_block + 1):
  428. brushnet_block = nn.Conv2d(
  429. output_channel, output_channel, kernel_size=1
  430. )
  431. brushnet_block = zero_module(brushnet_block)
  432. self.brushnet_up_blocks.append(brushnet_block)
  433. if not is_final_block:
  434. brushnet_block = nn.Conv2d(
  435. output_channel, output_channel, kernel_size=1
  436. )
  437. brushnet_block = zero_module(brushnet_block)
  438. self.brushnet_up_blocks.append(brushnet_block)
  439. @classmethod
  440. def from_unet(
  441. cls,
  442. unet: UNet2DConditionModel,
  443. brushnet_conditioning_channel_order: str = "rgb",
  444. conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (
  445. 16,
  446. 32,
  447. 96,
  448. 256,
  449. ),
  450. load_weights_from_unet: bool = True,
  451. conditioning_channels: int = 5,
  452. ):
  453. r"""
  454. Instantiate a [`BrushNetModel`] from [`UNet2DConditionModel`].
  455. Parameters:
  456. unet (`UNet2DConditionModel`):
  457. The UNet model weights to copy to the [`BrushNetModel`]. All configuration options are also copied
  458. where applicable.
  459. """
  460. transformer_layers_per_block = (
  461. unet.config.transformer_layers_per_block
  462. if "transformer_layers_per_block" in unet.config
  463. else 1
  464. )
  465. encoder_hid_dim = (
  466. unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
  467. )
  468. encoder_hid_dim_type = (
  469. unet.config.encoder_hid_dim_type
  470. if "encoder_hid_dim_type" in unet.config
  471. else None
  472. )
  473. addition_embed_type = (
  474. unet.config.addition_embed_type
  475. if "addition_embed_type" in unet.config
  476. else None
  477. )
  478. addition_time_embed_dim = (
  479. unet.config.addition_time_embed_dim
  480. if "addition_time_embed_dim" in unet.config
  481. else None
  482. )
  483. brushnet = cls(
  484. in_channels=unet.config.in_channels,
  485. conditioning_channels=conditioning_channels,
  486. flip_sin_to_cos=unet.config.flip_sin_to_cos,
  487. freq_shift=unet.config.freq_shift,
  488. down_block_types=[
  489. "DownBlock2D",
  490. "DownBlock2D",
  491. "DownBlock2D",
  492. "DownBlock2D",
  493. ],
  494. mid_block_type="MidBlock2D",
  495. up_block_types=["UpBlock2D", "UpBlock2D", "UpBlock2D", "UpBlock2D"],
  496. only_cross_attention=unet.config.only_cross_attention,
  497. block_out_channels=unet.config.block_out_channels,
  498. layers_per_block=unet.config.layers_per_block,
  499. downsample_padding=unet.config.downsample_padding,
  500. mid_block_scale_factor=unet.config.mid_block_scale_factor,
  501. act_fn=unet.config.act_fn,
  502. norm_num_groups=unet.config.norm_num_groups,
  503. norm_eps=unet.config.norm_eps,
  504. cross_attention_dim=unet.config.cross_attention_dim,
  505. transformer_layers_per_block=transformer_layers_per_block,
  506. encoder_hid_dim=encoder_hid_dim,
  507. encoder_hid_dim_type=encoder_hid_dim_type,
  508. attention_head_dim=unet.config.attention_head_dim,
  509. num_attention_heads=unet.config.num_attention_heads,
  510. use_linear_projection=unet.config.use_linear_projection,
  511. class_embed_type=unet.config.class_embed_type,
  512. addition_embed_type=addition_embed_type,
  513. addition_time_embed_dim=addition_time_embed_dim,
  514. num_class_embeds=unet.config.num_class_embeds,
  515. upcast_attention=unet.config.upcast_attention,
  516. resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
  517. projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
  518. brushnet_conditioning_channel_order=brushnet_conditioning_channel_order,
  519. conditioning_embedding_out_channels=conditioning_embedding_out_channels,
  520. )
  521. if load_weights_from_unet:
  522. conv_in_condition_weight = torch.zeros_like(
  523. brushnet.conv_in_condition.weight
  524. )
  525. conv_in_condition_weight[:, :4, ...] = unet.conv_in.weight
  526. conv_in_condition_weight[:, 4:8, ...] = unet.conv_in.weight
  527. brushnet.conv_in_condition.weight = torch.nn.Parameter(
  528. conv_in_condition_weight
  529. )
  530. brushnet.conv_in_condition.bias = unet.conv_in.bias
  531. brushnet.time_proj.load_state_dict(unet.time_proj.state_dict())
  532. brushnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
  533. if brushnet.class_embedding:
  534. brushnet.class_embedding.load_state_dict(
  535. unet.class_embedding.state_dict()
  536. )
  537. brushnet.down_blocks.load_state_dict(
  538. unet.down_blocks.state_dict(), strict=False
  539. )
  540. brushnet.mid_block.load_state_dict(
  541. unet.mid_block.state_dict(), strict=False
  542. )
  543. brushnet.up_blocks.load_state_dict(
  544. unet.up_blocks.state_dict(), strict=False
  545. )
  546. return brushnet
  547. @property
  548. # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
  549. def attn_processors(self) -> Dict[str, AttentionProcessor]:
  550. r"""
  551. Returns:
  552. `dict` of attention processors: A dictionary containing all attention processors used in the model with
  553. indexed by its weight name.
  554. """
  555. # set recursively
  556. processors = {}
  557. def fn_recursive_add_processors(
  558. name: str,
  559. module: torch.nn.Module,
  560. processors: Dict[str, AttentionProcessor],
  561. ):
  562. if hasattr(module, "get_processor"):
  563. processors[f"{name}.processor"] = module.get_processor(
  564. return_deprecated_lora=True
  565. )
  566. for sub_name, child in module.named_children():
  567. fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
  568. return processors
  569. for name, module in self.named_children():
  570. fn_recursive_add_processors(name, module, processors)
  571. return processors
  572. # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
  573. def set_attn_processor(
  574. self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]
  575. ):
  576. r"""
  577. Sets the attention processor to use to compute attention.
  578. Parameters:
  579. processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
  580. The instantiated processor class or a dictionary of processor classes that will be set as the processor
  581. for **all** `Attention` layers.
  582. If `processor` is a dict, the key needs to define the path to the corresponding cross attention
  583. processor. This is strongly recommended when setting trainable attention processors.
  584. """
  585. count = len(self.attn_processors.keys())
  586. if isinstance(processor, dict) and len(processor) != count:
  587. raise ValueError(
  588. f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
  589. f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
  590. )
  591. def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
  592. if hasattr(module, "set_processor"):
  593. if not isinstance(processor, dict):
  594. module.set_processor(processor)
  595. else:
  596. module.set_processor(processor.pop(f"{name}.processor"))
  597. for sub_name, child in module.named_children():
  598. fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
  599. for name, module in self.named_children():
  600. fn_recursive_attn_processor(name, module, processor)
  601. # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
  602. def set_default_attn_processor(self):
  603. """
  604. Disables custom attention processors and sets the default attention implementation.
  605. """
  606. if all(
  607. proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS
  608. for proc in self.attn_processors.values()
  609. ):
  610. processor = AttnAddedKVProcessor()
  611. elif all(
  612. proc.__class__ in CROSS_ATTENTION_PROCESSORS
  613. for proc in self.attn_processors.values()
  614. ):
  615. processor = AttnProcessor()
  616. else:
  617. raise ValueError(
  618. f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
  619. )
  620. self.set_attn_processor(processor)
  621. # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
  622. def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
  623. r"""
  624. Enable sliced attention computation.
  625. When this option is enabled, the attention module splits the input tensor in slices to compute attention in
  626. several steps. This is useful for saving some memory in exchange for a small decrease in speed.
  627. Args:
  628. slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
  629. When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
  630. `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
  631. provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
  632. must be a multiple of `slice_size`.
  633. """
  634. sliceable_head_dims = []
  635. def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
  636. if hasattr(module, "set_attention_slice"):
  637. sliceable_head_dims.append(module.sliceable_head_dim)
  638. for child in module.children():
  639. fn_recursive_retrieve_sliceable_dims(child)
  640. # retrieve number of attention layers
  641. for module in self.children():
  642. fn_recursive_retrieve_sliceable_dims(module)
  643. num_sliceable_layers = len(sliceable_head_dims)
  644. if slice_size == "auto":
  645. # half the attention head size is usually a good trade-off between
  646. # speed and memory
  647. slice_size = [dim // 2 for dim in sliceable_head_dims]
  648. elif slice_size == "max":
  649. # make smallest slice possible
  650. slice_size = num_sliceable_layers * [1]
  651. slice_size = (
  652. num_sliceable_layers * [slice_size]
  653. if not isinstance(slice_size, list)
  654. else slice_size
  655. )
  656. if len(slice_size) != len(sliceable_head_dims):
  657. raise ValueError(
  658. f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
  659. f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
  660. )
  661. for i in range(len(slice_size)):
  662. size = slice_size[i]
  663. dim = sliceable_head_dims[i]
  664. if size is not None and size > dim:
  665. raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
  666. # Recursively walk through all the children.
  667. # Any children which exposes the set_attention_slice method
  668. # gets the message
  669. def fn_recursive_set_attention_slice(
  670. module: torch.nn.Module, slice_size: List[int]
  671. ):
  672. if hasattr(module, "set_attention_slice"):
  673. module.set_attention_slice(slice_size.pop())
  674. for child in module.children():
  675. fn_recursive_set_attention_slice(child, slice_size)
  676. reversed_slice_size = list(reversed(slice_size))
  677. for module in self.children():
  678. fn_recursive_set_attention_slice(module, reversed_slice_size)
  679. def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
  680. if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
  681. module.gradient_checkpointing = value
  682. def forward(
  683. self,
  684. sample: torch.FloatTensor,
  685. timestep: Union[torch.Tensor, float, int],
  686. encoder_hidden_states: torch.Tensor,
  687. brushnet_cond: torch.FloatTensor,
  688. conditioning_scale: float = 1.0,
  689. class_labels: Optional[torch.Tensor] = None,
  690. timestep_cond: Optional[torch.Tensor] = None,
  691. attention_mask: Optional[torch.Tensor] = None,
  692. added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
  693. cross_attention_kwargs: Optional[Dict[str, Any]] = None,
  694. guess_mode: bool = False,
  695. return_dict: bool = True,
  696. ) -> Union[BrushNetOutput, Tuple[Tuple[torch.FloatTensor, ...], torch.FloatTensor]]:
  697. """
  698. The [`BrushNetModel`] forward method.
  699. Args:
  700. sample (`torch.FloatTensor`):
  701. The noisy input tensor.
  702. timestep (`Union[torch.Tensor, float, int]`):
  703. The number of timesteps to denoise an input.
  704. encoder_hidden_states (`torch.Tensor`):
  705. The encoder hidden states.
  706. brushnet_cond (`torch.FloatTensor`):
  707. The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
  708. conditioning_scale (`float`, defaults to `1.0`):
  709. The scale factor for BrushNet outputs.
  710. class_labels (`torch.Tensor`, *optional*, defaults to `None`):
  711. Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
  712. timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
  713. Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
  714. timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
  715. embeddings.
  716. attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
  717. An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
  718. is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
  719. negative values to the attention scores corresponding to "discard" tokens.
  720. added_cond_kwargs (`dict`):
  721. Additional conditions for the Stable Diffusion XL UNet.
  722. cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
  723. A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
  724. guess_mode (`bool`, defaults to `False`):
  725. In this mode, the BrushNet encoder tries its best to recognize the input content of the input even if
  726. you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
  727. return_dict (`bool`, defaults to `True`):
  728. Whether or not to return a [`~models.brushnet.BrushNetOutput`] instead of a plain tuple.
  729. Returns:
  730. [`~models.brushnet.BrushNetOutput`] **or** `tuple`:
  731. If `return_dict` is `True`, a [`~models.brushnet.BrushNetOutput`] is returned, otherwise a tuple is
  732. returned where the first element is the sample tensor.
  733. """
  734. # check channel order
  735. channel_order = self.config.brushnet_conditioning_channel_order
  736. if channel_order == "rgb":
  737. # in rgb order by default
  738. ...
  739. elif channel_order == "bgr":
  740. brushnet_cond = torch.flip(brushnet_cond, dims=[1])
  741. else:
  742. raise ValueError(
  743. f"unknown `brushnet_conditioning_channel_order`: {channel_order}"
  744. )
  745. # prepare attention_mask
  746. if attention_mask is not None:
  747. attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
  748. attention_mask = attention_mask.unsqueeze(1)
  749. # 1. time
  750. timesteps = timestep
  751. if not torch.is_tensor(timesteps):
  752. # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
  753. # This would be a good case for the `match` statement (Python 3.10+)
  754. is_mps = sample.device.type == "mps"
  755. if isinstance(timestep, float):
  756. dtype = torch.float32 if is_mps else torch.float64
  757. else:
  758. dtype = torch.int32 if is_mps else torch.int64
  759. timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
  760. elif len(timesteps.shape) == 0:
  761. timesteps = timesteps[None].to(sample.device)
  762. # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
  763. timesteps = timesteps.expand(sample.shape[0])
  764. t_emb = self.time_proj(timesteps)
  765. # timesteps does not contain any weights and will always return f32 tensors
  766. # but time_embedding might actually be running in fp16. so we need to cast here.
  767. # there might be better ways to encapsulate this.
  768. t_emb = t_emb.to(dtype=sample.dtype)
  769. emb = self.time_embedding(t_emb, timestep_cond)
  770. aug_emb = None
  771. if self.class_embedding is not None:
  772. if class_labels is None:
  773. raise ValueError(
  774. "class_labels should be provided when num_class_embeds > 0"
  775. )
  776. if self.config.class_embed_type == "timestep":
  777. class_labels = self.time_proj(class_labels)
  778. class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
  779. emb = emb + class_emb
  780. if self.config.addition_embed_type is not None:
  781. if self.config.addition_embed_type == "text":
  782. aug_emb = self.add_embedding(encoder_hidden_states)
  783. elif self.config.addition_embed_type == "text_time":
  784. if "text_embeds" not in added_cond_kwargs:
  785. raise ValueError(
  786. 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`"
  787. )
  788. text_embeds = added_cond_kwargs.get("text_embeds")
  789. if "time_ids" not in added_cond_kwargs:
  790. raise ValueError(
  791. 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`"
  792. )
  793. time_ids = added_cond_kwargs.get("time_ids")
  794. time_embeds = self.add_time_proj(time_ids.flatten())
  795. time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
  796. add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
  797. add_embeds = add_embeds.to(emb.dtype)
  798. aug_emb = self.add_embedding(add_embeds)
  799. emb = emb + aug_emb if aug_emb is not None else emb
  800. # 2. pre-process
  801. brushnet_cond = torch.concat([sample, brushnet_cond], 1)
  802. sample = self.conv_in_condition(brushnet_cond)
  803. # 3. down
  804. down_block_res_samples = (sample,)
  805. for downsample_block in self.down_blocks:
  806. if (
  807. hasattr(downsample_block, "has_cross_attention")
  808. and downsample_block.has_cross_attention
  809. ):
  810. sample, res_samples = downsample_block(
  811. hidden_states=sample,
  812. temb=emb,
  813. encoder_hidden_states=encoder_hidden_states,
  814. attention_mask=attention_mask,
  815. cross_attention_kwargs=cross_attention_kwargs,
  816. )
  817. else:
  818. sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
  819. down_block_res_samples += res_samples
  820. # 4. PaintingNet down blocks
  821. brushnet_down_block_res_samples = ()
  822. for down_block_res_sample, brushnet_down_block in zip(
  823. down_block_res_samples, self.brushnet_down_blocks
  824. ):
  825. down_block_res_sample = brushnet_down_block(down_block_res_sample)
  826. brushnet_down_block_res_samples = brushnet_down_block_res_samples + (
  827. down_block_res_sample,
  828. )
  829. # 5. mid
  830. if self.mid_block is not None:
  831. if (
  832. hasattr(self.mid_block, "has_cross_attention")
  833. and self.mid_block.has_cross_attention
  834. ):
  835. sample = self.mid_block(
  836. sample,
  837. emb,
  838. encoder_hidden_states=encoder_hidden_states,
  839. attention_mask=attention_mask,
  840. cross_attention_kwargs=cross_attention_kwargs,
  841. )
  842. else:
  843. sample = self.mid_block(sample, emb)
  844. # 6. BrushNet mid blocks
  845. brushnet_mid_block_res_sample = self.brushnet_mid_block(sample)
  846. # 7. up
  847. up_block_res_samples = ()
  848. for i, upsample_block in enumerate(self.up_blocks):
  849. is_final_block = i == len(self.up_blocks) - 1
  850. res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
  851. down_block_res_samples = down_block_res_samples[
  852. : -len(upsample_block.resnets)
  853. ]
  854. # if we have not reached the final block and need to forward the
  855. # upsample size, we do it here
  856. if not is_final_block:
  857. upsample_size = down_block_res_samples[-1].shape[2:]
  858. if (
  859. hasattr(upsample_block, "has_cross_attention")
  860. and upsample_block.has_cross_attention
  861. ):
  862. sample, up_res_samples = upsample_block(
  863. hidden_states=sample,
  864. temb=emb,
  865. res_hidden_states_tuple=res_samples,
  866. encoder_hidden_states=encoder_hidden_states,
  867. cross_attention_kwargs=cross_attention_kwargs,
  868. upsample_size=upsample_size,
  869. attention_mask=attention_mask,
  870. return_res_samples=True,
  871. )
  872. else:
  873. sample, up_res_samples = upsample_block(
  874. hidden_states=sample,
  875. temb=emb,
  876. res_hidden_states_tuple=res_samples,
  877. upsample_size=upsample_size,
  878. return_res_samples=True,
  879. )
  880. up_block_res_samples += up_res_samples
  881. # 8. BrushNet up blocks
  882. brushnet_up_block_res_samples = ()
  883. for up_block_res_sample, brushnet_up_block in zip(
  884. up_block_res_samples, self.brushnet_up_blocks
  885. ):
  886. up_block_res_sample = brushnet_up_block(up_block_res_sample)
  887. brushnet_up_block_res_samples = brushnet_up_block_res_samples + (
  888. up_block_res_sample,
  889. )
  890. # 6. scaling
  891. if guess_mode and not self.config.global_pool_conditions:
  892. scales = torch.logspace(
  893. -1,
  894. 0,
  895. len(brushnet_down_block_res_samples)
  896. + 1
  897. + len(brushnet_up_block_res_samples),
  898. device=sample.device,
  899. ) # 0.1 to 1.0
  900. scales = scales * conditioning_scale
  901. brushnet_down_block_res_samples = [
  902. sample * scale
  903. for sample, scale in zip(
  904. brushnet_down_block_res_samples,
  905. scales[: len(brushnet_down_block_res_samples)],
  906. )
  907. ]
  908. brushnet_mid_block_res_sample = (
  909. brushnet_mid_block_res_sample
  910. * scales[len(brushnet_down_block_res_samples)]
  911. )
  912. brushnet_up_block_res_samples = [
  913. sample * scale
  914. for sample, scale in zip(
  915. brushnet_up_block_res_samples,
  916. scales[len(brushnet_down_block_res_samples) + 1 :],
  917. )
  918. ]
  919. else:
  920. brushnet_down_block_res_samples = [
  921. sample * conditioning_scale
  922. for sample in brushnet_down_block_res_samples
  923. ]
  924. brushnet_mid_block_res_sample = (
  925. brushnet_mid_block_res_sample * conditioning_scale
  926. )
  927. brushnet_up_block_res_samples = [
  928. sample * conditioning_scale for sample in brushnet_up_block_res_samples
  929. ]
  930. if self.config.global_pool_conditions:
  931. brushnet_down_block_res_samples = [
  932. torch.mean(sample, dim=(2, 3), keepdim=True)
  933. for sample in brushnet_down_block_res_samples
  934. ]
  935. brushnet_mid_block_res_sample = torch.mean(
  936. brushnet_mid_block_res_sample, dim=(2, 3), keepdim=True
  937. )
  938. brushnet_up_block_res_samples = [
  939. torch.mean(sample, dim=(2, 3), keepdim=True)
  940. for sample in brushnet_up_block_res_samples
  941. ]
  942. if not return_dict:
  943. return (
  944. brushnet_down_block_res_samples,
  945. brushnet_mid_block_res_sample,
  946. brushnet_up_block_res_samples,
  947. )
  948. return BrushNetOutput(
  949. down_block_res_samples=brushnet_down_block_res_samples,
  950. mid_block_res_sample=brushnet_mid_block_res_sample,
  951. up_block_res_samples=brushnet_up_block_res_samples,
  952. )
  953. def zero_module(module):
  954. for p in module.parameters():
  955. nn.init.zeros_(p)
  956. return module
  957. if __name__ == "__main__":
  958. BrushNetModel.from_pretrained(
  959. "/Users/cwq/data/models/brushnet/brushnet_random_mask",
  960. variant="fp16",
  961. use_safetensors=True,
  962. )