giulio98 commited on
Commit
e835170
1 Parent(s): 0c397d9

Update unet/conditional_unet_model.py

Browse files
Files changed (1) hide show
  1. unet/conditional_unet_model.py +763 -55
unet/conditional_unet_model.py CHANGED
@@ -1,83 +1,791 @@
1
- from typing import Optional, Union, List, Tuple
2
 
3
  import torch
4
- from diffusers.utils.torch_utils import randn_tensor
5
- from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- class ScoreSdeVePipelineConditioned(DiffusionPipeline):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  r"""
10
- Pipeline for unconditional image generation.
11
- This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
12
- implemented for all pipelines (downloading, saving, running on a particular device, etc.).
13
  Parameters:
14
- unet ([`UNet2DModel`]):
15
- A `UNet2DModel` to denoise the encoded image.
16
- scheduler ([`ScoreSdeVeScheduler`]):
17
- A `ScoreSdeVeScheduler` to be used in combination with `unet` to denoise the encoded image.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  """
19
- def __init__(self, unet, scheduler):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  super().__init__()
21
- self.register_modules(unet=unet, scheduler=scheduler)
22
 
23
- @torch.no_grad()
24
- def __call__(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  self,
26
- batch_size: int = 1,
27
- num_inference_steps: int = 2000,
28
  class_labels: Optional[torch.Tensor] = None,
29
- generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
30
- output_type: Optional[str] = "pil",
31
  return_dict: bool = True,
32
- **kwargs,
33
- ) -> Union[ImagePipelineOutput, Tuple]:
34
  r"""
35
- The call function to the pipeline for generation.
36
  Args:
37
- batch_size (`int`, *optional*, defaults to 1):
38
- The number of images to generate.
39
- generator (`torch.Generator`, `optional`):
40
- A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
41
- generation deterministic.
42
- output_type (`str`, `optional`, defaults to `"pil"`):
43
- The output format of the generated image. Choose between `PIL.Image` or `np.array`.
44
  return_dict (`bool`, *optional*, defaults to `True`):
45
- Whether or not to return a [`ImagePipelineOutput`] instead of a plain tuple.
46
  Returns:
47
- [`~pipelines.ImagePipelineOutput`] or `tuple`:
48
- If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
49
- returned where the first element is a list with the generated images.
50
  """
51
- img_size = self.unet.config.sample_size
52
- shape = (batch_size, 3, img_size, img_size)
 
 
 
 
 
 
 
 
53
 
54
- model = self.unet
 
55
 
56
- sample = randn_tensor(shape, generator=generator, device=self.device) * self.scheduler.init_noise_sigma
57
- sample = sample.to(self.device)
58
 
59
- self.scheduler.set_timesteps(num_inference_steps)
60
- self.scheduler.set_sigmas(num_inference_steps)
 
 
 
61
 
62
- for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
63
- sigma_t = self.scheduler.sigmas[i] * torch.ones(shape[0], device=self.device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- # correction step
66
- for _ in range(self.scheduler.config.correct_steps):
67
- model_output = self.unet(sample, sigma_t, class_labels).sample
68
- sample = self.scheduler.step_correct(model_output, sample, generator=generator).prev_sample
69
 
70
- # prediction step
71
- model_output = model(sample, sigma_t, class_labels).sample
72
- output = self.scheduler.step_pred(model_output, t, sample, generator=generator)
73
 
74
- sample, sample_mean = output.prev_sample, output.prev_sample_mean
 
 
 
 
75
 
76
- sample = sample_mean.clamp(0, 1)
77
- sample = sample.cpu().permute(0, 2, 3, 1).numpy()
78
- if output_type == "pil":
79
- sample = self.numpy_to_pil(sample)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  if not return_dict:
82
  return (sample,)
83
- return ImagePipelineOutput(images=sample)
 
 
1
+ from typing import List, Optional, Tuple, Union
2
 
3
  import torch
4
+ from dataclasses import dataclass
5
+ from typing import Optional, Tuple, Union
6
 
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
11
+ from diffusers.utils import BaseOutput
12
+ from diffusers.models.embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
13
+ from diffusers.models.modeling_utils import ModelMixin
14
+ from diffusers.models.unets.unet_2d_blocks import UNetMidBlock2D, get_down_block, get_up_block
15
+
16
+ @dataclass
17
+ class UNet2DOutput(BaseOutput):
18
+ """
19
+ The output of [`UNet2DModel`].
20
+ Args:
21
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
22
+ The hidden states output from the last layer of the model.
23
+ """
24
+
25
+ sample: torch.FloatTensor
26
+
27
+
28
+ class UNet2DModel(ModelMixin, ConfigMixin):
29
+ r"""
30
+ A 2D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.
31
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
32
+ for all models (such as downloading or saving).
33
+ Parameters:
34
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
35
+ Height and width of input/output sample. Dimensions must be a multiple of `2 ** (len(block_out_channels) -
36
+ 1)`.
37
+ in_channels (`int`, *optional*, defaults to 3): Number of channels in the input sample.
38
+ out_channels (`int`, *optional*, defaults to 3): Number of channels in the output.
39
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
40
+ time_embedding_type (`str`, *optional*, defaults to `"positional"`): Type of time embedding to use.
41
+ freq_shift (`int`, *optional*, defaults to 0): Frequency shift for Fourier time embedding.
42
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
43
+ Whether to flip sin to cos for Fourier time embedding.
44
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")`):
45
+ Tuple of downsample block types.
46
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2D"`):
47
+ Block type for middle of UNet, it can be either `UNetMidBlock2D` or `UnCLIPUNetMidBlock2D`.
48
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")`):
49
+ Tuple of upsample block types.
50
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(224, 448, 672, 896)`):
51
+ Tuple of block output channels.
52
+ layers_per_block (`int`, *optional*, defaults to `2`): The number of layers per block.
53
+ mid_block_scale_factor (`float`, *optional*, defaults to `1`): The scale factor for the mid block.
54
+ downsample_padding (`int`, *optional*, defaults to `1`): The padding for the downsample convolution.
55
+ downsample_type (`str`, *optional*, defaults to `conv`):
56
+ The downsample type for downsampling layers. Choose between "conv" and "resnet"
57
+ upsample_type (`str`, *optional*, defaults to `conv`):
58
+ The upsample type for upsampling layers. Choose between "conv" and "resnet"
59
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
60
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
61
+ attention_head_dim (`int`, *optional*, defaults to `8`): The attention head dimension.
62
+ norm_num_groups (`int`, *optional*, defaults to `32`): The number of groups for normalization.
63
+ attn_norm_num_groups (`int`, *optional*, defaults to `None`):
64
+ If set to an integer, a group norm layer will be created in the mid block's [`Attention`] layer with the
65
+ given number of groups. If left as `None`, the group norm layer will only be created if
66
+ `resnet_time_scale_shift` is set to `default`, and if created will have `norm_num_groups` groups.
67
+ norm_eps (`float`, *optional*, defaults to `1e-5`): The epsilon for normalization.
68
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
69
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
70
+ class_embed_type (`str`, *optional*, defaults to `None`):
71
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
72
+ `"timestep"`, or `"identity"`.
73
+ num_class_embeds (`int`, *optional*, defaults to `None`):
74
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim` when performing class
75
+ conditioning with `class_embed_type` equal to `None`.
76
+ """
77
+
78
+ @register_to_config
79
+ def __init__(
80
+ self,
81
+ sample_size: Optional[Union[int, Tuple[int, int]]] = None,
82
+ in_channels: int = 3,
83
+ out_channels: int = 3,
84
+ center_input_sample: bool = False,
85
+ time_embedding_type: str = "positional",
86
+ freq_shift: int = 0,
87
+ flip_sin_to_cos: bool = True,
88
+ down_block_types: Tuple[str, ...] = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
89
+ up_block_types: Tuple[str, ...] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
90
+ block_out_channels: Tuple[int, ...] = (224, 448, 672, 896),
91
+ layers_per_block: int = 2,
92
+ mid_block_scale_factor: float = 1,
93
+ downsample_padding: int = 1,
94
+ downsample_type: str = "conv",
95
+ upsample_type: str = "conv",
96
+ dropout: float = 0.0,
97
+ act_fn: str = "silu",
98
+ attention_head_dim: Optional[int] = 8,
99
+ norm_num_groups: int = 32,
100
+ attn_norm_num_groups: Optional[int] = None,
101
+ norm_eps: float = 1e-5,
102
+ resnet_time_scale_shift: str = "default",
103
+ add_attention: bool = True,
104
+ class_embed_type: Optional[str] = None,
105
+ num_class_embeds: Optional[int] = None,
106
+ num_train_timesteps: Optional[int] = None,
107
+ set_W_to_weight: Optional[bool] = True
108
+ ):
109
+ super().__init__()
110
+
111
+ self.sample_size = sample_size
112
+ time_embed_dim = block_out_channels[0] * 4
113
+
114
+ # Check inputs
115
+ if len(down_block_types) != len(up_block_types):
116
+ raise ValueError(
117
+ 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}."
118
+ )
119
+
120
+ if len(block_out_channels) != len(down_block_types):
121
+ raise ValueError(
122
+ 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}."
123
+ )
124
+
125
+ # input
126
+ self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
127
+
128
+ # time
129
+ if time_embedding_type == "fourier":
130
+ self.time_proj = GaussianFourierProjection(embedding_size=block_out_channels[0], scale=16, set_W_to_weight=set_W_to_weight)
131
+ timestep_input_dim = 2 * block_out_channels[0]
132
+ elif time_embedding_type == "positional":
133
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
134
+ timestep_input_dim = block_out_channels[0]
135
+ elif time_embedding_type == "learned":
136
+ self.time_proj = nn.Embedding(num_train_timesteps, block_out_channels[0])
137
+ timestep_input_dim = block_out_channels[0]
138
+
139
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
140
+
141
+ # class embedding
142
+ if class_embed_type is None and num_class_embeds is not None:
143
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
144
+ elif class_embed_type == "timestep":
145
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
146
+ elif class_embed_type == "identity":
147
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
148
+ else:
149
+ self.class_embedding = None
150
+
151
+ self.down_blocks = nn.ModuleList([])
152
+ self.mid_block = None
153
+ self.up_blocks = nn.ModuleList([])
154
+
155
+ # down
156
+ output_channel = block_out_channels[0]
157
+ for i, down_block_type in enumerate(down_block_types):
158
+ input_channel = output_channel
159
+ output_channel = block_out_channels[i]
160
+ is_final_block = i == len(block_out_channels) - 1
161
+
162
+ down_block = get_down_block(
163
+ down_block_type,
164
+ num_layers=layers_per_block,
165
+ in_channels=input_channel,
166
+ out_channels=output_channel,
167
+ temb_channels=time_embed_dim,
168
+ add_downsample=not is_final_block,
169
+ resnet_eps=norm_eps,
170
+ resnet_act_fn=act_fn,
171
+ resnet_groups=norm_num_groups,
172
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
173
+ downsample_padding=downsample_padding,
174
+ resnet_time_scale_shift=resnet_time_scale_shift,
175
+ downsample_type=downsample_type,
176
+ dropout=dropout,
177
+ )
178
+ self.down_blocks.append(down_block)
179
+
180
+ # mid
181
+ self.mid_block = UNetMidBlock2D(
182
+ in_channels=block_out_channels[-1],
183
+ temb_channels=time_embed_dim,
184
+ dropout=dropout,
185
+ resnet_eps=norm_eps,
186
+ resnet_act_fn=act_fn,
187
+ output_scale_factor=mid_block_scale_factor,
188
+ resnet_time_scale_shift=resnet_time_scale_shift,
189
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1],
190
+ resnet_groups=norm_num_groups,
191
+ attn_groups=attn_norm_num_groups,
192
+ add_attention=add_attention,
193
+ )
194
+
195
+ # up
196
+ reversed_block_out_channels = list(reversed(block_out_channels))
197
+ output_channel = reversed_block_out_channels[0]
198
+ for i, up_block_type in enumerate(up_block_types):
199
+ prev_output_channel = output_channel
200
+ output_channel = reversed_block_out_channels[i]
201
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
202
+
203
+ is_final_block = i == len(block_out_channels) - 1
204
+
205
+ up_block = get_up_block(
206
+ up_block_type,
207
+ num_layers=layers_per_block + 1,
208
+ in_channels=input_channel,
209
+ out_channels=output_channel,
210
+ prev_output_channel=prev_output_channel,
211
+ temb_channels=time_embed_dim,
212
+ add_upsample=not is_final_block,
213
+ resnet_eps=norm_eps,
214
+ resnet_act_fn=act_fn,
215
+ resnet_groups=norm_num_groups,
216
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
217
+ resnet_time_scale_shift=resnet_time_scale_shift,
218
+ upsample_type=upsample_type,
219
+ dropout=dropout,
220
+ )
221
+ self.up_blocks.append(up_block)
222
+ prev_output_channel = output_channel
223
+
224
+ # out
225
+ num_groups_out = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4, 32)
226
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=num_groups_out, eps=norm_eps)
227
+ self.conv_act = nn.SiLU()
228
+ self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
229
+
230
+ def forward(
231
+ self,
232
+ sample: torch.FloatTensor,
233
+ timestep: Union[torch.Tensor, float, int],
234
+ class_labels: Optional[torch.Tensor] = None,
235
+ return_dict: bool = True,
236
+ ) -> Union[UNet2DOutput, Tuple]:
237
+ r"""
238
+ The [`UNet2DModel`] forward method.
239
+ Args:
240
+ sample (`torch.FloatTensor`):
241
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
242
+ timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
243
+ class_labels (`torch.FloatTensor`, *optional*, defaults to `None`):
244
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
245
+ return_dict (`bool`, *optional*, defaults to `True`):
246
+ Whether or not to return a [`~models.unet_2d.UNet2DOutput`] instead of a plain tuple.
247
+ Returns:
248
+ [`~models.unet_2d.UNet2DOutput`] or `tuple`:
249
+ If `return_dict` is True, an [`~models.unet_2d.UNet2DOutput`] is returned, otherwise a `tuple` is
250
+ returned where the first element is the sample tensor.
251
+ """
252
+ # 0. center input if necessary
253
+ if self.config.center_input_sample:
254
+ sample = 2 * sample - 1.0
255
+
256
+ # 1. time
257
+ timesteps = timestep
258
+ if not torch.is_tensor(timesteps):
259
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
260
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
261
+ timesteps = timesteps[None].to(sample.device)
262
+
263
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
264
+ timesteps = timesteps * torch.ones(sample.shape[0], dtype=timesteps.dtype, device=timesteps.device)
265
+
266
+ t_emb = self.time_proj(timesteps)
267
+
268
+ # timesteps does not contain any weights and will always return f32 tensors
269
+ # but time_embedding might actually be running in fp16. so we need to cast here.
270
+ # there might be better ways to encapsulate this.
271
+ t_emb = t_emb.to(dtype=self.dtype)
272
+ emb = self.time_embedding(t_emb)
273
+
274
+ if self.class_embedding is not None:
275
+ if class_labels is None:
276
+ raise ValueError("class_labels should be provided when doing class conditioning")
277
+
278
+ if self.config.class_embed_type == "timestep":
279
+ class_labels = self.time_proj(class_labels)
280
+
281
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
282
+ emb = emb + class_emb
283
+ elif self.class_embedding is None and class_labels is not None:
284
+ raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
285
+
286
+ # 2. pre-process
287
+ skip_sample = sample
288
+ sample = self.conv_in(sample)
289
 
290
+ # 3. down
291
+ down_block_res_samples = (sample,)
292
+ for downsample_block in self.down_blocks:
293
+ if hasattr(downsample_block, "skip_conv"):
294
+ sample, res_samples, skip_sample = downsample_block(
295
+ hidden_states=sample, temb=emb, skip_sample=skip_sample
296
+ )
297
+ else:
298
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
299
+
300
+ down_block_res_samples += res_samples
301
+
302
+ # 4. mid
303
+ sample = self.mid_block(sample, emb)
304
+
305
+ # 5. up
306
+ skip_sample = None
307
+ for upsample_block in self.up_blocks:
308
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
309
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
310
+
311
+ if hasattr(upsample_block, "skip_conv"):
312
+ sample, skip_sample = upsample_block(sample, res_samples, emb, skip_sample)
313
+ else:
314
+ sample = upsample_block(sample, res_samples, emb)
315
+
316
+ # 6. post-process
317
+ sample = self.conv_norm_out(sample)
318
+ sample = self.conv_act(sample)
319
+ sample = self.conv_out(sample)
320
+
321
+ if skip_sample is not None:
322
+ sample += skip_sample
323
+
324
+ if self.config.time_embedding_type == "fourier":
325
+ timesteps = timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]))))
326
+ sample = sample / timesteps
327
+
328
+ if not return_dict:
329
+ return (sample,)
330
+
331
+ return UNet2DOutput(sample=sample)
332
+
333
+ NUM_CLASSES_FLOOR_HUE = 10
334
+ NUM_CLASSES_OBJECT_HUE = 10
335
+ NUM_CLASSES_ORIENTATION = 15
336
+ NUM_CLASSES_SCALE = 8
337
+ NUM_CLASSES_SHAPE = 4
338
+ NUM_CLASSES_WALL_HUE = 10
339
+ class ClassConditionedUnetForShapes3D(ModelMixin, ConfigMixin):
340
+ @register_to_config
341
+ def __init__(self,
342
+ num_classes_floor_hue=NUM_CLASSES_FLOOR_HUE + 1,
343
+ num_classes_object_hue=NUM_CLASSES_OBJECT_HUE + 1,
344
+ num_classes_orientation=NUM_CLASSES_ORIENTATION + 1,
345
+ num_classes_scale=NUM_CLASSES_SCALE + 1,
346
+ num_classes_shape=NUM_CLASSES_SHAPE + 1,
347
+ num_classes_wall_hue=NUM_CLASSES_WALL_HUE + 1,
348
+ sample_size: Optional[Union[int, Tuple[int, int]]] = None,
349
+ in_channels: int = 3,
350
+ out_channels: int = 3,
351
+ center_input_sample: bool = False,
352
+ time_embedding_type: str = "positional",
353
+ freq_shift: int = 0,
354
+ flip_sin_to_cos: bool = True,
355
+ down_block_types: Tuple[str, ...] = (
356
+ "DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
357
+ up_block_types: Tuple[str, ...] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
358
+ block_out_channels: Tuple[int, ...] = (224, 448, 672, 896),
359
+ layers_per_block: int = 2,
360
+ mid_block_scale_factor: float = 1,
361
+ downsample_padding: int = 1,
362
+ downsample_type: str = "conv",
363
+ upsample_type: str = "conv",
364
+ dropout: float = 0.0,
365
+ act_fn: str = "silu",
366
+ attention_head_dim: Optional[int] = 8,
367
+ norm_num_groups: int = 32,
368
+ attn_norm_num_groups: Optional[int] = None,
369
+ norm_eps: float = 1e-5,
370
+ resnet_time_scale_shift: str = "default",
371
+ add_attention: bool = True,
372
+ class_embed_type: Optional[str] = None,
373
+ num_class_embeds: Optional[int] = None,
374
+ num_train_timesteps: Optional[int] = None,
375
+ set_W_to_weight: Optional[bool] = True
376
+ ):
377
+ super().__init__()
378
+ self.class_floor_hue = nn.Embedding(num_classes_floor_hue, num_classes_floor_hue)
379
+ self.class_object_hue = nn.Embedding(num_classes_object_hue, num_classes_object_hue)
380
+ self.class_orientation = nn.Embedding(num_classes_orientation, num_classes_orientation)
381
+ self.class_scale = nn.Embedding(num_classes_scale, num_classes_scale)
382
+ self.class_shape = nn.Embedding(num_classes_shape, num_classes_shape)
383
+ self.class_wall_hue = nn.Embedding(num_classes_wall_hue, num_classes_wall_hue)
384
+ self.model = UNet2DModel(
385
+ sample_size=sample_size,
386
+ in_channels=in_channels,
387
+ out_channels=out_channels,
388
+ center_input_sample=center_input_sample,
389
+ time_embedding_type=time_embedding_type,
390
+ freq_shift=freq_shift,
391
+ flip_sin_to_cos=flip_sin_to_cos,
392
+ down_block_types=down_block_types,
393
+ up_block_types=up_block_types,
394
+ block_out_channels=block_out_channels,
395
+ layers_per_block=layers_per_block,
396
+ mid_block_scale_factor=mid_block_scale_factor,
397
+ downsample_padding=downsample_padding,
398
+ downsample_type=downsample_type,
399
+ upsample_type=upsample_type,
400
+ dropout=dropout,
401
+ act_fn=act_fn,
402
+ attention_head_dim=attention_head_dim,
403
+ norm_num_groups=norm_num_groups,
404
+ attn_norm_num_groups=attn_norm_num_groups,
405
+ norm_eps=norm_eps,
406
+ resnet_time_scale_shift=resnet_time_scale_shift,
407
+ add_attention=add_attention,
408
+ class_embed_type=class_embed_type,
409
+ num_class_embeds=num_class_embeds,
410
+ num_train_timesteps=num_train_timesteps,
411
+ set_W_to_weight=set_W_to_weight
412
+ )
413
+
414
+ def forward(self, x, t, class_labels):
415
+ bs, ch, w, h = x.shape
416
+
417
+ class_cond_floor_hue = self.class_floor_hue(class_labels[:, 0])
418
+ class_cond_floor_hue = class_cond_floor_hue.view(bs, class_cond_floor_hue.shape[1], 1, 1).expand(bs, class_cond_floor_hue.shape[1], w, h)
419
+ class_cond_object_hue = self.class_object_hue(class_labels[:, 1])
420
+ class_cond_object_hue = class_cond_object_hue.view(bs, class_cond_object_hue.shape[1], 1, 1).expand(bs, class_cond_object_hue.shape[1], w, h)
421
+ class_cond_orientation = self.class_orientation(class_labels[:, 2])
422
+ class_cond_orientation = class_cond_orientation.view(bs, class_cond_orientation.shape[1], 1, 1).expand(bs, class_cond_orientation.shape[1], w, h)
423
+ class_cond_scale = self.class_scale(class_labels[:, 3])
424
+ class_cond_scale = class_cond_scale.view(bs, class_cond_scale.shape[1], 1, 1).expand(bs, class_cond_scale.shape[1], w, h)
425
+ class_cond_shape = self.class_shape(class_labels[:, 4])
426
+ class_cond_shape = class_cond_shape.view(bs, class_cond_shape.shape[1], 1, 1).expand(bs, class_cond_shape.shape[1], w, h)
427
+ class_cond_wall_hue = self.class_wall_hue(class_labels[:, 5])
428
+ class_cond_wall_hue = class_cond_wall_hue.view(bs, class_cond_wall_hue.shape[1], 1, 1).expand(bs, class_cond_wall_hue.shape[1], w, h)
429
+ net_input = torch.cat([x, class_cond_floor_hue, class_cond_object_hue, class_cond_orientation, class_cond_scale, class_cond_shape, class_cond_wall_hue], dim=1)
430
+ return self.model(net_input, t)
431
+
432
+
433
+ class MultiLabelConditionalUNet2DModelForShapes3D(ModelMixin, ConfigMixin):
434
  r"""
435
+ A 2D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.
436
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
437
+ for all models (such as downloading or saving).
438
  Parameters:
439
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
440
+ Height and width of input/output sample. Dimensions must be a multiple of `2 ** (len(block_out_channels) -
441
+ 1)`.
442
+ in_channels (`int`, *optional*, defaults to 3): Number of channels in the input sample.
443
+ out_channels (`int`, *optional*, defaults to 3): Number of channels in the output.
444
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
445
+ time_embedding_type (`str`, *optional*, defaults to `"positional"`): Type of time embedding to use.
446
+ freq_shift (`int`, *optional*, defaults to 0): Frequency shift for Fourier time embedding.
447
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
448
+ Whether to flip sin to cos for Fourier time embedding.
449
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")`):
450
+ Tuple of downsample block types.
451
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2D"`):
452
+ Block type for middle of UNet, it can be either `UNetMidBlock2D` or `UnCLIPUNetMidBlock2D`.
453
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")`):
454
+ Tuple of upsample block types.
455
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(224, 448, 672, 896)`):
456
+ Tuple of block output channels.
457
+ layers_per_block (`int`, *optional*, defaults to `2`): The number of layers per block.
458
+ mid_block_scale_factor (`float`, *optional*, defaults to `1`): The scale factor for the mid block.
459
+ downsample_padding (`int`, *optional*, defaults to `1`): The padding for the downsample convolution.
460
+ downsample_type (`str`, *optional*, defaults to `conv`):
461
+ The downsample type for downsampling layers. Choose between "conv" and "resnet"
462
+ upsample_type (`str`, *optional*, defaults to `conv`):
463
+ The upsample type for upsampling layers. Choose between "conv" and "resnet"
464
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
465
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
466
+ attention_head_dim (`int`, *optional*, defaults to `8`): The attention head dimension.
467
+ norm_num_groups (`int`, *optional*, defaults to `32`): The number of groups for normalization.
468
+ attn_norm_num_groups (`int`, *optional*, defaults to `None`):
469
+ If set to an integer, a group norm layer will be created in the mid block's [`Attention`] layer with the
470
+ given number of groups. If left as `None`, the group norm layer will only be created if
471
+ `resnet_time_scale_shift` is set to `default`, and if created will have `norm_num_groups` groups.
472
+ norm_eps (`float`, *optional*, defaults to `1e-5`): The epsilon for normalization.
473
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
474
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
475
+ class_embed_type (`str`, *optional*, defaults to `None`):
476
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
477
+ `"timestep"`, or `"identity"`.
478
+ num_class_embeds (`int`, *optional*, defaults to `None`):
479
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim` when performing class
480
+ conditioning with `class_embed_type` equal to `None`.
481
  """
482
+
483
+ @register_to_config
484
+ def __init__(
485
+ self,
486
+ sample_size: Optional[Union[int, Tuple[int, int]]] = None,
487
+ in_channels: int = 3,
488
+ out_channels: int = 3,
489
+ center_input_sample: bool = False,
490
+ time_embedding_type: str = "positional",
491
+ freq_shift: int = 0,
492
+ flip_sin_to_cos: bool = True,
493
+ down_block_types: Tuple[str, ...] = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
494
+ up_block_types: Tuple[str, ...] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
495
+ block_out_channels: Tuple[int, ...] = (224, 448, 672, 896),
496
+ layers_per_block: int = 2,
497
+ mid_block_scale_factor: float = 1,
498
+ downsample_padding: int = 1,
499
+ downsample_type: str = "conv",
500
+ upsample_type: str = "conv",
501
+ dropout: float = 0.0,
502
+ act_fn: str = "silu",
503
+ attention_head_dim: Optional[int] = 8,
504
+ norm_num_groups: int = 32,
505
+ attn_norm_num_groups: Optional[int] = None,
506
+ norm_eps: float = 1e-5,
507
+ resnet_time_scale_shift: str = "default",
508
+ add_attention: bool = True,
509
+ class_embed_type: Optional[str] = None,
510
+ num_class_embeds_floor_hue=NUM_CLASSES_FLOOR_HUE + 1,
511
+ num_class_embeds_object_hue=NUM_CLASSES_OBJECT_HUE + 1,
512
+ num_class_embeds_orientation=NUM_CLASSES_ORIENTATION + 1,
513
+ num_class_embeds_scale=NUM_CLASSES_SCALE + 1,
514
+ num_class_embeds_shape=NUM_CLASSES_SHAPE + 1,
515
+ num_class_embeds_wall_hue=NUM_CLASSES_WALL_HUE + 1,
516
+ num_train_timesteps: Optional[int] = None,
517
+ set_W_to_weight: Optional[bool] = True
518
+ ):
519
  super().__init__()
 
520
 
521
+ self.sample_size = sample_size
522
+ time_embed_dim = block_out_channels[0] * 4
523
+
524
+ # Check inputs
525
+ if len(down_block_types) != len(up_block_types):
526
+ raise ValueError(
527
+ 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}."
528
+ )
529
+
530
+ if len(block_out_channels) != len(down_block_types):
531
+ raise ValueError(
532
+ 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}."
533
+ )
534
+
535
+ # input
536
+ self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
537
+
538
+ # time
539
+ if time_embedding_type == "fourier":
540
+ self.time_proj = GaussianFourierProjection(embedding_size=block_out_channels[0], scale=16, set_W_to_weight=set_W_to_weight)
541
+ timestep_input_dim = 2 * block_out_channels[0]
542
+ elif time_embedding_type == "positional":
543
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
544
+ timestep_input_dim = block_out_channels[0]
545
+ elif time_embedding_type == "learned":
546
+ self.time_proj = nn.Embedding(num_train_timesteps, block_out_channels[0])
547
+ timestep_input_dim = block_out_channels[0]
548
+
549
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
550
+
551
+ # class embedding
552
+ if class_embed_type is None and num_class_embeds_floor_hue is not None:
553
+ self.class_embedding_floor_hue = nn.Embedding(num_class_embeds_floor_hue, time_embed_dim)
554
+ self.class_embedding_object_hue = nn.Embedding(num_class_embeds_object_hue, time_embed_dim)
555
+ self.class_embedding_orientation = nn.Embedding(num_class_embeds_orientation, time_embed_dim)
556
+ self.class_embedding_scale = nn.Embedding(num_class_embeds_scale, time_embed_dim)
557
+ self.class_embedding_shape = nn.Embedding(num_class_embeds_shape, time_embed_dim)
558
+ self.class_embedding_wall_hue = nn.Embedding(num_class_embeds_wall_hue, time_embed_dim)
559
+ elif class_embed_type == "timestep":
560
+ self.class_embedding_floor_hue = TimestepEmbedding(timestep_input_dim, time_embed_dim)
561
+ self.class_embedding_object_hue = TimestepEmbedding(timestep_input_dim, time_embed_dim)
562
+ self.class_embedding_orientation = TimestepEmbedding(timestep_input_dim, time_embed_dim)
563
+ self.class_embedding_scale = TimestepEmbedding(timestep_input_dim, time_embed_dim)
564
+ self.class_embedding_shape = TimestepEmbedding(timestep_input_dim, time_embed_dim)
565
+ self.class_embedding_wall_hue = TimestepEmbedding(timestep_input_dim, time_embed_dim)
566
+ elif class_embed_type == "identity":
567
+ self.class_embedding_floor_hue = nn.Identity(time_embed_dim, time_embed_dim)
568
+ self.class_embedding_object_hue = nn.Identity(time_embed_dim, time_embed_dim)
569
+ self.class_embedding_orientation = nn.Identity(time_embed_dim, time_embed_dim)
570
+ self.class_embedding_scale = nn.Identity(time_embed_dim, time_embed_dim)
571
+ self.class_embedding_shape = nn.Identity(time_embed_dim, time_embed_dim)
572
+ self.class_embedding_wall_hue = nn.Identity(time_embed_dim, time_embed_dim)
573
+ else:
574
+ self.class_embedding_floor_hue = None
575
+
576
+ self.down_blocks = nn.ModuleList([])
577
+ self.mid_block = None
578
+ self.up_blocks = nn.ModuleList([])
579
+
580
+ # down
581
+ output_channel = block_out_channels[0]
582
+ for i, down_block_type in enumerate(down_block_types):
583
+ input_channel = output_channel
584
+ output_channel = block_out_channels[i]
585
+ is_final_block = i == len(block_out_channels) - 1
586
+
587
+ down_block = get_down_block(
588
+ down_block_type,
589
+ num_layers=layers_per_block,
590
+ in_channels=input_channel,
591
+ out_channels=output_channel,
592
+ temb_channels=time_embed_dim,
593
+ add_downsample=not is_final_block,
594
+ resnet_eps=norm_eps,
595
+ resnet_act_fn=act_fn,
596
+ resnet_groups=norm_num_groups,
597
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
598
+ downsample_padding=downsample_padding,
599
+ resnet_time_scale_shift=resnet_time_scale_shift,
600
+ downsample_type=downsample_type,
601
+ dropout=dropout,
602
+ )
603
+ self.down_blocks.append(down_block)
604
+
605
+ # mid
606
+ self.mid_block = UNetMidBlock2D(
607
+ in_channels=block_out_channels[-1],
608
+ temb_channels=time_embed_dim,
609
+ dropout=dropout,
610
+ resnet_eps=norm_eps,
611
+ resnet_act_fn=act_fn,
612
+ output_scale_factor=mid_block_scale_factor,
613
+ resnet_time_scale_shift=resnet_time_scale_shift,
614
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1],
615
+ resnet_groups=norm_num_groups,
616
+ attn_groups=attn_norm_num_groups,
617
+ add_attention=add_attention,
618
+ )
619
+
620
+ # up
621
+ reversed_block_out_channels = list(reversed(block_out_channels))
622
+ output_channel = reversed_block_out_channels[0]
623
+ for i, up_block_type in enumerate(up_block_types):
624
+ prev_output_channel = output_channel
625
+ output_channel = reversed_block_out_channels[i]
626
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
627
+
628
+ is_final_block = i == len(block_out_channels) - 1
629
+
630
+ up_block = get_up_block(
631
+ up_block_type,
632
+ num_layers=layers_per_block + 1,
633
+ in_channels=input_channel,
634
+ out_channels=output_channel,
635
+ prev_output_channel=prev_output_channel,
636
+ temb_channels=time_embed_dim,
637
+ add_upsample=not is_final_block,
638
+ resnet_eps=norm_eps,
639
+ resnet_act_fn=act_fn,
640
+ resnet_groups=norm_num_groups,
641
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
642
+ resnet_time_scale_shift=resnet_time_scale_shift,
643
+ upsample_type=upsample_type,
644
+ dropout=dropout,
645
+ )
646
+ self.up_blocks.append(up_block)
647
+ prev_output_channel = output_channel
648
+
649
+ # out
650
+ num_groups_out = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4, 32)
651
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=num_groups_out, eps=norm_eps)
652
+ self.conv_act = nn.SiLU()
653
+ self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
654
+
655
+ def forward(
656
  self,
657
+ sample: torch.FloatTensor,
658
+ timestep: Union[torch.Tensor, float, int],
659
  class_labels: Optional[torch.Tensor] = None,
 
 
660
  return_dict: bool = True,
661
+ ) -> Union[UNet2DOutput, Tuple]:
 
662
  r"""
663
+ The [`UNet2DModel`] forward method.
664
  Args:
665
+ sample (`torch.FloatTensor`):
666
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
667
+ timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
668
+ class_labels (`torch.FloatTensor`, *optional*, defaults to `None`):
669
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
 
 
670
  return_dict (`bool`, *optional*, defaults to `True`):
671
+ Whether or not to return a [`~models.unet_2d.UNet2DOutput`] instead of a plain tuple.
672
  Returns:
673
+ [`~models.unet_2d.UNet2DOutput`] or `tuple`:
674
+ If `return_dict` is True, an [`~models.unet_2d.UNet2DOutput`] is returned, otherwise a `tuple` is
675
+ returned where the first element is the sample tensor.
676
  """
677
+ # 0. center input if necessary
678
+ if self.config.center_input_sample:
679
+ sample = 2 * sample - 1.0
680
+
681
+ # 1. time
682
+ timesteps = timestep
683
+ if not torch.is_tensor(timesteps):
684
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
685
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
686
+ timesteps = timesteps[None].to(sample.device)
687
 
688
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
689
+ timesteps = timesteps * torch.ones(sample.shape[0], dtype=timesteps.dtype, device=timesteps.device)
690
 
691
+ t_emb = self.time_proj(timesteps)
 
692
 
693
+ # timesteps does not contain any weights and will always return f32 tensors
694
+ # but time_embedding might actually be running in fp16. so we need to cast here.
695
+ # there might be better ways to encapsulate this.
696
+ t_emb = t_emb.to(dtype=self.dtype)
697
+ emb = self.time_embedding(t_emb)
698
 
699
+ if self.class_embedding_floor_hue is not None:
700
+ if class_labels is None:
701
+ raise ValueError("class_labels should be provided when doing class conditioning")
702
+ class_labels_floor_hue = class_labels[:, 0]
703
+ class_labels_object_hue = class_labels[:, 1]
704
+ class_labels_orientation = class_labels[:, 2]
705
+ class_labels_scale = class_labels[:, 3]
706
+ class_labels_shape = class_labels[:, 4]
707
+ class_labels_wall_hue = class_labels[:, 5]
708
+ if self.config.class_embed_type == "timestep":
709
+ class_labels_floor_hue = self.time_proj(class_labels_floor_hue)
710
+ class_labels_object_hue = self.time_proj(class_labels_object_hue)
711
+ class_labels_orientation = self.time_proj(class_labels_orientation)
712
+ class_labels_scale = self.time_proj(class_labels_scale)
713
+ class_labels_shape = self.time_proj(class_labels_shape)
714
+ class_labels_wall_hue = self.time_proj(class_labels_wall_hue)
715
 
716
+ def add_embedding_if_non_zero(class_labels, class_embedding):
717
+ # Create an output tensor initialized to zero of the required shape
718
+ output = torch.zeros((class_labels.size(0), emb.size(1)), device=emb.device)
 
719
 
720
+ # Check for non-zero indices
721
+ non_zero_indices = class_labels.nonzero(as_tuple=True)
 
722
 
723
+ if non_zero_indices[0].numel() > 0:
724
+ # Compute embeddings for non-zero indices only
725
+ embeddings = class_embedding(class_labels[non_zero_indices])
726
+ # Place computed embeddings back into the correct positions
727
+ output[non_zero_indices] = embeddings
728
 
729
+ return output
730
+
731
+ if self.class_embedding_floor_hue:
732
+ emb += self.class_embedding_floor_hue(class_labels_floor_hue)
733
+ if self.class_embedding_object_hue:
734
+ emb += self.class_embedding_object_hue(class_labels_object_hue)
735
+ if self.class_embedding_orientation:
736
+ emb += self.class_embedding_orientation(class_labels_orientation)
737
+ if self.class_embedding_scale:
738
+ emb += self.class_embedding_scale(class_labels_scale)
739
+ if self.class_embedding_shape:
740
+ emb += self.class_embedding_shape(class_labels_shape)
741
+ if self.class_embedding_wall_hue:
742
+ emb += self.class_embedding_wall_hue(class_labels_wall_hue)
743
+ elif self.class_embedding_floor_hue is None and class_labels is not None:
744
+ raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
745
+
746
+ # 2. pre-process
747
+ skip_sample = sample
748
+ sample = self.conv_in(sample)
749
+
750
+ # 3. down
751
+ down_block_res_samples = (sample,)
752
+ for downsample_block in self.down_blocks:
753
+ if hasattr(downsample_block, "skip_conv"):
754
+ sample, res_samples, skip_sample = downsample_block(
755
+ hidden_states=sample, temb=emb, skip_sample=skip_sample
756
+ )
757
+ else:
758
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
759
+
760
+ down_block_res_samples += res_samples
761
+
762
+ # 4. mid
763
+ sample = self.mid_block(sample, emb)
764
+
765
+ # 5. up
766
+ skip_sample = None
767
+ for upsample_block in self.up_blocks:
768
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
769
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
770
+
771
+ if hasattr(upsample_block, "skip_conv"):
772
+ sample, skip_sample = upsample_block(sample, res_samples, emb, skip_sample)
773
+ else:
774
+ sample = upsample_block(sample, res_samples, emb)
775
+
776
+ # 6. post-process
777
+ sample = self.conv_norm_out(sample)
778
+ sample = self.conv_act(sample)
779
+ sample = self.conv_out(sample)
780
+
781
+ if skip_sample is not None:
782
+ sample += skip_sample
783
+
784
+ if self.config.time_embedding_type == "fourier":
785
+ timesteps = timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]))))
786
+ sample = sample / timesteps
787
 
788
  if not return_dict:
789
  return (sample,)
790
+
791
+ return UNet2DOutput(sample=sample)