giulio98 commited on
Commit
283b97d
·
verified ·
1 Parent(s): 22385b2

Update unet/conditional_unet_model.py

Browse files
Files changed (1) hide show
  1. unet/conditional_unet_model.py +411 -13
unet/conditional_unet_model.py CHANGED
@@ -13,13 +13,6 @@ from diffusers.models.embeddings import GaussianFourierProjection, TimestepEmbed
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
- NUM_CLASSES_FLOOR_HUE = 10
17
- NUM_CLASSES_OBJECT_HUE = 10
18
- NUM_CLASSES_ORIENTATION = 15
19
- NUM_CLASSES_SCALE = 8
20
- NUM_CLASSES_SHAPE = 4
21
- NUM_CLASSES_WALL_HUE = 10
22
-
23
  @dataclass
24
  class UNet2DOutput(BaseOutput):
25
  """
@@ -32,6 +25,411 @@ class UNet2DOutput(BaseOutput):
32
  sample: torch.FloatTensor
33
 
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  class MultiLabelConditionalUNet2DModelForShapes3D(ModelMixin, ConfigMixin):
36
  r"""
37
  A 2D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.
@@ -331,17 +729,17 @@ class MultiLabelConditionalUNet2DModelForShapes3D(ModelMixin, ConfigMixin):
331
  return output
332
 
333
  if self.class_embedding_floor_hue:
334
- emb += add_embedding_if_non_zero(class_labels_floor_hue, self.class_embedding_floor_hue)
335
  if self.class_embedding_object_hue:
336
- emb += add_embedding_if_non_zero(class_labels_object_hue, self.class_embedding_object_hue)
337
  if self.class_embedding_orientation:
338
- emb += add_embedding_if_non_zero(class_labels_orientation, self.class_embedding_orientation)
339
  if self.class_embedding_scale:
340
- emb += add_embedding_if_non_zero(class_labels_scale, self.class_embedding_scale)
341
  if self.class_embedding_shape:
342
- emb += add_embedding_if_non_zero(class_labels_shape, self.class_embedding_shape)
343
  if self.class_embedding_wall_hue:
344
- emb += add_embedding_if_non_zero(class_labels_wall_hue, self.class_embedding_wall_hue)
345
  elif self.class_embedding_floor_hue is None and class_labels is not None:
346
  raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
347
 
 
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
  """
 
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.
 
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