giulio98 commited on
Commit
65fe534
·
verified ·
1 Parent(s): 87bab8b

Delete unet2d_model.py

Browse files
Files changed (1) hide show
  1. unet2d_model.py +0 -336
unet2d_model.py DELETED
@@ -1,336 +0,0 @@
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
-
17
- @dataclass
18
- class UNet2DOutput(BaseOutput):
19
- """
20
- The output of [`UNet2DModel`].
21
-
22
- Args:
23
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
24
- The hidden states output from the last layer of the model.
25
- """
26
-
27
- sample: torch.FloatTensor
28
-
29
-
30
- class UNet2DModel(ModelMixin, ConfigMixin):
31
- r"""
32
- A 2D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.
33
-
34
- This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
35
- for all models (such as downloading or saving).
36
-
37
- Parameters:
38
- sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
39
- Height and width of input/output sample. Dimensions must be a multiple of `2 ** (len(block_out_channels) -
40
- 1)`.
41
- in_channels (`int`, *optional*, defaults to 3): Number of channels in the input sample.
42
- out_channels (`int`, *optional*, defaults to 3): Number of channels in the output.
43
- center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
44
- time_embedding_type (`str`, *optional*, defaults to `"positional"`): Type of time embedding to use.
45
- freq_shift (`int`, *optional*, defaults to 0): Frequency shift for Fourier time embedding.
46
- flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
47
- Whether to flip sin to cos for Fourier time embedding.
48
- down_block_types (`Tuple[str]`, *optional*, defaults to `("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")`):
49
- Tuple of downsample block types.
50
- mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2D"`):
51
- Block type for middle of UNet, it can be either `UNetMidBlock2D` or `UnCLIPUNetMidBlock2D`.
52
- up_block_types (`Tuple[str]`, *optional*, defaults to `("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")`):
53
- Tuple of upsample block types.
54
- block_out_channels (`Tuple[int]`, *optional*, defaults to `(224, 448, 672, 896)`):
55
- Tuple of block output channels.
56
- layers_per_block (`int`, *optional*, defaults to `2`): The number of layers per block.
57
- mid_block_scale_factor (`float`, *optional*, defaults to `1`): The scale factor for the mid block.
58
- downsample_padding (`int`, *optional*, defaults to `1`): The padding for the downsample convolution.
59
- downsample_type (`str`, *optional*, defaults to `conv`):
60
- The downsample type for downsampling layers. Choose between "conv" and "resnet"
61
- upsample_type (`str`, *optional*, defaults to `conv`):
62
- The upsample type for upsampling layers. Choose between "conv" and "resnet"
63
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
64
- act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
65
- attention_head_dim (`int`, *optional*, defaults to `8`): The attention head dimension.
66
- norm_num_groups (`int`, *optional*, defaults to `32`): The number of groups for normalization.
67
- attn_norm_num_groups (`int`, *optional*, defaults to `None`):
68
- If set to an integer, a group norm layer will be created in the mid block's [`Attention`] layer with the
69
- given number of groups. If left as `None`, the group norm layer will only be created if
70
- `resnet_time_scale_shift` is set to `default`, and if created will have `norm_num_groups` groups.
71
- norm_eps (`float`, *optional*, defaults to `1e-5`): The epsilon for normalization.
72
- resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
73
- for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
74
- class_embed_type (`str`, *optional*, defaults to `None`):
75
- The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
76
- `"timestep"`, or `"identity"`.
77
- num_class_embeds (`int`, *optional*, defaults to `None`):
78
- Input dimension of the learnable embedding matrix to be projected to `time_embed_dim` when performing class
79
- conditioning with `class_embed_type` equal to `None`.
80
- """
81
-
82
- @register_to_config
83
- def __init__(
84
- self,
85
- sample_size: Optional[Union[int, Tuple[int, int]]] = None,
86
- in_channels: int = 3,
87
- out_channels: int = 3,
88
- center_input_sample: bool = False,
89
- time_embedding_type: str = "positional",
90
- freq_shift: int = 0,
91
- flip_sin_to_cos: bool = True,
92
- down_block_types: Tuple[str, ...] = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
93
- up_block_types: Tuple[str, ...] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
94
- block_out_channels: Tuple[int, ...] = (224, 448, 672, 896),
95
- layers_per_block: int = 2,
96
- mid_block_scale_factor: float = 1,
97
- downsample_padding: int = 1,
98
- downsample_type: str = "conv",
99
- upsample_type: str = "conv",
100
- dropout: float = 0.0,
101
- act_fn: str = "silu",
102
- attention_head_dim: Optional[int] = 8,
103
- norm_num_groups: int = 32,
104
- attn_norm_num_groups: Optional[int] = None,
105
- norm_eps: float = 1e-5,
106
- resnet_time_scale_shift: str = "default",
107
- add_attention: bool = True,
108
- class_embed_type: Optional[str] = None,
109
- num_class_embeds: Optional[int] = None,
110
- num_train_timesteps: Optional[int] = None,
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=False)
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)