Diffusers
Safetensors
giulio98 commited on
Commit
f69a6b6
·
verified ·
1 Parent(s): eb46b4a

Create conditional_unet_model.py

Browse files
Files changed (1) hide show
  1. unet/conditional_unet_model.py +391 -0
unet/conditional_unet_model.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
21
+ Args:
22
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
23
+ The hidden states output from the last layer of the model.
24
+ """
25
+
26
+ sample: torch.FloatTensor
27
+
28
+
29
+ class MultiLabelConditionalUNet2DModelForShapes3D(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_floor_hue=NUM_CLASSES_FLOOR_HUE + 1,
109
+ num_class_embeds_object_hue=NUM_CLASSES_OBJECT_HUE + 1,
110
+ num_class_embeds_orientation=NUM_CLASSES_ORIENTATION + 1,
111
+ num_class_embeds_scale=NUM_CLASSES_SCALE + 1,
112
+ num_class_embeds_shape=NUM_CLASSES_SHAPE + 1,
113
+ num_class_embeds_wall_hue=NUM_CLASSES_WALL_HUE + 1,
114
+ num_train_timesteps: Optional[int] = None,
115
+ set_W_to_weight: Optional[bool] = True
116
+ ):
117
+ super().__init__()
118
+
119
+ self.sample_size = sample_size
120
+ time_embed_dim = block_out_channels[0] * 4
121
+
122
+ # Check inputs
123
+ if len(down_block_types) != len(up_block_types):
124
+ raise ValueError(
125
+ 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}."
126
+ )
127
+
128
+ if len(block_out_channels) != len(down_block_types):
129
+ raise ValueError(
130
+ 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}."
131
+ )
132
+
133
+ # input
134
+ self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
135
+
136
+ # time
137
+ if time_embedding_type == "fourier":
138
+ self.time_proj = GaussianFourierProjection(embedding_size=block_out_channels[0], scale=16, set_W_to_weight=set_W_to_weight)
139
+ timestep_input_dim = 2 * block_out_channels[0]
140
+ elif time_embedding_type == "positional":
141
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
142
+ timestep_input_dim = block_out_channels[0]
143
+ elif time_embedding_type == "learned":
144
+ self.time_proj = nn.Embedding(num_train_timesteps, block_out_channels[0])
145
+ timestep_input_dim = block_out_channels[0]
146
+
147
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
148
+
149
+ # class embedding
150
+ if class_embed_type is None and num_class_embeds_floor_hue is not None:
151
+ self.class_embedding_floor_hue = nn.Embedding(num_class_embeds_floor_hue, time_embed_dim)
152
+ self.class_embedding_object_hue = nn.Embedding(num_class_embeds_object_hue, time_embed_dim)
153
+ self.class_embedding_orientation = nn.Embedding(num_class_embeds_orientation, time_embed_dim)
154
+ self.class_embedding_scale = nn.Embedding(num_class_embeds_scale, time_embed_dim)
155
+ self.class_embedding_shape = nn.Embedding(num_class_embeds_shape, time_embed_dim)
156
+ self.class_embedding_wall_hue = nn.Embedding(num_class_embeds_wall_hue, time_embed_dim)
157
+ elif class_embed_type == "timestep":
158
+ self.class_embedding_floor_hue = TimestepEmbedding(timestep_input_dim, time_embed_dim)
159
+ self.class_embedding_object_hue = TimestepEmbedding(timestep_input_dim, time_embed_dim)
160
+ self.class_embedding_orientation = TimestepEmbedding(timestep_input_dim, time_embed_dim)
161
+ self.class_embedding_scale = TimestepEmbedding(timestep_input_dim, time_embed_dim)
162
+ self.class_embedding_shape = TimestepEmbedding(timestep_input_dim, time_embed_dim)
163
+ self.class_embedding_wall_hue = TimestepEmbedding(timestep_input_dim, time_embed_dim)
164
+ elif class_embed_type == "identity":
165
+ self.class_embedding_floor_hue = nn.Identity(time_embed_dim, time_embed_dim)
166
+ self.class_embedding_object_hue = nn.Identity(time_embed_dim, time_embed_dim)
167
+ self.class_embedding_orientation = nn.Identity(time_embed_dim, time_embed_dim)
168
+ self.class_embedding_scale = nn.Identity(time_embed_dim, time_embed_dim)
169
+ self.class_embedding_shape = nn.Identity(time_embed_dim, time_embed_dim)
170
+ self.class_embedding_wall_hue = nn.Identity(time_embed_dim, time_embed_dim)
171
+ else:
172
+ self.class_embedding_floor_hue = None
173
+
174
+ self.down_blocks = nn.ModuleList([])
175
+ self.mid_block = None
176
+ self.up_blocks = nn.ModuleList([])
177
+
178
+ # down
179
+ output_channel = block_out_channels[0]
180
+ for i, down_block_type in enumerate(down_block_types):
181
+ input_channel = output_channel
182
+ output_channel = block_out_channels[i]
183
+ is_final_block = i == len(block_out_channels) - 1
184
+
185
+ down_block = get_down_block(
186
+ down_block_type,
187
+ num_layers=layers_per_block,
188
+ in_channels=input_channel,
189
+ out_channels=output_channel,
190
+ temb_channels=time_embed_dim,
191
+ add_downsample=not is_final_block,
192
+ resnet_eps=norm_eps,
193
+ resnet_act_fn=act_fn,
194
+ resnet_groups=norm_num_groups,
195
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
196
+ downsample_padding=downsample_padding,
197
+ resnet_time_scale_shift=resnet_time_scale_shift,
198
+ downsample_type=downsample_type,
199
+ dropout=dropout,
200
+ )
201
+ self.down_blocks.append(down_block)
202
+
203
+ # mid
204
+ self.mid_block = UNetMidBlock2D(
205
+ in_channels=block_out_channels[-1],
206
+ temb_channels=time_embed_dim,
207
+ dropout=dropout,
208
+ resnet_eps=norm_eps,
209
+ resnet_act_fn=act_fn,
210
+ output_scale_factor=mid_block_scale_factor,
211
+ resnet_time_scale_shift=resnet_time_scale_shift,
212
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1],
213
+ resnet_groups=norm_num_groups,
214
+ attn_groups=attn_norm_num_groups,
215
+ add_attention=add_attention,
216
+ )
217
+
218
+ # up
219
+ reversed_block_out_channels = list(reversed(block_out_channels))
220
+ output_channel = reversed_block_out_channels[0]
221
+ for i, up_block_type in enumerate(up_block_types):
222
+ prev_output_channel = output_channel
223
+ output_channel = reversed_block_out_channels[i]
224
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
225
+
226
+ is_final_block = i == len(block_out_channels) - 1
227
+
228
+ up_block = get_up_block(
229
+ up_block_type,
230
+ num_layers=layers_per_block + 1,
231
+ in_channels=input_channel,
232
+ out_channels=output_channel,
233
+ prev_output_channel=prev_output_channel,
234
+ temb_channels=time_embed_dim,
235
+ add_upsample=not is_final_block,
236
+ resnet_eps=norm_eps,
237
+ resnet_act_fn=act_fn,
238
+ resnet_groups=norm_num_groups,
239
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
240
+ resnet_time_scale_shift=resnet_time_scale_shift,
241
+ upsample_type=upsample_type,
242
+ dropout=dropout,
243
+ )
244
+ self.up_blocks.append(up_block)
245
+ prev_output_channel = output_channel
246
+
247
+ # out
248
+ num_groups_out = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4, 32)
249
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=num_groups_out, eps=norm_eps)
250
+ self.conv_act = nn.SiLU()
251
+ self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
252
+
253
+ def forward(
254
+ self,
255
+ sample: torch.FloatTensor,
256
+ timestep: Union[torch.Tensor, float, int],
257
+ class_labels: Optional[torch.Tensor] = None,
258
+ return_dict: bool = True,
259
+ ) -> Union[UNet2DOutput, Tuple]:
260
+ r"""
261
+ The [`UNet2DModel`] forward method.
262
+
263
+ Args:
264
+ sample (`torch.FloatTensor`):
265
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
266
+ timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
267
+ class_labels (`torch.FloatTensor`, *optional*, defaults to `None`):
268
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
269
+ return_dict (`bool`, *optional*, defaults to `True`):
270
+ Whether or not to return a [`~models.unet_2d.UNet2DOutput`] instead of a plain tuple.
271
+
272
+ Returns:
273
+ [`~models.unet_2d.UNet2DOutput`] or `tuple`:
274
+ If `return_dict` is True, an [`~models.unet_2d.UNet2DOutput`] is returned, otherwise a `tuple` is
275
+ returned where the first element is the sample tensor.
276
+ """
277
+ # 0. center input if necessary
278
+ if self.config.center_input_sample:
279
+ sample = 2 * sample - 1.0
280
+
281
+ # 1. time
282
+ timesteps = timestep
283
+ if not torch.is_tensor(timesteps):
284
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
285
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
286
+ timesteps = timesteps[None].to(sample.device)
287
+
288
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
289
+ timesteps = timesteps * torch.ones(sample.shape[0], dtype=timesteps.dtype, device=timesteps.device)
290
+
291
+ t_emb = self.time_proj(timesteps)
292
+
293
+ # timesteps does not contain any weights and will always return f32 tensors
294
+ # but time_embedding might actually be running in fp16. so we need to cast here.
295
+ # there might be better ways to encapsulate this.
296
+ t_emb = t_emb.to(dtype=self.dtype)
297
+ emb = self.time_embedding(t_emb)
298
+
299
+ if self.class_embedding_floor_hue is not None:
300
+ if class_labels is None:
301
+ raise ValueError("class_labels should be provided when doing class conditioning")
302
+ class_labels_floor_hue = class_labels[:, 0]
303
+ class_labels_object_hue = class_labels[:, 1]
304
+ class_labels_orientation = class_labels[:, 2]
305
+ class_labels_scale = class_labels[:, 3]
306
+ class_labels_shape = class_labels[:, 4]
307
+ class_labels_wall_hue = class_labels[:, 5]
308
+ if self.config.class_embed_type == "timestep":
309
+ class_labels_floor_hue = self.time_proj(class_labels_floor_hue)
310
+ class_labels_object_hue = self.time_proj(class_labels_object_hue)
311
+ class_labels_orientation = self.time_proj(class_labels_orientation)
312
+ class_labels_scale = self.time_proj(class_labels_scale)
313
+ class_labels_shape = self.time_proj(class_labels_shape)
314
+ class_labels_wall_hue = self.time_proj(class_labels_wall_hue)
315
+
316
+ def add_embedding_if_non_zero(class_labels, class_embedding):
317
+ # Create an output tensor initialized to zero of the required shape
318
+ output = torch.zeros((class_labels.size(0), emb.size(1)), device=emb.device)
319
+
320
+ # Check for non-zero indices
321
+ non_zero_indices = class_labels.nonzero(as_tuple=True)
322
+
323
+ if non_zero_indices[0].numel() > 0:
324
+ # Compute embeddings for non-zero indices only
325
+ embeddings = class_embedding(class_labels[non_zero_indices])
326
+ # Place computed embeddings back into the correct positions
327
+ output[non_zero_indices] = embeddings
328
+
329
+ return output
330
+
331
+ if self.class_embedding_floor_hue:
332
+ emb += add_embedding_if_non_zero(class_labels_floor_hue, self.class_embedding_floor_hue)
333
+ if self.class_embedding_object_hue:
334
+ emb += add_embedding_if_non_zero(class_labels_object_hue, self.class_embedding_object_hue)
335
+ if self.class_embedding_orientation:
336
+ emb += add_embedding_if_non_zero(class_labels_orientation, self.class_embedding_orientation)
337
+ if self.class_embedding_scale:
338
+ emb += add_embedding_if_non_zero(class_labels_scale, self.class_embedding_scale)
339
+ if self.class_embedding_shape:
340
+ emb += add_embedding_if_non_zero(class_labels_shape, self.class_embedding_shape)
341
+ if self.class_embedding_wall_hue:
342
+ emb += add_embedding_if_non_zero(class_labels_wall_hue, self.class_embedding_wall_hue)
343
+ elif self.class_embedding_floor_hue is None and class_labels is not None:
344
+ raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
345
+
346
+ # 2. pre-process
347
+ skip_sample = sample
348
+ sample = self.conv_in(sample)
349
+
350
+ # 3. down
351
+ down_block_res_samples = (sample,)
352
+ for downsample_block in self.down_blocks:
353
+ if hasattr(downsample_block, "skip_conv"):
354
+ sample, res_samples, skip_sample = downsample_block(
355
+ hidden_states=sample, temb=emb, skip_sample=skip_sample
356
+ )
357
+ else:
358
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
359
+
360
+ down_block_res_samples += res_samples
361
+
362
+ # 4. mid
363
+ sample = self.mid_block(sample, emb)
364
+
365
+ # 5. up
366
+ skip_sample = None
367
+ for upsample_block in self.up_blocks:
368
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
369
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
370
+
371
+ if hasattr(upsample_block, "skip_conv"):
372
+ sample, skip_sample = upsample_block(sample, res_samples, emb, skip_sample)
373
+ else:
374
+ sample = upsample_block(sample, res_samples, emb)
375
+
376
+ # 6. post-process
377
+ sample = self.conv_norm_out(sample)
378
+ sample = self.conv_act(sample)
379
+ sample = self.conv_out(sample)
380
+
381
+ if skip_sample is not None:
382
+ sample += skip_sample
383
+
384
+ if self.config.time_embedding_type == "fourier":
385
+ timesteps = timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]))))
386
+ sample = sample / timesteps
387
+
388
+ if not return_dict:
389
+ return (sample,)
390
+
391
+ return UNet2DOutput(sample=sample)