giulio98 commited on
Commit
b9f7d09
·
verified ·
1 Parent(s): b500214

Create unet/conditional_unet_model.py

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