OSCR

A multi-modal foundation model for brain disease diagnosis and medical imaging.

Code ↔ Paper

8 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 8 matches · 1 of them tie a paragraph to a whole file, not to given lines: a weak match, whose lines are not tinted
  1. [1] § Methods › Fine-tuning Brainfound to downstream tasks › Medical image report generation task ↔ downstream_task/report_gen/pretrain_model.py, lines 20–103 · score 0.66 · beam search, hidden layers, text decoder, vocabulary, BERT, models
  2. [2] § Methods › Fine-tuning Brainfound to downstream tasks › ICH and midline structure segmentation task ↔ downstream_task/report_gen/pretrain.py, lines 309–419 · score 0.63 · AdamW, weight decay, location, optimizer, validation, maps
  3. [3] § Methods › Fine-tuning Brainfound to downstream tasks › ICH and midline structure segmentation task ↔ pretrain_code/stage2/pretrain.py, lines 386–523 · score 0.63 · AdamW, weight decay, location, optimizer, validation, maps
  4. [4] § Methods › Network architecture ↔ downstream_task/report_gen/modules/caption_modules.py, the whole file · a weak match · score 0.61 · multi head, position embedding, language model, tokens, transformer
  5. [5] § Methods › Network architecture ↔ downstream_task/report_gen/UNet2d_condition.py, lines 814–889 · score 0.60 · UNet, cross attention, connected, deep, residual, width
  6. [6] § Methods › Network architecture ↔ pretrain_code/stage3/UNet2d_condition.py, lines 810–885 · score 0.60 · UNet, cross attention, connected, deep, residual, width
  7. [7] § Methods › Network architecture ↔ downstream_task/report_gen/modules/fusion_modules.py, lines 42–103 · score 0.60 · Positional encoding, transformer encoders, layer normalization, module, model
  8. [8] § Methods › Visualization of saliency maps ↔ downstream_task/report_gen/UNet2d_condition.py, lines 1437–1535 · score 0.54 · Grad CAM, heatmap, bilinear, contour, weights

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 1,535 lines · 75 KB · no license · 2 matches

  1. # Copyright 2023 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import safetensors
  15. from dataclasses import dataclass
  16. from typing import Any, Dict, List, Optional, Tuple, Union
  17. import torch
  18. import torch.nn as nn
  19. import numpy as np
  20. import matplotlib.pyplot as plt
  21. import cv2
  22. import os
  23. import torch.nn.functional as F
  24. from diffusers.models.modeling_utils import ModelMixin
  25. # from diffusers.models.unets.unet_2d_blocks import SimpleCrossAttnUpBlock2D
  26. from diffusers.configuration_utils import ConfigMixin, register_to_config
  27. from diffusers.loaders import UNet2DConditionLoadersMixin
  28. from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, logging, scale_lora_layers, unscale_lora_layers
  29. from diffusers.models.activations import get_activation
  30. from diffusers.models.attention_processor import (
  31. ADDED_KV_ATTENTION_PROCESSORS,
  32. CROSS_ATTENTION_PROCESSORS,
  33. AttentionProcessor,
  34. AttnAddedKVProcessor,
  35. AttnProcessor,
  36. )
  37. from diffusers.models.embeddings import (
  38. GaussianFourierProjection,
  39. ImageHintTimeEmbedding,
  40. ImageProjection,
  41. ImageTimeEmbedding,
  42. TextImageProjection,
  43. TextImageTimeEmbedding,
  44. TextTimeEmbedding,
  45. TimestepEmbedding,
  46. Timesteps,
  47. )
  48. from diffusers.models.unets.unet_2d_blocks import (
  49. UNetMidBlock2D,
  50. UNetMidBlock2DCrossAttn,
  51. UNetMidBlock2DSimpleCrossAttn,
  52. get_down_block,
  53. get_up_block,
  54. )
  55. logger = logging.get_logger(__name__) # pylint: disable=invalid-name
  56. @dataclass
  57. class UNet2DConditionOutput(BaseOutput):
  58. """
  59. The output of [`UNet2DConditionModel`].
  60. Args:
  61. sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  62. The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
  63. """
  64. sample: torch.FloatTensor = None
  65. class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
  66. r"""
  67. A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
  68. shaped output.
  69. This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
  70. for all models (such as downloading or saving).
  71. Parameters:
  72. sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
  73. Height and width of input/output sample.
  74. in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
  75. out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
  76. center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
  77. flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
  78. Whether to flip the sin to cos in the time embedding.
  79. freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
  80. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
  81. The tuple of downsample blocks to use.
  82. mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
  83. Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
  84. `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
  85. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
  86. The tuple of upsample blocks to use.
  87. only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
  88. Whether to include self-attention in the basic transformer blocks, see
  89. [`~models.attention.BasicTransformerBlock`].
  90. block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
  91. The tuple of output channels for each block.
  92. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
  93. downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
  94. mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
  95. dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
  96. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
  97. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
  98. If `None`, normalization and activation layers is skipped in post-processing.
  99. norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
  100. cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
  101. The dimension of the cross attention features.
  102. transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
  103. The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
  104. [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
  105. [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
  106. reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
  107. The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
  108. blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
  109. [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
  110. [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
  111. encoder_hid_dim (`int`, *optional*, defaults to None):
  112. If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
  113. dimension to `cross_attention_dim`.
  114. encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
  115. If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
  116. embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
  117. attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
  118. num_attention_heads (`int`, *optional*):
  119. The number of attention heads. If not defined, defaults to `attention_head_dim`
  120. resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
  121. for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
  122. class_embed_type (`str`, *optional*, defaults to `None`):
  123. The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
  124. `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
  125. addition_embed_type (`str`, *optional*, defaults to `None`):
  126. Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
  127. "text". "text" will use the `TextTimeEmbedding` layer.
  128. addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
  129. Dimension for the timestep embeddings.
  130. num_class_embeds (`int`, *optional*, defaults to `None`):
  131. Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
  132. class conditioning with `class_embed_type` equal to `None`.
  133. time_embedding_type (`str`, *optional*, defaults to `positional`):
  134. The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
  135. time_embedding_dim (`int`, *optional*, defaults to `None`):
  136. An optional override for the dimension of the projected time embedding.
  137. time_embedding_act_fn (`str`, *optional*, defaults to `None`):
  138. Optional activation function to use only once on the time embeddings before they are passed to the rest of
  139. the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
  140. timestep_post_act (`str`, *optional*, defaults to `None`):
  141. The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
  142. time_cond_proj_dim (`int`, *optional*, defaults to `None`):
  143. The dimension of `cond_proj` layer in the timestep embedding.
  144. conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`,
  145. *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`,
  146. *optional*): The dimension of the `class_labels` input when
  147. `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
  148. class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
  149. embeddings with the class embeddings.
  150. mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
  151. Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
  152. `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
  153. `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
  154. otherwise.
  155. """
  156. _supports_gradient_checkpointing = True
  157. @register_to_config
  158. def __init__(
  159. self,
  160. sample_size: Optional[int] = None,
  161. in_channels: int = 4,
  162. out_channels: int = 4,
  163. center_input_sample: bool = False,
  164. flip_sin_to_cos: bool = True,
  165. freq_shift: int = 0,
  166. down_block_types: Tuple[str] = (
  167. "CrossAttnDownBlock2D",
  168. "CrossAttnDownBlock2D",
  169. "CrossAttnDownBlock2D",
  170. "DownBlock2D",
  171. ),
  172. mid_block_type: Optional[str] = "UNetMidBlock2D",
  173. up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
  174. only_cross_attention: Union[bool, Tuple[bool]] = False,
  175. block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
  176. layers_per_block: Union[int, Tuple[int]] = 2,
  177. downsample_padding: int = 1,
  178. mid_block_scale_factor: float = 1,
  179. dropout: float = 0.0,
  180. act_fn: str = "silu",
  181. norm_num_groups: Optional[int] = 32,
  182. norm_eps: float = 1e-5,
  183. cross_attention_dim: Union[int, Tuple[int]] = 1280,
  184. transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
  185. reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
  186. encoder_hid_dim: Optional[int] = None,
  187. encoder_hid_dim_type: Optional[str] = None,
  188. attention_head_dim: Union[int, Tuple[int]] = 8,
  189. num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
  190. dual_cross_attention: bool = False,
  191. use_linear_projection: bool = False,
  192. class_embed_type: Optional[str] = None,
  193. addition_embed_type: Optional[str] = None,
  194. addition_time_embed_dim: Optional[int] = None,
  195. num_class_embeds: Optional[int] = None,
  196. upcast_attention: bool = False,
  197. resnet_time_scale_shift: str = "default",
  198. resnet_skip_time_act: bool = False,
  199. resnet_out_scale_factor: int = 1.0,
  200. time_embedding_type: str = "positional",
  201. time_embedding_dim: Optional[int] = None,
  202. time_embedding_act_fn: Optional[str] = None,
  203. timestep_post_act: Optional[str] = None,
  204. time_cond_proj_dim: Optional[int] = None,
  205. conv_in_kernel: int = 3,
  206. conv_out_kernel: int = 3,
  207. projection_class_embeddings_input_dim: Optional[int] = None,
  208. attention_type: str = "default",
  209. class_embeddings_concat: bool = False,
  210. mid_block_only_cross_attention: Optional[bool] = None,
  211. cross_attention_norm: Optional[str] = None,
  212. addition_embed_type_num_heads=64,
  213. return_deep_fea=False,
  214. ):
  215. super().__init__()
  216. self.return_deep_fea = return_deep_fea
  217. self.sample_size = sample_size
  218. if num_attention_heads is not None:
  219. raise ValueError(
  220. "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."
  221. )
  222. # If `num_attention_heads` is not defined (which is the case for most models)
  223. # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
  224. # The reason for this behavior is to correct for incorrectly named variables that were introduced
  225. # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
  226. # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
  227. # which is why we correct for the naming here.
  228. num_attention_heads = num_attention_heads or attention_head_dim
  229. # Check inputs
  230. if len(down_block_types) != len(up_block_types):
  231. raise ValueError(
  232. 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}."
  233. )
  234. if len(block_out_channels) != len(down_block_types):
  235. raise ValueError(
  236. 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}."
  237. )
  238. if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
  239. raise ValueError(
  240. 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}."
  241. )
  242. if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
  243. raise ValueError(
  244. 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}."
  245. )
  246. if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
  247. raise ValueError(
  248. f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
  249. )
  250. if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
  251. raise ValueError(
  252. f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
  253. )
  254. if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
  255. raise ValueError(
  256. f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
  257. )
  258. if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:
  259. for layer_number_per_block in transformer_layers_per_block:
  260. if isinstance(layer_number_per_block, list):
  261. raise ValueError("Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.")
  262. # input
  263. conv_in_padding = (conv_in_kernel - 1) // 2
  264. self.conv_in = nn.Conv2d(
  265. in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
  266. )
  267. # time
  268. if time_embedding_type == "fourier":
  269. time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
  270. if time_embed_dim % 2 != 0:
  271. raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
  272. self.time_proj = GaussianFourierProjection(
  273. time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
  274. )
  275. timestep_input_dim = time_embed_dim
  276. elif time_embedding_type == "positional":
  277. time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
  278. self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
  279. timestep_input_dim = block_out_channels[0]
  280. else:
  281. raise ValueError(
  282. f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
  283. )
  284. self.time_embedding = TimestepEmbedding(
  285. timestep_input_dim,
  286. time_embed_dim,
  287. act_fn=act_fn,
  288. post_act_fn=timestep_post_act,
  289. cond_proj_dim=time_cond_proj_dim,
  290. )
  291. if encoder_hid_dim_type is None and encoder_hid_dim is not None:
  292. encoder_hid_dim_type = "text_proj"
  293. self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
  294. logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
  295. if encoder_hid_dim is None and encoder_hid_dim_type is not None:
  296. raise ValueError(
  297. f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
  298. )
  299. if encoder_hid_dim_type == "text_proj":
  300. self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
  301. elif encoder_hid_dim_type == "text_image_proj":
  302. # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
  303. # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
  304. # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
  305. self.encoder_hid_proj = TextImageProjection(
  306. text_embed_dim=encoder_hid_dim,
  307. image_embed_dim=cross_attention_dim,
  308. cross_attention_dim=cross_attention_dim,
  309. )
  310. elif encoder_hid_dim_type == "image_proj":
  311. # Kandinsky 2.2
  312. self.encoder_hid_proj = ImageProjection(
  313. image_embed_dim=encoder_hid_dim,
  314. cross_attention_dim=cross_attention_dim,
  315. )
  316. elif encoder_hid_dim_type is not None:
  317. raise ValueError(
  318. f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
  319. )
  320. else:
  321. self.encoder_hid_proj = None
  322. # class embedding
  323. if class_embed_type is None and num_class_embeds is not None:
  324. self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
  325. elif class_embed_type == "timestep":
  326. self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
  327. elif class_embed_type == "identity":
  328. self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
  329. elif class_embed_type == "projection":
  330. if projection_class_embeddings_input_dim is None:
  331. raise ValueError(
  332. "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
  333. )
  334. # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
  335. # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
  336. # 2. it projects from an arbitrary input dimension.
  337. #
  338. # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
  339. # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
  340. # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
  341. self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
  342. elif class_embed_type == "simple_projection":
  343. if projection_class_embeddings_input_dim is None:
  344. raise ValueError(
  345. "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
  346. )
  347. self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
  348. else:
  349. self.class_embedding = None
  350. if addition_embed_type == "text":
  351. if encoder_hid_dim is not None:
  352. text_time_embedding_from_dim = encoder_hid_dim
  353. else:
  354. text_time_embedding_from_dim = cross_attention_dim
  355. self.add_embedding = TextTimeEmbedding(
  356. text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
  357. )
  358. elif addition_embed_type == "text_image":
  359. # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
  360. # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
  361. # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
  362. self.add_embedding = TextImageTimeEmbedding(
  363. text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
  364. )
  365. elif addition_embed_type == "text_time":
  366. self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
  367. self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
  368. elif addition_embed_type == "image":
  369. # Kandinsky 2.2
  370. self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
  371. elif addition_embed_type == "image_hint":
  372. # Kandinsky 2.2 ControlNet
  373. self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
  374. elif addition_embed_type is not None:
  375. raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
  376. if time_embedding_act_fn is None:
  377. self.time_embed_act = None
  378. else:
  379. self.time_embed_act = get_activation(time_embedding_act_fn)
  380. self.down_blocks = nn.ModuleList([])
  381. self.up_blocks = nn.ModuleList([])
  382. if isinstance(only_cross_attention, bool):
  383. if mid_block_only_cross_attention is None:
  384. mid_block_only_cross_attention = only_cross_attention
  385. only_cross_attention = [only_cross_attention] * len(down_block_types)
  386. if mid_block_only_cross_attention is None:
  387. mid_block_only_cross_attention = False
  388. if isinstance(num_attention_heads, int):
  389. num_attention_heads = (num_attention_heads,) * len(down_block_types)
  390. if isinstance(attention_head_dim, int):
  391. attention_head_dim = (attention_head_dim,) * len(down_block_types)
  392. if isinstance(cross_attention_dim, int):
  393. cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
  394. if isinstance(layers_per_block, int):
  395. layers_per_block = [layers_per_block] * len(down_block_types)
  396. if isinstance(transformer_layers_per_block, int):
  397. transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
  398. if class_embeddings_concat:
  399. # The time embeddings are concatenated with the class embeddings. The dimension of the
  400. # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
  401. # regular time embeddings
  402. blocks_time_embed_dim = time_embed_dim * 2
  403. else:
  404. blocks_time_embed_dim = time_embed_dim
  405. # down
  406. output_channel = block_out_channels[0]
  407. for i, down_block_type in enumerate(down_block_types):
  408. input_channel = output_channel
  409. output_channel = block_out_channels[i]
  410. is_final_block = i == len(block_out_channels) - 1
  411. down_block = get_down_block(
  412. down_block_type,
  413. num_layers=layers_per_block[i],
  414. transformer_layers_per_block=transformer_layers_per_block[i],
  415. in_channels=input_channel,
  416. out_channels=output_channel,
  417. temb_channels=blocks_time_embed_dim,
  418. add_downsample=not is_final_block,
  419. resnet_eps=norm_eps,
  420. resnet_act_fn=act_fn,
  421. resnet_groups=norm_num_groups,
  422. cross_attention_dim=cross_attention_dim[i],
  423. num_attention_heads=num_attention_heads[i],
  424. downsample_padding=downsample_padding,
  425. dual_cross_attention=dual_cross_attention,
  426. use_linear_projection=use_linear_projection,
  427. only_cross_attention=only_cross_attention[i],
  428. upcast_attention=upcast_attention,
  429. resnet_time_scale_shift=resnet_time_scale_shift,
  430. attention_type=attention_type,
  431. resnet_skip_time_act=resnet_skip_time_act,
  432. resnet_out_scale_factor=resnet_out_scale_factor,
  433. cross_attention_norm=cross_attention_norm,
  434. attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
  435. dropout=dropout,
  436. )
  437. self.down_blocks.append(down_block)
  438. if not self.return_deep_fea:
  439. # mid
  440. if mid_block_type == "UNetMidBlock2DCrossAttn":
  441. self.mid_block = UNetMidBlock2DCrossAttn(
  442. transformer_layers_per_block=transformer_layers_per_block[-1],
  443. in_channels=block_out_channels[-1],
  444. temb_channels=blocks_time_embed_dim,
  445. dropout=dropout,
  446. resnet_eps=norm_eps,
  447. resnet_act_fn=act_fn,
  448. output_scale_factor=mid_block_scale_factor,
  449. resnet_time_scale_shift=resnet_time_scale_shift,
  450. cross_attention_dim=cross_attention_dim[-1],
  451. num_attention_heads=num_attention_heads[-1],
  452. resnet_groups=norm_num_groups,
  453. dual_cross_attention=dual_cross_attention,
  454. use_linear_projection=use_linear_projection,
  455. upcast_attention=upcast_attention,
  456. attention_type=attention_type,
  457. )
  458. elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
  459. self.mid_block = UNetMidBlock2DSimpleCrossAttn(
  460. in_channels=block_out_channels[-1],
  461. temb_channels=blocks_time_embed_dim,
  462. dropout=dropout,
  463. resnet_eps=norm_eps,
  464. resnet_act_fn=act_fn,
  465. output_scale_factor=mid_block_scale_factor,
  466. cross_attention_dim=cross_attention_dim[-1],
  467. attention_head_dim=attention_head_dim[-1],
  468. resnet_groups=norm_num_groups,
  469. resnet_time_scale_shift=resnet_time_scale_shift,
  470. skip_time_act=resnet_skip_time_act,
  471. only_cross_attention=mid_block_only_cross_attention,
  472. cross_attention_norm=cross_attention_norm,
  473. )
  474. elif mid_block_type == "UNetMidBlock2D":
  475. self.mid_block = UNetMidBlock2D(
  476. in_channels=block_out_channels[-1],
  477. temb_channels=blocks_time_embed_dim,
  478. dropout=dropout,
  479. # num_layers=0,
  480. resnet_eps=norm_eps,
  481. resnet_act_fn=act_fn,
  482. output_scale_factor=mid_block_scale_factor,
  483. resnet_groups=norm_num_groups,
  484. resnet_time_scale_shift=resnet_time_scale_shift,
  485. attn_groups=None,
  486. #
  487. add_attention=True,
  488. attention_head_dim=attention_head_dim[-1] if attention_head_dim is not None else block_out_channels[-1],
  489. )
  490. elif mid_block_type is None:
  491. self.mid_block = None
  492. else:
  493. raise ValueError(f"unknown mid_block_type : {mid_block_type}")
  494. # count how many layers upsample the images
  495. self.num_upsamplers = 0
  496. # up
  497. reversed_block_out_channels = list(reversed(block_out_channels))
  498. reversed_num_attention_heads = list(reversed(num_attention_heads))
  499. reversed_layers_per_block = list(reversed(layers_per_block))
  500. reversed_cross_attention_dim = list(reversed(cross_attention_dim))
  501. reversed_transformer_layers_per_block = (
  502. list(reversed(transformer_layers_per_block))
  503. if reverse_transformer_layers_per_block is None
  504. else reverse_transformer_layers_per_block
  505. )
  506. only_cross_attention = list(reversed(only_cross_attention))
  507. output_channel = reversed_block_out_channels[0]
  508. for i, up_block_type in enumerate(up_block_types):
  509. is_final_block = i == len(block_out_channels) - 1
  510. prev_output_channel = output_channel
  511. output_channel = reversed_block_out_channels[i]
  512. input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
  513. # add upsample block for all BUT final layer
  514. if not is_final_block:
  515. add_upsample = True
  516. self.num_upsamplers += 1
  517. else:
  518. add_upsample = False
  519. up_block = get_up_block(
  520. up_block_type,
  521. num_layers=reversed_layers_per_block[i] + 1,
  522. transformer_layers_per_block=reversed_transformer_layers_per_block[i],
  523. in_channels=input_channel,
  524. out_channels=output_channel,
  525. prev_output_channel=prev_output_channel,
  526. temb_channels=blocks_time_embed_dim,
  527. add_upsample=add_upsample,
  528. resnet_eps=norm_eps,
  529. resnet_act_fn=act_fn,
  530. resolution_idx=i,
  531. resnet_groups=norm_num_groups,
  532. cross_attention_dim=reversed_cross_attention_dim[i],
  533. num_attention_heads=reversed_num_attention_heads[i],
  534. dual_cross_attention=dual_cross_attention,
  535. use_linear_projection=use_linear_projection,
  536. only_cross_attention=only_cross_attention[i],
  537. upcast_attention=upcast_attention,
  538. resnet_time_scale_shift=resnet_time_scale_shift,
  539. attention_type=attention_type,
  540. resnet_skip_time_act=resnet_skip_time_act,
  541. resnet_out_scale_factor=resnet_out_scale_factor,
  542. cross_attention_norm=cross_attention_norm,
  543. attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
  544. dropout=dropout,
  545. )
  546. self.up_blocks.append(up_block)
  547. prev_output_channel = output_channel
  548. # out
  549. if norm_num_groups is not None:
  550. self.conv_norm_out = nn.GroupNorm(
  551. num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
  552. )
  553. self.conv_act = get_activation(act_fn)
  554. else:
  555. self.conv_norm_out = None
  556. self.conv_act = None
  557. conv_out_padding = (conv_out_kernel - 1) // 2
  558. self.conv_out = nn.Conv2d(
  559. block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
  560. )
  561. if attention_type in ["gated", "gated-text-image"]:
  562. positive_len = 768
  563. if isinstance(cross_attention_dim, int):
  564. positive_len = cross_attention_dim
  565. elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list):
  566. positive_len = cross_attention_dim[0]
  567. feature_type = "text-only" if attention_type == "gated" else "text-image"
  568. self.position_net = PositionNet(
  569. positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type
  570. )
  571. @property
  572. def attn_processors(self) -> Dict[str, AttentionProcessor]:
  573. r"""
  574. Returns:
  575. `dict` of attention processors: A dictionary containing all attention processors used in the model with
  576. indexed by its weight name.
  577. """
  578. # set recursively
  579. processors = {}
  580. def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
  581. if hasattr(module, "get_processor"):
  582. processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
  583. for sub_name, child in module.named_children():
  584. fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
  585. return processors
  586. for name, module in self.named_children():
  587. fn_recursive_add_processors(name, module, processors)
  588. return processors
  589. def set_attn_processor(
  590. self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
  591. ):
  592. r"""
  593. Sets the attention processor to use to compute attention.
  594. Parameters:
  595. processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
  596. The instantiated processor class or a dictionary of processor classes that will be set as the processor
  597. for **all** `Attention` layers.
  598. If `processor` is a dict, the key needs to define the path to the corresponding cross attention
  599. processor. This is strongly recommended when setting trainable attention processors.
  600. """
  601. count = len(self.attn_processors.keys())
  602. if isinstance(processor, dict) and len(processor) != count:
  603. raise ValueError(
  604. f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
  605. f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
  606. )
  607. def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
  608. if hasattr(module, "set_processor"):
  609. if not isinstance(processor, dict):
  610. module.set_processor(processor, _remove_lora=_remove_lora)
  611. else:
  612. module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
  613. for sub_name, child in module.named_children():
  614. fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
  615. for name, module in self.named_children():
  616. fn_recursive_attn_processor(name, module, processor)
  617. def set_default_attn_processor(self):
  618. """
  619. Disables custom attention processors and sets the default attention implementation.
  620. """
  621. if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
  622. processor = AttnAddedKVProcessor()
  623. elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
  624. processor = AttnProcessor()
  625. else:
  626. raise ValueError(
  627. f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
  628. )
  629. self.set_attn_processor(processor, _remove_lora=True)
  630. def set_attention_slice(self, slice_size):
  631. r"""
  632. Enable sliced attention computation.
  633. When this option is enabled, the attention module splits the input tensor in slices to compute attention in
  634. several steps. This is useful for saving some memory in exchange for a small decrease in speed.
  635. Args:
  636. slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
  637. When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
  638. `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
  639. provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
  640. must be a multiple of `slice_size`.
  641. """
  642. sliceable_head_dims = []
  643. def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
  644. if hasattr(module, "set_attention_slice"):
  645. sliceable_head_dims.append(module.sliceable_head_dim)
  646. for child in module.children():
  647. fn_recursive_retrieve_sliceable_dims(child)
  648. # retrieve number of attention layers
  649. for module in self.children():
  650. fn_recursive_retrieve_sliceable_dims(module)
  651. num_sliceable_layers = len(sliceable_head_dims)
  652. if slice_size == "auto":
  653. # half the attention head size is usually a good trade-off between
  654. # speed and memory
  655. slice_size = [dim // 2 for dim in sliceable_head_dims]
  656. elif slice_size == "max":
  657. # make smallest slice possible
  658. slice_size = num_sliceable_layers * [1]
  659. slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
  660. if len(slice_size) != len(sliceable_head_dims):
  661. raise ValueError(
  662. f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
  663. f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
  664. )
  665. for i in range(len(slice_size)):
  666. size = slice_size[i]
  667. dim = sliceable_head_dims[i]
  668. if size is not None and size > dim:
  669. raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
  670. # Recursively walk through all the children.
  671. # Any children which exposes the set_attention_slice method
  672. # gets the message
  673. def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
  674. if hasattr(module, "set_attention_slice"):
  675. module.set_attention_slice(slice_size.pop())
  676. for child in module.children():
  677. fn_recursive_set_attention_slice(child, slice_size)
  678. reversed_slice_size = list(reversed(slice_size))
  679. for module in self.children():
  680. fn_recursive_set_attention_slice(module, reversed_slice_size)
  681. def _set_gradient_checkpointing(self, module, value=False):
  682. if hasattr(module, "gradient_checkpointing"):
  683. module.gradient_checkpointing = value
  684. def enable_freeu(self, s1, s2, b1, b2):
  685. r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
  686. The suffixes after the scaling factors represent the stage blocks where they are being applied.
  687. Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
  688. are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
  689. Args:
  690. s1 (`float`):
  691. Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
  692. mitigate the "oversmoothing effect" in the enhanced denoising process.
  693. s2 (`float`):
  694. Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
  695. mitigate the "oversmoothing effect" in the enhanced denoising process.
  696. b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
  697. b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
  698. """
  699. for i, upsample_block in enumerate(self.up_blocks):
  700. setattr(upsample_block, "s1", s1)
  701. setattr(upsample_block, "s2", s2)
  702. setattr(upsample_block, "b1", b1)
  703. setattr(upsample_block, "b2", b2)
  704. def disable_freeu(self):
  705. """Disables the FreeU mechanism."""
  706. freeu_keys = {"s1", "s2", "b1", "b2"}
  707. for i, upsample_block in enumerate(self.up_blocks):
  708. for k in freeu_keys:
  709. if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
  710. setattr(upsample_block, k, None)
  711. def forward(
  712. self,
  713. sample: torch.FloatTensor,
  714. timestep: Union[torch.Tensor, float, int],
  715. encoder_hidden_states: torch.Tensor,
  716. class_labels: Optional[torch.Tensor] = None,
  717. timestep_cond: Optional[torch.Tensor] = None,
  718. attention_mask: Optional[torch.Tensor] = None,
  719. cross_attention_kwargs: Optional[Dict[str, Any]] = None,
  720. added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
  721. down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
  722. mid_block_additional_residual: Optional[torch.Tensor] = None,
  723. down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
  724. encoder_attention_mask: Optional[torch.Tensor] = None,
  725. return_dict: bool = True,
  726. ) -> Union[UNet2DConditionOutput, Tuple]:
  727. r"""
  728. The [`UNet2DConditionModel`] forward method.
  729. Args:
  730. sample (`torch.FloatTensor`):
  731. The noisy input tensor with the following shape `(batch, channel, height, width)`.
  732. timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
  733. encoder_hidden_states (`torch.FloatTensor`):
  734. The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
  735. class_labels (`torch.Tensor`, *optional*, defaults to `None`):
  736. Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
  737. timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
  738. Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
  739. through the `self.time_embedding` layer to obtain the timestep embeddings.
  740. attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
  741. An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
  742. is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
  743. negative values to the attention scores corresponding to "discard" tokens.
  744. cross_attention_kwargs (`dict`, *optional*):
  745. A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
  746. `self.processor` in
  747. [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
  748. added_cond_kwargs: (`dict`, *optional*):
  749. A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
  750. are passed along to the UNet blocks.
  751. down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
  752. A tuple of tensors that if specified are added to the residuals of down unet blocks.
  753. mid_block_additional_residual: (`torch.Tensor`, *optional*):
  754. A tensor that if specified is added to the residual of the middle unet block.
  755. encoder_attention_mask (`torch.Tensor`):
  756. A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
  757. `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
  758. which adds large negative values to the attention scores corresponding to "discard" tokens.
  759. return_dict (`bool`, *optional*, defaults to `True`):
  760. Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
  761. tuple.
  762. cross_attention_kwargs (`dict`, *optional*):
  763. A kwargs dictionary that if specified is passed along to the [`AttnProcessor`].
  764. added_cond_kwargs: (`dict`, *optional*):
  765. A kwargs dictionary containin additional embeddings that if specified are added to the embeddings that
  766. are passed along to the UNet blocks.
  767. down_block_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
  768. additional residuals to be added to UNet long skip connections from down blocks to up blocks for
  769. example from ControlNet side model(s)
  770. mid_block_additional_residual (`torch.Tensor`, *optional*):
  771. additional residual to be added to UNet mid block output, for example from ControlNet side model
  772. down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
  773. additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
  774. Returns:
  775. [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
  776. If `return_dict` is True, an [`~models.unet_2d_condition.UNet2DConditionOutput`] is returned, otherwise
  777. a `tuple` is returned where the first element is the sample tensor.
  778. """
  779. # By default samples have to be AT least a multiple of the overall upsampling factor.
  780. # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
  781. # However, the upsampling interpolation output size can be forced to fit any upsampling size
  782. # on the fly if necessary.
  783. if not self.return_deep_fea:
  784. default_overall_up_factor = 2**self.num_upsamplers
  785. # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
  786. forward_upsample_size = False
  787. upsample_size = None
  788. for dim in sample.shape[-2:]:
  789. if dim % default_overall_up_factor != 0:
  790. # Forward upsample size to force interpolation output size.
  791. forward_upsample_size = True
  792. break
  793. # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
  794. # expects mask of shape:
  795. # [batch, key_tokens]
  796. # adds singleton query_tokens dimension:
  797. # [batch, 1, key_tokens]
  798. # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
  799. # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
  800. # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
  801. if attention_mask is not None:
  802. # assume that mask is expressed as:
  803. # (1 = keep, 0 = discard)
  804. # convert mask into a bias that can be added to attention scores:
  805. # (keep = +0, discard = -10000.0)
  806. attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
  807. attention_mask = attention_mask.unsqueeze(1)
  808. # convert encoder_attention_mask to a bias the same way we do for attention_mask
  809. if encoder_attention_mask is not None:
  810. encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
  811. encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
  812. # 0. center input if necessary
  813. if self.config.center_input_sample:
  814. sample = 2 * sample - 1.0
  815. # 1. time
  816. timesteps = timestep
  817. if not torch.is_tensor(timesteps):
  818. # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
  819. # This would be a good case for the `match` statement (Python 3.10+)
  820. is_mps = sample.device.type == "mps"
  821. if isinstance(timestep, float):
  822. dtype = torch.float32 if is_mps else torch.float64
  823. else:
  824. dtype = torch.int32 if is_mps else torch.int64
  825. timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
  826. elif len(timesteps.shape) == 0:
  827. timesteps = timesteps[None].to(sample.device)
  828. # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
  829. timesteps = timesteps.expand(sample.shape[0])
  830. t_emb = self.time_proj(timesteps)
  831. # `Timesteps` does not contain any weights and will always return f32 tensors
  832. # but time_embedding might actually be running in fp16. so we need to cast here.
  833. # there might be better ways to encapsulate this.
  834. t_emb = t_emb.to(dtype=sample.dtype)
  835. emb = self.time_embedding(t_emb, timestep_cond)
  836. aug_emb = None
  837. if self.class_embedding is not None:
  838. if class_labels is None:
  839. raise ValueError("class_labels should be provided when num_class_embeds > 0")
  840. if self.config.class_embed_type == "timestep":
  841. class_labels = self.time_proj(class_labels)
  842. # `Timesteps` does not contain any weights and will always return f32 tensors
  843. # there might be better ways to encapsulate this.
  844. class_labels = class_labels.to(dtype=sample.dtype)
  845. class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
  846. if self.config.class_embeddings_concat:
  847. emb = torch.cat([emb, class_emb], dim=-1)
  848. else:
  849. emb = emb + class_emb
  850. if self.config.addition_embed_type == "text":
  851. aug_emb = self.add_embedding(encoder_hidden_states)
  852. elif self.config.addition_embed_type == "text_image":
  853. # Kandinsky 2.1 - style
  854. if "image_embeds" not in added_cond_kwargs:
  855. raise ValueError(
  856. f"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
  857. )
  858. image_embs = added_cond_kwargs.get("image_embeds")
  859. text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
  860. aug_emb = self.add_embedding(text_embs, image_embs)
  861. elif self.config.addition_embed_type == "text_time":
  862. # SDXL - style
  863. if "text_embeds" not in added_cond_kwargs:
  864. raise ValueError(
  865. 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`"
  866. )
  867. text_embeds = added_cond_kwargs.get("text_embeds")
  868. if "time_ids" not in added_cond_kwargs:
  869. raise ValueError(
  870. 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`"
  871. )
  872. time_ids = added_cond_kwargs.get("time_ids")
  873. time_embeds = self.add_time_proj(time_ids.flatten())
  874. time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
  875. add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
  876. add_embeds = add_embeds.to(emb.dtype)
  877. aug_emb = self.add_embedding(add_embeds)
  878. elif self.config.addition_embed_type == "image":
  879. # Kandinsky 2.2 - style
  880. if "image_embeds" not in added_cond_kwargs:
  881. raise ValueError(
  882. f"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
  883. )
  884. image_embs = added_cond_kwargs.get("image_embeds")
  885. aug_emb = self.add_embedding(image_embs)
  886. elif self.config.addition_embed_type == "image_hint":
  887. # Kandinsky 2.2 - style
  888. if "image_embeds" not in added_cond_kwargs or "hint" not in added_cond_kwargs:
  889. raise ValueError(
  890. f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`"
  891. )
  892. image_embs = added_cond_kwargs.get("image_embeds")
  893. hint = added_cond_kwargs.get("hint")
  894. aug_emb, hint = self.add_embedding(image_embs, hint)
  895. sample = torch.cat([sample, hint], dim=1)
  896. emb = emb + aug_emb if aug_emb is not None else emb
  897. if self.time_embed_act is not None:
  898. emb = self.time_embed_act(emb)
  899. if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
  900. encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
  901. elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
  902. # Kadinsky 2.1 - style
  903. if "image_embeds" not in added_cond_kwargs:
  904. raise ValueError(
  905. f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
  906. )
  907. image_embeds = added_cond_kwargs.get("image_embeds")
  908. encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
  909. elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
  910. # Kandinsky 2.2 - style
  911. if "image_embeds" not in added_cond_kwargs:
  912. raise ValueError(
  913. f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
  914. )
  915. image_embeds = added_cond_kwargs.get("image_embeds")
  916. encoder_hidden_states = self.encoder_hid_proj(image_embeds)
  917. # 2. pre-process
  918. sample = self.conv_in(sample)
  919. # 2.5 GLIGEN position net
  920. if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
  921. cross_attention_kwargs = cross_attention_kwargs.copy()
  922. gligen_args = cross_attention_kwargs.pop("gligen")
  923. cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
  924. # 3. down
  925. lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
  926. if USE_PEFT_BACKEND:
  927. # weight the lora layers by setting `lora_scale` for each PEFT layer
  928. scale_lora_layers(self, lora_scale)
  929. is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
  930. # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
  931. is_adapter = down_intrablock_additional_residuals is not None
  932. # maintain backward compatibility for legacy usage, where
  933. # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
  934. # but can only use one or the other
  935. if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
  936. deprecate(
  937. "T2I should not use down_block_additional_residuals",
  938. "1.3.0",
  939. "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
  940. and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
  941. for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
  942. standard_warn=False,
  943. )
  944. down_intrablock_additional_residuals = down_block_additional_residuals
  945. is_adapter = True
  946. down_block_res_samples = (sample,)
  947. for downsample_block in self.down_blocks:
  948. if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
  949. # For t2i-adapter CrossAttnDownBlock2D
  950. additional_residuals = {}
  951. if is_adapter and len(down_intrablock_additional_residuals) > 0:
  952. additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
  953. sample, res_samples = downsample_block(
  954. hidden_states=sample,
  955. temb=emb,
  956. encoder_hidden_states=encoder_hidden_states,
  957. attention_mask=attention_mask,
  958. cross_attention_kwargs=cross_attention_kwargs,
  959. encoder_attention_mask=encoder_attention_mask,
  960. **additional_residuals,
  961. )
  962. else:
  963. sample, res_samples = downsample_block(hidden_states=sample, temb=emb, scale=lora_scale)
  964. if is_adapter and len(down_intrablock_additional_residuals) > 0:
  965. sample += down_intrablock_additional_residuals.pop(0)
  966. down_block_res_samples += res_samples
  967. if is_controlnet:
  968. new_down_block_res_samples = ()
  969. for down_block_res_sample, down_block_additional_residual in zip(
  970. down_block_res_samples, down_block_additional_residuals
  971. ):
  972. down_block_res_sample = down_block_res_sample + down_block_additional_residual
  973. new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
  974. down_block_res_samples = new_down_block_res_samples
  975. if self.return_deep_fea:
  976. return sample
  977. # 4. mid
  978. if self.mid_block is not None:
  979. if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
  980. sample = self.mid_block(
  981. sample,
  982. emb,
  983. encoder_hidden_states=encoder_hidden_states,
  984. attention_mask=attention_mask,
  985. cross_attention_kwargs=cross_attention_kwargs,
  986. encoder_attention_mask=encoder_attention_mask,
  987. )
  988. else:
  989. sample = self.mid_block(sample, emb)
  990. # To support T2I-Adapter-XL
  991. if (
  992. is_adapter
  993. and len(down_intrablock_additional_residuals) > 0
  994. and sample.shape == down_intrablock_additional_residuals[0].shape
  995. ):
  996. sample += down_intrablock_additional_residuals.pop(0)
  997. if is_controlnet:
  998. sample = sample + mid_block_additional_residual
  999. # 5. up
  1000. for i, upsample_block in enumerate(self.up_blocks):
  1001. is_final_block = i == len(self.up_blocks) - 1
  1002. res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
  1003. down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
  1004. # if we have not reached the final block and need to forward the
  1005. # upsample size, we do it here
  1006. if not is_final_block and forward_upsample_size:
  1007. upsample_size = down_block_res_samples[-1].shape[2:]
  1008. if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
  1009. sample = upsample_block(
  1010. hidden_states=sample,
  1011. temb=emb,
  1012. res_hidden_states_tuple=res_samples,
  1013. encoder_hidden_states=encoder_hidden_states,
  1014. cross_attention_kwargs=cross_attention_kwargs,
  1015. upsample_size=upsample_size,
  1016. attention_mask=attention_mask,
  1017. encoder_attention_mask=encoder_attention_mask,
  1018. )
  1019. else:
  1020. sample = upsample_block(
  1021. hidden_states=sample,
  1022. temb=emb,
  1023. res_hidden_states_tuple=res_samples,
  1024. upsample_size=upsample_size,
  1025. scale=lora_scale,
  1026. )
  1027. # 6. post-process
  1028. if self.conv_norm_out:
  1029. sample = self.conv_norm_out(sample)
  1030. sample = self.conv_act(sample)
  1031. sample = self.conv_out(sample)
  1032. if USE_PEFT_BACKEND:
  1033. # remove `lora_scale` from each PEFT layer
  1034. unscale_lora_layers(self, lora_scale)
  1035. if not return_dict:
  1036. return (sample,)
  1037. return UNet2DConditionOutput(sample=sample)
  1038. class CLIPDDPM_2D(nn.Module):
  1039. '''
  1040. Wrapper to extract features from pretrained DDPMs.
  1041. :param steps: list of diffusion steps t.
  1042. :param blocks: list of the UNet decoder blocks.
  1043. '''
  1044. def __init__(self, model_path, num_cls=2, steps=[0], seq_len=1, clip_train=True):
  1045. super().__init__()
  1046. self.steps = steps
  1047. self._load_pretrained_model(model_path)
  1048. self.clip_train = clip_train
  1049. if not self.clip_train:
  1050. self.fc = nn.Linear(768, num_cls)
  1051. torch.nn.init.xavier_uniform_(self.fc.weight)
  1052. self.conv = nn.Conv2d(512*seq_len, 768, 3)
  1053. torch.nn.init.xavier_uniform_(self.conv.weight)
  1054. self.act = nn.ReLU()
  1055. self.avg = nn.AdaptiveAvgPool2d((1,1))
  1056. self.seq_len = seq_len
  1057. def _load_pretrained_model(self, model_path):
  1058. from diffusers import DDPMScheduler
  1059. self.noise_scheduler = DDPMScheduler(num_train_timesteps=1000)
  1060. # Needed to pass only expected args to the function
  1061. self.model = UNet2DConditionModel(
  1062. sample_size=256, # the target image resolution
  1063. in_channels=3, # the number of input channels, 3 for RGB images
  1064. out_channels=3, # the number of output channels
  1065. layers_per_block=2, # how many ResNet layers to use per UNet block
  1066. block_out_channels=(64, 64, 128, 256, 512), # the number of output channels for each UNet block
  1067. down_block_types=(
  1068. "DownBlock2D",
  1069. "CrossAttnDownBlock2D",
  1070. "CrossAttnDownBlock2D",
  1071. "CrossAttnDownBlock2D",
  1072. "DownBlock2D",
  1073. ),
  1074. up_block_types=(
  1075. "UpBlock2D",
  1076. "CrossAttnUpBlock2D",
  1077. "CrossAttnUpBlock2D",
  1078. "CrossAttnUpBlock2D",
  1079. "UpBlock2D",
  1080. ),
  1081. norm_num_groups=32,
  1082. # addition_embed_type="text",
  1083. # addition_embed_type_num_heads=64,
  1084. encoder_hid_dim_type="text_proj",
  1085. encoder_hid_dim=768,
  1086. )
  1087. self.model.eval()
  1088. # @torch.no_grad()
  1089. def forward(self, x, encoder_hidden_states):
  1090. noise = torch.randn(x.shape).to(x.device)
  1091. activations = []
  1092. input_with_noise = []
  1093. t = self.steps[0]
  1094. for i in range(self.seq_len):
  1095. # Compute x_t and run DDPM
  1096. t = torch.tensor([t]).to(x.device).long()
  1097. noisy_x = self.noise_scheduler.add_noise(x, noise, t)
  1098. # input_with_noise.append(noisy_x)
  1099. direct_out = self.model(noisy_x, t, encoder_hidden_states=encoder_hidden_states)
  1100. # return sample
  1101. activations.append(direct_out)
  1102. del(noise)
  1103. del(noisy_x)
  1104. first = torch.cat(activations, dim=1)
  1105. first = self.conv(first)
  1106. first = self.act(first)
  1107. outputs = self.avg(first.contiguous())
  1108. outputs = torch.flatten(outputs, 1)
  1109. if self.clip_train:
  1110. return outputs
  1111. outputs = torch.nn.functional.dropout(outputs, p=0.5)
  1112. outputs = self.fc(outputs.contiguous())
  1113. return outputs
  1114. class CLIPDDPM_2D_CAM(nn.Module):
  1115. '''
  1116. Wrapper to extract features from pretrained DDPMs.
  1117. :param steps: list of diffusion steps t.
  1118. :param blocks: list of the UNet decoder blocks.
  1119. '''
  1120. def __init__(self, model_path, num_cls=2, steps=[0], seq_len=1, clip_train=True):
  1121. super().__init__()
  1122. self.steps = steps
  1123. self._load_pretrained_model(model_path)
  1124. self.clip_train = clip_train
  1125. if not self.clip_train:
  1126. self.fc = nn.Linear(768, num_cls)
  1127. torch.nn.init.xavier_uniform_(self.fc.weight)
  1128. self.conv = nn.Conv2d(512*seq_len, 768, 3)
  1129. torch.nn.init.xavier_uniform_(self.conv.weight)
  1130. self.act = nn.ReLU()
  1131. self.avg = nn.AdaptiveAvgPool2d((1,1))
  1132. self.seq_len = seq_len
  1133. # Grad-CAM storage
  1134. self.gradients = None
  1135. self.activations = None
  1136. def save_gradients(self, grad):
  1137. self.gradients = grad
  1138. def _load_pretrained_model(self, model_path):
  1139. from diffusers import DDPMScheduler
  1140. self.noise_scheduler = DDPMScheduler(num_train_timesteps=1000)
  1141. # Needed to pass only expected args to the function
  1142. self.model = UNet2DConditionModel(
  1143. sample_size=256, # the target image resolution
  1144. in_channels=3, # the number of input channels, 3 for RGB images
  1145. out_channels=3, # the number of output channels
  1146. layers_per_block=2, # how many ResNet layers to use per UNet block
  1147. block_out_channels=(64, 64, 128, 256, 512), # the number of output channels for each UNet block
  1148. down_block_types=(
  1149. "DownBlock2D",
  1150. "CrossAttnDownBlock2D",
  1151. "CrossAttnDownBlock2D",
  1152. "CrossAttnDownBlock2D",
  1153. "DownBlock2D",
  1154. ),
  1155. up_block_types=(
  1156. "UpBlock2D",
  1157. "CrossAttnUpBlock2D",
  1158. "CrossAttnUpBlock2D",
  1159. "CrossAttnUpBlock2D",
  1160. "UpBlock2D",
  1161. ),
  1162. norm_num_groups=32,
  1163. # addition_embed_type="text",
  1164. # addition_embed_type_num_heads=64,
  1165. encoder_hid_dim_type="text_proj",
  1166. encoder_hid_dim=768,
  1167. )
  1168. self.model.eval()
  1169. # @torch.no_grad()
  1170. def forward(self, x, encoder_hidden_states):
  1171. noise = torch.randn(x.shape).to(x.device)
  1172. activations = []
  1173. input_with_noise = []
  1174. t = self.steps[0]
  1175. for i in range(self.seq_len):
  1176. # Compute x_t and run DDPM
  1177. t = torch.tensor([t]).to(x.device).long()
  1178. noisy_x = self.noise_scheduler.add_noise(x, noise, t)
  1179. # input_with_noise.append(noisy_x)
  1180. direct_out = self.model(noisy_x, t, encoder_hidden_states=encoder_hidden_states)
  1181. # return sample
  1182. activations.append(direct_out)
  1183. del(noise)
  1184. del(noisy_x)
  1185. first = torch.cat(activations, dim=1)
  1186. # Register hooks for Grad-CAM
  1187. first.requires_grad_(True)
  1188. first.register_hook(self.save_gradients)
  1189. self.activations = first
  1190. first = self.conv(first)
  1191. first = self.act(first)
  1192. outputs = self.avg(first.contiguous())
  1193. outputs = torch.flatten(outputs, 1)
  1194. if self.clip_train:
  1195. return outputs
  1196. outputs = torch.nn.functional.dropout(outputs, p=0.5)
  1197. outputs = self.fc(outputs.contiguous())
  1198. return outputs
  1199. def generate_gradcam(self, x, encoder_hidden_states,loss_):
  1200. """Generate Grad-CAM for a specific class."""
  1201. x.requires_grad_(True)
  1202. output = self.forward(x, encoder_hidden_states)
  1203. # Backward
  1204. self.model.zero_grad()
  1205. loss_.backward()
  1206. '''# Compute Grad-CAM weights
  1207. gradients = self.gradients.detach().cpu().numpy()
  1208. activations = self.activations.detach().cpu().numpy()
  1209. # Global average pooling to compute weights
  1210. weights = np.mean(gradients, axis=(2, 3))
  1211. grad_cam = np.sum(weights[:, :, np.newaxis, np.newaxis] * activations, axis=1)
  1212. grad_cam = np.maximum(grad_cam, 0)
  1213. grad_cam = grad_cam[0]
  1214. # Normalize the Grad-CAM heatmap
  1215. grad_cam -= grad_cam.min()
  1216. grad_cam /= grad_cam.max()
  1217. return grad_cam'''
  1218. # Grad-CAM for each image in the batch
  1219. grad_cams = []
  1220. for i in range(x.size(0)): # Iterate through each sample in the batch
  1221. # Get the gradients and activations for each sample
  1222. gradients = self.gradients[i:i+1].detach().cpu().numpy() # For each sample
  1223. activations = self.activations[i:i+1].detach().cpu().numpy() # For each sample
  1224. # Compute Grad-CAM weights by averaging the gradients over the spatial dimensions (height, width)
  1225. weights = np.mean(gradients, axis=(2, 3)) # Global average pooling to compute weights
  1226. # Calculate the Grad-CAM heatmap by summing the weighted activations
  1227. grad_cam = np.sum(weights[:, :, np.newaxis, np.newaxis] * activations, axis=1)
  1228. # Apply ReLU to the heatmap to keep only positive contributions
  1229. grad_cam = np.maximum(grad_cam, 0) # Apply ReLU
  1230. # Normalize the Grad-CAM heatmap to the range [0, 1]
  1231. grad_cam -= grad_cam.min()
  1232. grad_cam /= grad_cam.max()
  1233. grad_cams.append(grad_cam)
  1234. # Return the list of Grad-CAMs for the batch
  1235. return grad_cams
  1236. def save_gradcam(self, grad_cam, input_image, save_path, file_name):
  1237. # ---------- heatmap ----------
  1238. grad_cam_resized = torch.from_numpy(grad_cam).unsqueeze(0)
  1239. grad_cam_resized = grad_cam_resized.float()
  1240. while grad_cam_resized.shape[2] < input_image.shape[2]:
  1241. grad_cam_resized = F.interpolate(grad_cam_resized, scale_factor=2, mode='bilinear')
  1242. grad_cam_resized = grad_cam_resized.squeeze().cpu().numpy()
  1243. grad_cam_resized = (grad_cam_resized - grad_cam_resized.min()) / (grad_cam_resized.max() - grad_cam_resized.min())
  1244. heatmap = grad_cam_resized
  1245. if len(heatmap.shape) == 3:
  1246. heatmap = np.mean(heatmap, axis=2)
  1247. grad_cam_resized = np.uint8(255 * grad_cam_resized)
  1248. grad_cam_resized = cv2.applyColorMap(grad_cam_resized, cv2.COLORMAP_TURBO)
  1249. save_heatmap_path = os.path.join(save_path, 'heatmap')
  1250. if not os.path.exists(save_heatmap_path):
  1251. os.makedirs(save_heatmap_path)
  1252. heatmap_name = f"{file_name}_heatmap.jpg"
  1253. save_heatmap = os.path.join(save_heatmap_path, heatmap_name)
  1254. cv2.imwrite(save_heatmap, grad_cam_resized)
  1255. save_heatmap_path = os.path.join(save_path, 'heatmap_npy')
  1256. if not os.path.exists(save_heatmap_path):
  1257. os.makedirs(save_heatmap_path)
  1258. heatmap_name = f"{file_name}_heatmap.npy"
  1259. save_heatmap = os.path.join(save_heatmap_path, heatmap_name)
  1260. np.save(save_heatmap, heatmap)
  1261. # ---------- input ----------
  1262. input_image = input_image.detach().cpu().numpy().squeeze().transpose(1, 2, 0)
  1263. input_image = (input_image - input_image.min()) / (input_image.max() - input_image.min())
  1264. base_image = input_image
  1265. if len(base_image.shape) == 3:
  1266. base_image = np.mean(base_image, axis=2)
  1267. save_input_path = os.path.join(save_path, 'original')
  1268. if not os.path.exists(save_input_path):
  1269. os.makedirs(save_input_path)
  1270. input_name = f"{file_name}.jpg"
  1271. save_input = os.path.join(save_input_path, input_name)
  1272. plt.imsave(save_input, base_image, cmap='gray')
  1273. save_input_path = os.path.join(save_path, 'original_npy')
  1274. if not os.path.exists(save_input_path):
  1275. os.makedirs(save_input_path)
  1276. input_name = f"{file_name}.npy"
  1277. save_input = os.path.join(save_input_path, input_name)
  1278. np.save(save_input, base_image)
  1279. # ---------- overlay ----------
  1280. input_image = np.uint8(255 * input_image)
  1281. overlay = cv2.addWeighted(input_image, 0.4, grad_cam_resized, 0.6, 0)
  1282. save_overlay_path = os.path.join(save_path, 'overlay')
  1283. if not os.path.exists(save_overlay_path):
  1284. os.makedirs(save_overlay_path)
  1285. overlay_name = f"{file_name}_overlay.jpg"
  1286. save_overlay = os.path.join(save_overlay_path, overlay_name)
  1287. cv2.imwrite(save_overlay, overlay)
  1288. save_overlay_path = os.path.join(save_path, 'overlay_npy')
  1289. if not os.path.exists(save_overlay_path):
  1290. os.makedirs(save_overlay_path)
  1291. overlay_name = f"{file_name}_overlay.npy"
  1292. save_overlay = os.path.join(save_overlay_path, overlay_name)
  1293. # np.save(save_overlay, overlay)
  1294. # ---------- contour ----------
  1295. fig, ax = plt.subplots(figsize=(2.56, 2.56), dpi=100)
  1296. ax.imshow(base_image, cmap='gray')
  1297. levels = [0.45, 0.55, 0.65, 0.75, 0.85]
  1298. contour = ax.contour(heatmap, levels=levels, cmap='jet', linewidths=2)
  1299. ax.axis('off')
  1300. plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
  1301. contour_data = []
  1302. for collection in contour.collections:
  1303. paths = collection.get_paths()
  1304. for path in paths:
  1305. contour_data.append(path.vertices)
  1306. contour_array = np.array(contour_data, dtype=object)
  1307. save_coutour_path = os.path.join(save_path, 'coutour')
  1308. if not os.path.exists(save_coutour_path):
  1309. os.makedirs(save_coutour_path)
  1310. coutour_name = f"{file_name}_coutour.jpg"
  1311. save_coutour = os.path.join(save_coutour_path, coutour_name)
  1312. plt.savefig(save_coutour, bbox_inches='tight', pad_inches=0, transparent=True)
  1313. plt.close()
  1314. save_coutour_path = os.path.join(save_path, 'coutour_npy')
  1315. if not os.path.exists(save_coutour_path):
  1316. os.makedirs(save_coutour_path)
  1317. coutour_name = f"{file_name}_coutour.npy"
  1318. save_coutour = os.path.join(save_coutour_path, coutour_name)
  1319. # np.save(save_coutour, contour_array)
  1320. print(f"{file_name} saved.")

UNet2d_condition.py at commit d91148c, no license · at the source

Overview

Authors: Guoxun Zhang1,2, Zebin Gao2,3, Caohui Duan4, Jiaxin Liu5, Yuerong Lizhu6,7, Yaou Liu6,7, Qian Chen8, Ling Wang8, Kailun Fei9, Tianyun Wang3, YuJia Chen5, Yanchen Guo5, Feng Xu10, Yuchen Guo2, Xin Lou4, Qionghai Dai1,2
  1. Department of Automation, BNRist, Tsinghua University, Beijing 100084, China
  2. Beijing National Research Center for Information Science and Technology, Tsinghua University, Beijing 100084, China
  3. School of Information Science and Technology, Fudan University, Shanghai 200438, China
  4. Department of Radiology, Chinese PLA General Hospital, Beijing 100039, China
  5. Tsinghua Shenzhen International Graduate School, Tsinghua University, Shenzhen 518071, China
  6. Department of Radiology, Beijing Tiantan Hospital, Capital Medical University, Beijing 100070, China
  7. Tiantan Image Research Center, China National Clinical Research Center for Neurological Diseases, Beijing 100070, China
  8. Beijing Friendship Hospital, Capital Medical University, Beijing 100050, China
  9. Cancer Hospital, Chinese Academy of Medical Sciences and Peking Union Medical College, Beijing 100730, China
  10. School of Software, BNRist, Tsinghua University, Beijing 100084, China
Journal: Patterns (New York, N.Y.), volume 7, issue 6, article 101538
Dates: received 14 September 2025; accepted 17 March 2026; published online 14 April 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1016/j.patter.2026.101538 · PMID 42328202 · PMCID PMC13280722 · OpenAlex W7154370387
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: human (organism), clinical / translational (subfield)
Methods: Connectivity, Machine learning
Keywords: multi-modal, foundation model, contrastive learning, brain disease, medical imaging, diffusion model
Topic: Medical Image Segmentation Techniques (Computer Vision and Pattern Recognition, Computer Science), according to OpenAlex
Funding: National Natural Science Foundation of China (82441013, 82441014, 62088102, 82327803, T2541076, T2541074, 82572167)
Citations: cited by 1 paper (Europe PMC); 62 references in the paper

Abstract

The precise and comprehensive diagnosis of complex brain disorders relies on non-invasive computed tomography (CT) and magnetic resonance imaging (MRI) in conjunction with multi-modal clinical information. Here, we present Brainfound, a multi-modal foundation model for brain medical imaging that integrates image-text contrastive learning with a diffusion-based generative framework. The model was pre-trained on more than 3 million brain CT slices and 7 million brain MRI slices paired with clinical reports. In multi-center evaluations, Brainfound demonstrates state-of-the-art performance across seven tasks, including brain disease diagnosis, lesion segmentation, MRI enhancement, cross-modality translation, automatic report generation, zero-shot disease classification, and human-AI dialogue. It substantially outperforms leading models in automated report generation and clinical question answering for brain imaging, and its performance approaches that of expert physicians. These findings highlight the potential of Brainfound for accelerating diagnosis, support treatment decisions, and advance human-in-the-loop brain health care.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 8 matches between paragraphs and lines of code.

Zenodo 18976379

License: CC-BY-4.0
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Size: 2 files
Software Heritage: not checked
Found in: “Data and code availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: PyTorch (89 files), NumPy (52 files), Hugging Face Transformers (16 files), Pillow (11 files), OpenCV (10 files), Matplotlib (7 files), scikit-learn (7 files), SciPy (6 files), MONAI (5 files), scikit-image (3 files), h5py (2 files), NiBabel (2 files), TensorFlow (2 files), tifffile (2 files), pandas (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
  • 29 September 2026: the link answers (HTTP 200)
141 files

Zenodo 7549620

License: CC-BY-4.0
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: the references
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (6 files), SciPy (2 files), ggplot2 (1 file), pandas (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
  • 29 September 2026: the link answers (HTTP 200)
8 files
At the source:

gingerbread000/brainfound

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: d91148c8fbe879db5d9fa8d578efdfac585d154b, 23 September 2025
Languages: Python (133), Shell (3), C++ (2), CUDA (2)
Size: 169 files, 140 scripts
Software Heritage: not archived
Found in: the Zenodo archive record
Holds: README
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: PyTorch (89 files), NumPy (52 files), Hugging Face Transformers (16 files), Pillow (11 files), OpenCV (10 files), Matplotlib (7 files), scikit-learn (7 files), SciPy (6 files), MONAI (5 files), scikit-image (3 files), h5py (2 files), NiBabel (2 files), TensorFlow (2 files), tifffile (2 files), pandas (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
141 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 3 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 288 scripts, each with its path and the digest of its content;
  • 8 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data and code availability

The source code and pre-trained model weights of the Brainfound foundation model have been deposited in Zenodo62 and are publicly available under a persistent DOI: https://doi.org/10.5281/zenodo.18976379. The training datasets used in this study contain sensitive clinical information and cannot be publicly shared due to ethical and privacy restrictions. Access to the data could be considered upon reasonable request and subject to approval by the corresponding institutions and ethics committee. The BraTS 2023 dataset is available from the Brain Tumor Segmentation (BraTs) challenge (https://www.synapse.org/#!Synapse:syn51156910), and the RSNA Intracranial Hemorrhage dataset is available from the RSNA Intracranial Hemorrhage Detection Challenge on Kaggle (https://www.kaggle.com/competitions/rsna-intracranial-hemorrhage-detection). Access to these dataset may require registration and agreement to the respective data usage terms.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 29 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 16 authors, 6 keywords, 1 funder, 61 references.

Cite

This paper

Zhang, G., Gao, Z., Duan, C., Liu, J., Lizhu, Y., Liu, Y., Chen, Q., Wang, L., Fei, K., Wang, T., Chen, Y., Guo, Y., Xu, F., Guo, Y., Lou, X., & Dai, Q. (2026). A multi-modal foundation model for brain disease diagnosis and medical imaging. Patterns (New York, N.Y.), 7(6), 101538. https://doi.org/10.1016/j.patter.2026.101538

BibTeX

@article{zhang2026multi,
author = {Zhang, Guoxun and Gao, Zebin and Duan, Caohui and Liu, Jiaxin and Lizhu, Yuerong and Liu, Yaou and Chen, Qian and Wang, Ling and Fei, Kailun and Wang, Tianyun and Chen, YuJia and Guo, Yanchen and Xu, Feng and Guo, Yuchen and Lou, Xin and Dai, Qionghai},
title = {{A multi-modal foundation model for brain disease diagnosis and medical imaging}},
journal = {Patterns (New York, N.Y.)},
year = {2026},
month = apr,
volume = {7},
number = {6},
pages = {101538},
publisher = {Elsevier},
issn = {2666-3899},
doi = {10.1016/j.patter.2026.101538},
url = {https://doi.org/10.1016/j.patter.2026.101538},
pmid = {42328202},
pmcid = {PMC13280722}
}

RIS

TY - JOUR
AU - Zhang, Guoxun
AU - Gao, Zebin
AU - Duan, Caohui
AU - Liu, Jiaxin
AU - Lizhu, Yuerong
AU - Liu, Yaou
AU - Chen, Qian
AU - Wang, Ling
AU - Fei, Kailun
AU - Wang, Tianyun
AU - Chen, YuJia
AU - Guo, Yanchen
AU - Xu, Feng
AU - Guo, Yuchen
AU - Lou, Xin
AU - Dai, Qionghai
TI - A multi-modal foundation model for brain disease diagnosis and medical imaging
T2 - Patterns (New York, N.Y.)
J2 - Patterns (N Y)
PY - 2026
DA - 2026/04/14
VL - 7
IS - 6
SP - 101538
SN - 2666-3899
PB - Elsevier
DO - 10.1016/j.patter.2026.101538
UR - https://doi.org/10.1016/j.patter.2026.101538
LA - en
ER -

CSL-JSON

{
"id": "10.1016/j.patter.2026.101538",
"type": "article-journal",
"title": "A multi-modal foundation model for brain disease diagnosis and medical imaging",
"container-title": "Patterns (New York, N.Y.)",
"author": [
{
"family": "Zhang",
"given": "Guoxun"
},
{
"family": "Gao",
"given": "Zebin"
},
{
"family": "Duan",
"given": "Caohui"
},
{
"family": "Liu",
"given": "Jiaxin"
},
{
"family": "Lizhu",
"given": "Yuerong"
},
{
"family": "Liu",
"given": "Yaou"
},
{
"family": "Chen",
"given": "Qian"
},
{
"family": "Wang",
"given": "Ling"
},
{
"family": "Fei",
"given": "Kailun"
},
{
"family": "Wang",
"given": "Tianyun"
},
{
"family": "Chen",
"given": "YuJia"
},
{
"family": "Guo",
"given": "Yanchen"
},
{
"family": "Xu",
"given": "Feng"
},
{
"family": "Guo",
"given": "Yuchen"
},
{
"family": "Lou",
"given": "Xin"
},
{
"family": "Dai",
"given": "Qionghai"
}
],
"container-title-short": "Patterns (N Y)",
"volume": "7",
"issue": "6",
"page": "101538",
"DOI": "10.1016/j.patter.2026.101538",
"PMID": "42328202",
"PMCID": "PMC13280722",
"ISSN": "2666-3899",
"publisher": "Elsevier",
"URL": "https://doi.org/10.1016/j.patter.2026.101538",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
14
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.3389/frai.2026.1771088 [code]
Few-shot deployment of pretrained MRI transformers in brain imaging tasks.
Journal: Frontiers in artificial intelligence
In common: MONAI, OpenCV, scikit-image, 9 other tools, 3 references
[2] doi:10.1364/boe.605322 [code]
Generalized plaque digitization framework for multi-dimensional mesoscopic images.
Journal: Biomedical optics express
In common: tifffile, TensorFlow, OpenCV, 9 other tools, 1 reference
[3] doi:10.7554/elife.107933 [code]
Modality-agnostic decoding of vision and language from fMRI.
Journal: eLife
In common: Hugging Face Transformers, OpenCV, scikit-image, 9 other tools, 1 reference
[4] doi:10.1016/j.xcrm.2026.102766 [code]
A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.
Journal: Cell reports. Medicine
In common: tifffile, TensorFlow, OpenCV, 9 other tools
[5] doi:10.1371/journal.pcbi.1014263 [code]
MIRAGE: Robust multi-modal architectures translate fMRI-to-image models from vision to mental imagery.
Journal: PLoS computational biology
In common: Hugging Face Transformers, OpenCV, scikit-image, 9 other tools
[6] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: Hugging Face Transformers, TensorFlow, OpenCV, 9 other tools
[7] doi:10.1111/joa.70203 [code]
Two-step workflow integrating automatic registration and manual refinement for the accurate alignment of serial histological sections in 3D reconstruction.
Journal: Journal of anatomy
In common: MONAI, Hugging Face Transformers, OpenCV, 8 other tools
[8] doi:10.3389/fnsys.2026.1822122 [code]
Convergence-divergence circuits for multimodal integration of innate and learned opponent valences.
Journal: Frontiers in systems neuroscience
In common: tifffile, TensorFlow, scikit-image, 9 other tools
[9] doi:10.1371/journal.pone.0344600 [code]
Robust disease prognosis via diagnostic knowledge preservation: A sequential learning approach.
Journal: PloS one
In common: OpenCV, scikit-image, h5py, 8 other tools, clinical / translational, 1 reference
[10] doi:10.1038/s41598-026-57519-w [code]
Automated segmentation of neurons and spinal cord structures in immunofluorescence images using SpineDL.
Journal: Scientific reports
In common: tifffile, OpenCV, scikit-image, 9 other tools

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.