Diffusers
Safetensors
giulio98 commited on
Commit
95aff0a
·
verified ·
1 Parent(s): dc626e3

Update unet/conditional_unet_model.py

Browse files
Files changed (1) hide show
  1. unet/conditional_unet_model.py +415 -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
  """
@@ -33,6 +26,415 @@ class UNet2DOutput(BaseOutput):
33
  sample: torch.FloatTensor
34
 
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  class MultiLabelConditionalUNet2DModelForShapes3D(ModelMixin, ConfigMixin):
37
  r"""
38
  A 2D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.
@@ -336,17 +738,17 @@ class MultiLabelConditionalUNet2DModelForShapes3D(ModelMixin, ConfigMixin):
336
  return output
337
 
338
  if self.class_embedding_floor_hue:
339
- emb += add_embedding_if_non_zero(class_labels_floor_hue, self.class_embedding_floor_hue)
340
  if self.class_embedding_object_hue:
341
- emb += add_embedding_if_non_zero(class_labels_object_hue, self.class_embedding_object_hue)
342
  if self.class_embedding_orientation:
343
- emb += add_embedding_if_non_zero(class_labels_orientation, self.class_embedding_orientation)
344
  if self.class_embedding_scale:
345
- emb += add_embedding_if_non_zero(class_labels_scale, self.class_embedding_scale)
346
  if self.class_embedding_shape:
347
- emb += add_embedding_if_non_zero(class_labels_shape, self.class_embedding_shape)
348
  if self.class_embedding_wall_hue:
349
- emb += add_embedding_if_non_zero(class_labels_wall_hue, self.class_embedding_wall_hue)
350
  elif self.class_embedding_floor_hue is None and class_labels is not None:
351
  raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
352
 
 
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
  """
 
26
  sample: torch.FloatTensor
27
 
28
 
29
+ class UNet2DModel(ModelMixin, ConfigMixin):
30
+ r"""
31
+ A 2D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.
32
+
33
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
34
+ for all models (such as downloading or saving).
35
+
36
+ Parameters:
37
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
38
+ Height and width of input/output sample. Dimensions must be a multiple of `2 ** (len(block_out_channels) -
39
+ 1)`.
40
+ in_channels (`int`, *optional*, defaults to 3): Number of channels in the input sample.
41
+ out_channels (`int`, *optional*, defaults to 3): Number of channels in the output.
42
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
43
+ time_embedding_type (`str`, *optional*, defaults to `"positional"`): Type of time embedding to use.
44
+ freq_shift (`int`, *optional*, defaults to 0): Frequency shift for Fourier time embedding.
45
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
46
+ Whether to flip sin to cos for Fourier time embedding.
47
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")`):
48
+ Tuple of downsample block types.
49
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2D"`):
50
+ Block type for middle of UNet, it can be either `UNetMidBlock2D` or `UnCLIPUNetMidBlock2D`.
51
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")`):
52
+ Tuple of upsample block types.
53
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(224, 448, 672, 896)`):
54
+ Tuple of block output channels.
55
+ layers_per_block (`int`, *optional*, defaults to `2`): The number of layers per block.
56
+ mid_block_scale_factor (`float`, *optional*, defaults to `1`): The scale factor for the mid block.
57
+ downsample_padding (`int`, *optional*, defaults to `1`): The padding for the downsample convolution.
58
+ downsample_type (`str`, *optional*, defaults to `conv`):
59
+ The downsample type for downsampling layers. Choose between "conv" and "resnet"
60
+ upsample_type (`str`, *optional*, defaults to `conv`):
61
+ The upsample type for upsampling layers. Choose between "conv" and "resnet"
62
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
63
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
64
+ attention_head_dim (`int`, *optional*, defaults to `8`): The attention head dimension.
65
+ norm_num_groups (`int`, *optional*, defaults to `32`): The number of groups for normalization.
66
+ attn_norm_num_groups (`int`, *optional*, defaults to `None`):
67
+ If set to an integer, a group norm layer will be created in the mid block's [`Attention`] layer with the
68
+ given number of groups. If left as `None`, the group norm layer will only be created if
69
+ `resnet_time_scale_shift` is set to `default`, and if created will have `norm_num_groups` groups.
70
+ norm_eps (`float`, *optional*, defaults to `1e-5`): The epsilon for normalization.
71
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
72
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
73
+ class_embed_type (`str`, *optional*, defaults to `None`):
74
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
75
+ `"timestep"`, or `"identity"`.
76
+ num_class_embeds (`int`, *optional*, defaults to `None`):
77
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim` when performing class
78
+ conditioning with `class_embed_type` equal to `None`.
79
+ """
80
+
81
+ @register_to_config
82
+ def __init__(
83
+ self,
84
+ sample_size: Optional[Union[int, Tuple[int, int]]] = None,
85
+ in_channels: int = 3,
86
+ out_channels: int = 3,
87
+ center_input_sample: bool = False,
88
+ time_embedding_type: str = "positional",
89
+ freq_shift: int = 0,
90
+ flip_sin_to_cos: bool = True,
91
+ down_block_types: Tuple[str, ...] = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
92
+ up_block_types: Tuple[str, ...] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
93
+ block_out_channels: Tuple[int, ...] = (224, 448, 672, 896),
94
+ layers_per_block: int = 2,
95
+ mid_block_scale_factor: float = 1,
96
+ downsample_padding: int = 1,
97
+ downsample_type: str = "conv",
98
+ upsample_type: str = "conv",
99
+ dropout: float = 0.0,
100
+ act_fn: str = "silu",
101
+ attention_head_dim: Optional[int] = 8,
102
+ norm_num_groups: int = 32,
103
+ attn_norm_num_groups: Optional[int] = None,
104
+ norm_eps: float = 1e-5,
105
+ resnet_time_scale_shift: str = "default",
106
+ add_attention: bool = True,
107
+ class_embed_type: Optional[str] = None,
108
+ num_class_embeds: Optional[int] = None,
109
+ num_train_timesteps: Optional[int] = None,
110
+ set_W_to_weight: Optional[bool] = True
111
+ ):
112
+ super().__init__()
113
+
114
+ self.sample_size = sample_size
115
+ time_embed_dim = block_out_channels[0] * 4
116
+
117
+ # Check inputs
118
+ if len(down_block_types) != len(up_block_types):
119
+ raise ValueError(
120
+ 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}."
121
+ )
122
+
123
+ if len(block_out_channels) != len(down_block_types):
124
+ raise ValueError(
125
+ 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}."
126
+ )
127
+
128
+ # input
129
+ self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
130
+
131
+ # time
132
+ if time_embedding_type == "fourier":
133
+ self.time_proj = GaussianFourierProjection(embedding_size=block_out_channels[0], scale=16, set_W_to_weight=set_W_to_weight)
134
+ timestep_input_dim = 2 * block_out_channels[0]
135
+ elif time_embedding_type == "positional":
136
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
137
+ timestep_input_dim = block_out_channels[0]
138
+ elif time_embedding_type == "learned":
139
+ self.time_proj = nn.Embedding(num_train_timesteps, block_out_channels[0])
140
+ timestep_input_dim = block_out_channels[0]
141
+
142
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
143
+
144
+ # class embedding
145
+ if class_embed_type is None and num_class_embeds is not None:
146
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
147
+ elif class_embed_type == "timestep":
148
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
149
+ elif class_embed_type == "identity":
150
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
151
+ else:
152
+ self.class_embedding = None
153
+
154
+ self.down_blocks = nn.ModuleList([])
155
+ self.mid_block = None
156
+ self.up_blocks = nn.ModuleList([])
157
+
158
+ # down
159
+ output_channel = block_out_channels[0]
160
+ for i, down_block_type in enumerate(down_block_types):
161
+ input_channel = output_channel
162
+ output_channel = block_out_channels[i]
163
+ is_final_block = i == len(block_out_channels) - 1
164
+
165
+ down_block = get_down_block(
166
+ down_block_type,
167
+ num_layers=layers_per_block,
168
+ in_channels=input_channel,
169
+ out_channels=output_channel,
170
+ temb_channels=time_embed_dim,
171
+ add_downsample=not is_final_block,
172
+ resnet_eps=norm_eps,
173
+ resnet_act_fn=act_fn,
174
+ resnet_groups=norm_num_groups,
175
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
176
+ downsample_padding=downsample_padding,
177
+ resnet_time_scale_shift=resnet_time_scale_shift,
178
+ downsample_type=downsample_type,
179
+ dropout=dropout,
180
+ )
181
+ self.down_blocks.append(down_block)
182
+
183
+ # mid
184
+ self.mid_block = UNetMidBlock2D(
185
+ in_channels=block_out_channels[-1],
186
+ temb_channels=time_embed_dim,
187
+ dropout=dropout,
188
+ resnet_eps=norm_eps,
189
+ resnet_act_fn=act_fn,
190
+ output_scale_factor=mid_block_scale_factor,
191
+ resnet_time_scale_shift=resnet_time_scale_shift,
192
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1],
193
+ resnet_groups=norm_num_groups,
194
+ attn_groups=attn_norm_num_groups,
195
+ add_attention=add_attention,
196
+ )
197
+
198
+ # up
199
+ reversed_block_out_channels = list(reversed(block_out_channels))
200
+ output_channel = reversed_block_out_channels[0]
201
+ for i, up_block_type in enumerate(up_block_types):
202
+ prev_output_channel = output_channel
203
+ output_channel = reversed_block_out_channels[i]
204
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
205
+
206
+ is_final_block = i == len(block_out_channels) - 1
207
+
208
+ up_block = get_up_block(
209
+ up_block_type,
210
+ num_layers=layers_per_block + 1,
211
+ in_channels=input_channel,
212
+ out_channels=output_channel,
213
+ prev_output_channel=prev_output_channel,
214
+ temb_channels=time_embed_dim,
215
+ add_upsample=not is_final_block,
216
+ resnet_eps=norm_eps,
217
+ resnet_act_fn=act_fn,
218
+ resnet_groups=norm_num_groups,
219
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
220
+ resnet_time_scale_shift=resnet_time_scale_shift,
221
+ upsample_type=upsample_type,
222
+ dropout=dropout,
223
+ )
224
+ self.up_blocks.append(up_block)
225
+ prev_output_channel = output_channel
226
+
227
+ # out
228
+ num_groups_out = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4, 32)
229
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=num_groups_out, eps=norm_eps)
230
+ self.conv_act = nn.SiLU()
231
+ self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
232
+
233
+ def forward(
234
+ self,
235
+ sample: torch.FloatTensor,
236
+ timestep: Union[torch.Tensor, float, int],
237
+ class_labels: Optional[torch.Tensor] = None,
238
+ return_dict: bool = True,
239
+ ) -> Union[UNet2DOutput, Tuple]:
240
+ r"""
241
+ The [`UNet2DModel`] forward method.
242
+
243
+ Args:
244
+ sample (`torch.FloatTensor`):
245
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
246
+ timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
247
+ class_labels (`torch.FloatTensor`, *optional*, defaults to `None`):
248
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
249
+ return_dict (`bool`, *optional*, defaults to `True`):
250
+ Whether or not to return a [`~models.unet_2d.UNet2DOutput`] instead of a plain tuple.
251
+
252
+ Returns:
253
+ [`~models.unet_2d.UNet2DOutput`] or `tuple`:
254
+ If `return_dict` is True, an [`~models.unet_2d.UNet2DOutput`] is returned, otherwise a `tuple` is
255
+ returned where the first element is the sample tensor.
256
+ """
257
+ # 0. center input if necessary
258
+ if self.config.center_input_sample:
259
+ sample = 2 * sample - 1.0
260
+
261
+ # 1. time
262
+ timesteps = timestep
263
+ if not torch.is_tensor(timesteps):
264
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
265
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
266
+ timesteps = timesteps[None].to(sample.device)
267
+
268
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
269
+ timesteps = timesteps * torch.ones(sample.shape[0], dtype=timesteps.dtype, device=timesteps.device)
270
+
271
+ t_emb = self.time_proj(timesteps)
272
+
273
+ # timesteps does not contain any weights and will always return f32 tensors
274
+ # but time_embedding might actually be running in fp16. so we need to cast here.
275
+ # there might be better ways to encapsulate this.
276
+ t_emb = t_emb.to(dtype=self.dtype)
277
+ emb = self.time_embedding(t_emb)
278
+
279
+ if self.class_embedding is not None:
280
+ if class_labels is None:
281
+ raise ValueError("class_labels should be provided when doing class conditioning")
282
+
283
+ if self.config.class_embed_type == "timestep":
284
+ class_labels = self.time_proj(class_labels)
285
+
286
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
287
+ emb = emb + class_emb
288
+ elif self.class_embedding is None and class_labels is not None:
289
+ raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
290
+
291
+ # 2. pre-process
292
+ skip_sample = sample
293
+ sample = self.conv_in(sample)
294
+
295
+ # 3. down
296
+ down_block_res_samples = (sample,)
297
+ for downsample_block in self.down_blocks:
298
+ if hasattr(downsample_block, "skip_conv"):
299
+ sample, res_samples, skip_sample = downsample_block(
300
+ hidden_states=sample, temb=emb, skip_sample=skip_sample
301
+ )
302
+ else:
303
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
304
+
305
+ down_block_res_samples += res_samples
306
+
307
+ # 4. mid
308
+ sample = self.mid_block(sample, emb)
309
+
310
+ # 5. up
311
+ skip_sample = None
312
+ for upsample_block in self.up_blocks:
313
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
314
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
315
+
316
+ if hasattr(upsample_block, "skip_conv"):
317
+ sample, skip_sample = upsample_block(sample, res_samples, emb, skip_sample)
318
+ else:
319
+ sample = upsample_block(sample, res_samples, emb)
320
+
321
+ # 6. post-process
322
+ sample = self.conv_norm_out(sample)
323
+ sample = self.conv_act(sample)
324
+ sample = self.conv_out(sample)
325
+
326
+ if skip_sample is not None:
327
+ sample += skip_sample
328
+
329
+ if self.config.time_embedding_type == "fourier":
330
+ timesteps = timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]))))
331
+ sample = sample / timesteps
332
+
333
+ if not return_dict:
334
+ return (sample,)
335
+
336
+ return UNet2DOutput(sample=sample)
337
+
338
+ NUM_CLASSES_FLOOR_HUE = 10
339
+ NUM_CLASSES_OBJECT_HUE = 10
340
+ NUM_CLASSES_ORIENTATION = 15
341
+ NUM_CLASSES_SCALE = 8
342
+ NUM_CLASSES_SHAPE = 4
343
+ NUM_CLASSES_WALL_HUE = 10
344
+ class ClassConditionedUnetForShapes3D(ModelMixin, ConfigMixin):
345
+ @register_to_config
346
+ def __init__(self,
347
+ num_classes_floor_hue=NUM_CLASSES_FLOOR_HUE + 1,
348
+ num_classes_object_hue=NUM_CLASSES_OBJECT_HUE + 1,
349
+ num_classes_orientation=NUM_CLASSES_ORIENTATION + 1,
350
+ num_classes_scale=NUM_CLASSES_SCALE + 1,
351
+ num_classes_shape=NUM_CLASSES_SHAPE + 1,
352
+ num_classes_wall_hue=NUM_CLASSES_WALL_HUE + 1,
353
+ sample_size: Optional[Union[int, Tuple[int, int]]] = None,
354
+ in_channels: int = 3,
355
+ out_channels: int = 3,
356
+ center_input_sample: bool = False,
357
+ time_embedding_type: str = "positional",
358
+ freq_shift: int = 0,
359
+ flip_sin_to_cos: bool = True,
360
+ down_block_types: Tuple[str, ...] = (
361
+ "DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
362
+ up_block_types: Tuple[str, ...] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
363
+ block_out_channels: Tuple[int, ...] = (224, 448, 672, 896),
364
+ layers_per_block: int = 2,
365
+ mid_block_scale_factor: float = 1,
366
+ downsample_padding: int = 1,
367
+ downsample_type: str = "conv",
368
+ upsample_type: str = "conv",
369
+ dropout: float = 0.0,
370
+ act_fn: str = "silu",
371
+ attention_head_dim: Optional[int] = 8,
372
+ norm_num_groups: int = 32,
373
+ attn_norm_num_groups: Optional[int] = None,
374
+ norm_eps: float = 1e-5,
375
+ resnet_time_scale_shift: str = "default",
376
+ add_attention: bool = True,
377
+ class_embed_type: Optional[str] = None,
378
+ num_class_embeds: Optional[int] = None,
379
+ num_train_timesteps: Optional[int] = None,
380
+ set_W_to_weight: Optional[bool] = True
381
+ ):
382
+ super().__init__()
383
+ self.class_floor_hue = nn.Embedding(num_classes_floor_hue, num_classes_floor_hue)
384
+ self.class_object_hue = nn.Embedding(num_classes_object_hue, num_classes_object_hue)
385
+ self.class_orientation = nn.Embedding(num_classes_orientation, num_classes_orientation)
386
+ self.class_scale = nn.Embedding(num_classes_scale, num_classes_scale)
387
+ self.class_shape = nn.Embedding(num_classes_shape, num_classes_shape)
388
+ self.class_wall_hue = nn.Embedding(num_classes_wall_hue, num_classes_wall_hue)
389
+ self.model = UNet2DModel(
390
+ sample_size=sample_size,
391
+ in_channels=in_channels,
392
+ out_channels=out_channels,
393
+ center_input_sample=center_input_sample,
394
+ time_embedding_type=time_embedding_type,
395
+ freq_shift=freq_shift,
396
+ flip_sin_to_cos=flip_sin_to_cos,
397
+ down_block_types=down_block_types,
398
+ up_block_types=up_block_types,
399
+ block_out_channels=block_out_channels,
400
+ layers_per_block=layers_per_block,
401
+ mid_block_scale_factor=mid_block_scale_factor,
402
+ downsample_padding=downsample_padding,
403
+ downsample_type=downsample_type,
404
+ upsample_type=upsample_type,
405
+ dropout=dropout,
406
+ act_fn=act_fn,
407
+ attention_head_dim=attention_head_dim,
408
+ norm_num_groups=norm_num_groups,
409
+ attn_norm_num_groups=attn_norm_num_groups,
410
+ norm_eps=norm_eps,
411
+ resnet_time_scale_shift=resnet_time_scale_shift,
412
+ add_attention=add_attention,
413
+ class_embed_type=class_embed_type,
414
+ num_class_embeds=num_class_embeds,
415
+ num_train_timesteps=num_train_timesteps,
416
+ set_W_to_weight=set_W_to_weight
417
+ )
418
+
419
+ def forward(self, x, t, class_labels):
420
+ bs, ch, w, h = x.shape
421
+
422
+ class_cond_floor_hue = self.class_floor_hue(class_labels[:, 0])
423
+ 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)
424
+ class_cond_object_hue = self.class_object_hue(class_labels[:, 1])
425
+ 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)
426
+ class_cond_orientation = self.class_orientation(class_labels[:, 2])
427
+ class_cond_orientation = class_cond_orientation.view(bs, class_cond_orientation.shape[1], 1, 1).expand(bs, class_cond_orientation.shape[1], w, h)
428
+ class_cond_scale = self.class_scale(class_labels[:, 3])
429
+ class_cond_scale = class_cond_scale.view(bs, class_cond_scale.shape[1], 1, 1).expand(bs, class_cond_scale.shape[1], w, h)
430
+ class_cond_shape = self.class_shape(class_labels[:, 4])
431
+ class_cond_shape = class_cond_shape.view(bs, class_cond_shape.shape[1], 1, 1).expand(bs, class_cond_shape.shape[1], w, h)
432
+ class_cond_wall_hue = self.class_wall_hue(class_labels[:, 5])
433
+ 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)
434
+ 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)
435
+ return self.model(net_input, t)
436
+
437
+
438
  class MultiLabelConditionalUNet2DModelForShapes3D(ModelMixin, ConfigMixin):
439
  r"""
440
  A 2D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.
 
738
  return output
739
 
740
  if self.class_embedding_floor_hue:
741
+ emb += self.class_embedding_floor_hue(class_labels_floor_hue)
742
  if self.class_embedding_object_hue:
743
+ emb += self.class_embedding_object_hue(class_labels_object_hue)
744
  if self.class_embedding_orientation:
745
+ emb += self.class_embedding_orientation(class_labels_orientation)
746
  if self.class_embedding_scale:
747
+ emb += self.class_embedding_scale(class_labels_scale)
748
  if self.class_embedding_shape:
749
+ emb += self.class_embedding_shape(class_labels_shape)
750
  if self.class_embedding_wall_hue:
751
+ emb += self.class_embedding_wall_hue(class_labels_wall_hue)
752
  elif self.class_embedding_floor_hue is None and class_labels is not None:
753
  raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
754