giulio98 commited on
Commit
8197344
0 Parent(s):

Initial commit without diffusion_pytorch_model.safetensors

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
conditional_pipeline.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union, List, Tuple
2
+
3
+ import torch
4
+ from diffusers.utils.torch_utils import randn_tensor
5
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
6
+
7
+ class ScoreSdeVePipelineConditioned(DiffusionPipeline):
8
+ r"""
9
+ Pipeline for unconditional image generation.
10
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
11
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
12
+ Parameters:
13
+ unet ([`UNet2DModel`]):
14
+ A `UNet2DModel` to denoise the encoded image.
15
+ scheduler ([`ScoreSdeVeScheduler`]):
16
+ A `ScoreSdeVeScheduler` to be used in combination with `unet` to denoise the encoded image.
17
+ """
18
+
19
+ def __init__(self, unet, scheduler):
20
+ super().__init__()
21
+ self.register_modules(unet=unet, scheduler=scheduler)
22
+
23
+ @torch.no_grad()
24
+ def __call__(
25
+ self,
26
+ batch_size: int = 1,
27
+ num_inference_steps: int = 2000,
28
+ class_labels: Optional[torch.Tensor] = None,
29
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
30
+ output_type: Optional[str] = "pil",
31
+ return_dict: bool = True,
32
+ **kwargs,
33
+ ) -> Union[ImagePipelineOutput, Tuple]:
34
+ r"""
35
+ The call function to the pipeline for generation.
36
+ Args:
37
+ batch_size (`int`, *optional*, defaults to 1):
38
+ The number of images to generate.
39
+ generator (`torch.Generator`, `optional`):
40
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
41
+ generation deterministic.
42
+ output_type (`str`, `optional`, defaults to `"pil"`):
43
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
44
+ return_dict (`bool`, *optional*, defaults to `True`):
45
+ Whether or not to return a [`ImagePipelineOutput`] instead of a plain tuple.
46
+ Returns:
47
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
48
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
49
+ returned where the first element is a list with the generated images.
50
+ """
51
+ img_size = self.unet.config.sample_size
52
+ shape = (batch_size, 3, img_size, img_size)
53
+
54
+ model = self.unet
55
+
56
+ sample = randn_tensor(shape, generator=generator, device=self.device) * self.scheduler.init_noise_sigma
57
+ sample = sample.to(self.device)
58
+
59
+ self.scheduler.set_timesteps(num_inference_steps)
60
+ self.scheduler.set_sigmas(num_inference_steps)
61
+
62
+ for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
63
+ sigma_t = self.scheduler.sigmas[i] * torch.ones(shape[0], device=self.device)
64
+
65
+ # correction step
66
+ for _ in range(self.scheduler.config.correct_steps):
67
+ model_output = self.unet(sample, sigma_t, class_labels).sample
68
+ sample = self.scheduler.step_correct(model_output, sample, generator=generator).prev_sample
69
+
70
+ # prediction step
71
+ model_output = model(sample, sigma_t, class_labels).sample
72
+ output = self.scheduler.step_pred(model_output, t, sample, generator=generator)
73
+
74
+ sample, sample_mean = output.prev_sample, output.prev_sample_mean
75
+
76
+ sample = sample_mean.clamp(0, 1)
77
+ sample = sample.cpu().permute(0, 2, 3, 1).numpy()
78
+ if output_type == "pil":
79
+ sample = self.numpy_to_pil(sample)
80
+
81
+ if not return_dict:
82
+ return (sample,)
83
+ return ImagePipelineOutput(images=sample)
model_index.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "conditional_pipeline",
4
+ "ScoreSdeVePipelineConditioned"
5
+ ],
6
+ "scheduler": [
7
+ "sde_ve_scheduler",
8
+ "ScoreSdeVeScheduler"
9
+ ],
10
+ "unet": [
11
+ "conditional_unet_model",
12
+ "UNet2DModel"
13
+ ]
14
+ }
scheduler/scheduler_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ScoreSdeVeScheduler",
3
+ "_diffusers_version": "0.27.2",
4
+ "correct_steps": 1,
5
+ "num_train_timesteps": 1000,
6
+ "sampling_eps": 1e-05,
7
+ "sigma_max": 90.0,
8
+ "sigma_min": 0.01,
9
+ "snr": 0.075
10
+ }
scheduler/sde_ve_scheduler.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Optional, Tuple, Union
4
+
5
+ import torch
6
+
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.utils import BaseOutput
9
+ from diffusers.utils.torch_utils import randn_tensor
10
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin, SchedulerOutput
11
+
12
+
13
+ @dataclass
14
+ class SdeVeOutput(BaseOutput):
15
+ """
16
+ Output class for the scheduler's `step` function output.
17
+ Args:
18
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
19
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
20
+ denoising loop.
21
+ prev_sample_mean (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
22
+ Mean averaged `prev_sample` over previous timesteps.
23
+ """
24
+
25
+ prev_sample: torch.FloatTensor
26
+ prev_sample_mean: torch.FloatTensor
27
+
28
+
29
+ class ScoreSdeVeScheduler(SchedulerMixin, ConfigMixin):
30
+ """
31
+ `ScoreSdeVeScheduler` is a variance exploding stochastic differential equation (SDE) scheduler.
32
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
33
+ methods the library implements for all schedulers such as loading and saving.
34
+ Args:
35
+ num_train_timesteps (`int`, defaults to 1000):
36
+ The number of diffusion steps to train the model.
37
+ snr (`float`, defaults to 0.15):
38
+ A coefficient weighting the step from the `model_output` sample (from the network) to the random noise.
39
+ sigma_min (`float`, defaults to 0.01):
40
+ The initial noise scale for the sigma sequence in the sampling procedure. The minimum sigma should mirror
41
+ the distribution of the data.
42
+ sigma_max (`float`, defaults to 1348.0):
43
+ The maximum value used for the range of continuous timesteps passed into the model.
44
+ sampling_eps (`float`, defaults to 1e-5):
45
+ The end value of sampling where timesteps decrease progressively from 1 to epsilon.
46
+ correct_steps (`int`, defaults to 1):
47
+ The number of correction steps performed on a produced sample.
48
+ """
49
+
50
+ order = 1
51
+
52
+ @register_to_config
53
+ def __init__(
54
+ self,
55
+ num_train_timesteps: int = 2000,
56
+ snr: float = 0.15,
57
+ sigma_min: float = 0.01,
58
+ sigma_max: float = 1348.0,
59
+ sampling_eps: float = 1e-5,
60
+ correct_steps: int = 1,
61
+ ):
62
+ # standard deviation of the initial noise distribution
63
+ self.init_noise_sigma = sigma_max
64
+
65
+ # setable values
66
+ self.timesteps = None
67
+
68
+ self.set_sigmas(num_train_timesteps, sigma_min, sigma_max, sampling_eps)
69
+
70
+ def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
71
+ """
72
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
73
+ current timestep.
74
+ Args:
75
+ sample (`torch.FloatTensor`):
76
+ The input sample.
77
+ timestep (`int`, *optional*):
78
+ The current timestep in the diffusion chain.
79
+ Returns:
80
+ `torch.FloatTensor`:
81
+ A scaled input sample.
82
+ """
83
+ return sample
84
+
85
+ def set_timesteps(
86
+ self, num_inference_steps: int, sampling_eps: float = None, device: Union[str, torch.device] = None
87
+ ):
88
+ """
89
+ Sets the continuous timesteps used for the diffusion chain (to be run before inference).
90
+ Args:
91
+ num_inference_steps (`int`):
92
+ The number of diffusion steps used when generating samples with a pre-trained model.
93
+ sampling_eps (`float`, *optional*):
94
+ The final timestep value (overrides value given during scheduler instantiation).
95
+ device (`str` or `torch.device`, *optional*):
96
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
97
+ """
98
+ sampling_eps = sampling_eps if sampling_eps is not None else self.config.sampling_eps
99
+
100
+ self.timesteps = torch.linspace(1, sampling_eps, num_inference_steps, device=device)
101
+
102
+ def set_sigmas(
103
+ self, num_inference_steps: int, sigma_min: float = None, sigma_max: float = None, sampling_eps: float = None
104
+ ):
105
+ """
106
+ Sets the noise scales used for the diffusion chain (to be run before inference). The sigmas control the weight
107
+ of the `drift` and `diffusion` components of the sample update.
108
+ Args:
109
+ num_inference_steps (`int`):
110
+ The number of diffusion steps used when generating samples with a pre-trained model.
111
+ sigma_min (`float`, optional):
112
+ The initial noise scale value (overrides value given during scheduler instantiation).
113
+ sigma_max (`float`, optional):
114
+ The final noise scale value (overrides value given during scheduler instantiation).
115
+ sampling_eps (`float`, optional):
116
+ The final timestep value (overrides value given during scheduler instantiation).
117
+ """
118
+ sigma_min = sigma_min if sigma_min is not None else self.config.sigma_min
119
+ sigma_max = sigma_max if sigma_max is not None else self.config.sigma_max
120
+ sampling_eps = sampling_eps if sampling_eps is not None else self.config.sampling_eps
121
+ if self.timesteps is None:
122
+ self.set_timesteps(num_inference_steps, sampling_eps)
123
+
124
+ self.sigmas = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps)
125
+ self.discrete_sigmas = torch.exp(torch.linspace(math.log(sigma_min), math.log(sigma_max), num_inference_steps))
126
+ self.sigmas = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps])
127
+
128
+ def get_adjacent_sigma(self, timesteps, t):
129
+ return torch.where(
130
+ timesteps == 0,
131
+ torch.zeros_like(t.to(timesteps.device)),
132
+ self.discrete_sigmas[timesteps - 1].to(timesteps.device),
133
+ )
134
+
135
+ def step_pred(
136
+ self,
137
+ model_output: torch.FloatTensor,
138
+ timestep: int,
139
+ sample: torch.FloatTensor,
140
+ generator: Optional[torch.Generator] = None,
141
+ return_dict: bool = True,
142
+ ) -> Union[SdeVeOutput, Tuple]:
143
+ """
144
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
145
+ process from the learned model outputs (most often the predicted noise).
146
+ Args:
147
+ model_output (`torch.FloatTensor`):
148
+ The direct output from learned diffusion model.
149
+ timestep (`int`):
150
+ The current discrete timestep in the diffusion chain.
151
+ sample (`torch.FloatTensor`):
152
+ A current instance of a sample created by the diffusion process.
153
+ generator (`torch.Generator`, *optional*):
154
+ A random number generator.
155
+ return_dict (`bool`, *optional*, defaults to `True`):
156
+ Whether or not to return a [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`.
157
+ Returns:
158
+ [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`:
159
+ If return_dict is `True`, [`~schedulers.scheduling_sde_ve.SdeVeOutput`] is returned, otherwise a tuple
160
+ is returned where the first element is the sample tensor.
161
+ """
162
+ if self.timesteps is None:
163
+ raise ValueError(
164
+ "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"
165
+ )
166
+
167
+ timestep = timestep * torch.ones(
168
+ sample.shape[0], device=sample.device
169
+ ) # torch.repeat_interleave(timestep, sample.shape[0])
170
+ timesteps = (timestep * (len(self.timesteps) - 1)).long()
171
+
172
+ # mps requires indices to be in the same device, so we use cpu as is the default with cuda
173
+ timesteps = timesteps.to(self.discrete_sigmas.device)
174
+
175
+ sigma = self.discrete_sigmas[timesteps].to(sample.device)
176
+ adjacent_sigma = self.get_adjacent_sigma(timesteps, timestep).to(sample.device)
177
+ drift = torch.zeros_like(sample)
178
+ diffusion = (sigma**2 - adjacent_sigma**2) ** 0.5
179
+
180
+ # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
181
+ # also equation 47 shows the analog from SDE models to ancestral sampling methods
182
+ diffusion = diffusion.flatten()
183
+ while len(diffusion.shape) < len(sample.shape):
184
+ diffusion = diffusion.unsqueeze(-1)
185
+ drift = drift - diffusion**2 * model_output
186
+
187
+ # equation 6: sample noise for the diffusion term of
188
+ noise = randn_tensor(
189
+ sample.shape, layout=sample.layout, generator=generator, device=sample.device, dtype=sample.dtype
190
+ )
191
+ prev_sample_mean = sample - drift # subtract because `dt` is a small negative timestep
192
+ # TODO is the variable diffusion the correct scaling term for the noise?
193
+ prev_sample = prev_sample_mean + diffusion * noise # add impact of diffusion field g
194
+
195
+ if not return_dict:
196
+ return (prev_sample, prev_sample_mean)
197
+
198
+ return SdeVeOutput(prev_sample=prev_sample, prev_sample_mean=prev_sample_mean)
199
+
200
+ def step_correct(
201
+ self,
202
+ model_output: torch.FloatTensor,
203
+ sample: torch.FloatTensor,
204
+ generator: Optional[torch.Generator] = None,
205
+ return_dict: bool = True,
206
+ ) -> Union[SchedulerOutput, Tuple]:
207
+ """
208
+ Correct the predicted sample based on the `model_output` of the network. This is often run repeatedly after
209
+ making the prediction for the previous timestep.
210
+ Args:
211
+ model_output (`torch.FloatTensor`):
212
+ The direct output from learned diffusion model.
213
+ sample (`torch.FloatTensor`):
214
+ A current instance of a sample created by the diffusion process.
215
+ generator (`torch.Generator`, *optional*):
216
+ A random number generator.
217
+ return_dict (`bool`, *optional*, defaults to `True`):
218
+ Whether or not to return a [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`.
219
+ Returns:
220
+ [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`:
221
+ If return_dict is `True`, [`~schedulers.scheduling_sde_ve.SdeVeOutput`] is returned, otherwise a tuple
222
+ is returned where the first element is the sample tensor.
223
+ """
224
+ if self.timesteps is None:
225
+ raise ValueError(
226
+ "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"
227
+ )
228
+
229
+ # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z"
230
+ # sample noise for correction
231
+ noise = randn_tensor(sample.shape, layout=sample.layout, generator=generator, device=sample.device).to(sample.device)
232
+
233
+ # compute step size from the model_output, the noise, and the snr
234
+ grad_norm = torch.norm(model_output.reshape(model_output.shape[0], -1), dim=-1).mean()
235
+ noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
236
+ step_size = (self.config.snr * noise_norm / grad_norm) ** 2 * 2
237
+ step_size = step_size * torch.ones(sample.shape[0]).to(sample.device)
238
+ # self.repeat_scalar(step_size, sample.shape[0])
239
+
240
+ # compute corrected sample: model_output term and noise term
241
+ step_size = step_size.flatten()
242
+ while len(step_size.shape) < len(sample.shape):
243
+ step_size = step_size.unsqueeze(-1)
244
+ prev_sample_mean = sample + step_size * model_output
245
+ prev_sample = prev_sample_mean + ((step_size * 2) ** 0.5) * noise
246
+
247
+ if not return_dict:
248
+ return (prev_sample,)
249
+
250
+ return SchedulerOutput(prev_sample=prev_sample)
251
+
252
+ def add_noise(
253
+ self,
254
+ original_samples: torch.FloatTensor,
255
+ noise: torch.FloatTensor,
256
+ timesteps: torch.FloatTensor,
257
+ ) -> torch.FloatTensor:
258
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
259
+ timesteps = timesteps.to(original_samples.device)
260
+ sigmas = self.config.sigma_min * (self.config.sigma_max / self.config.sigma_min) ** timesteps
261
+ noise = (
262
+ noise * sigmas[:, None, None, None]
263
+ if noise is not None
264
+ else torch.randn_like(original_samples) * sigmas[:, None, None, None]
265
+ )
266
+ noisy_samples = noise + original_samples
267
+ return noisy_samples
268
+
269
+ def __len__(self):
270
+ return self.config.num_train_timesteps
unet/conditional_unet_model.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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 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
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
33
+ for all models (such as downloading or saving).
34
+ Parameters:
35
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
36
+ Height and width of input/output sample. Dimensions must be a multiple of `2 ** (len(block_out_channels) -
37
+ 1)`.
38
+ in_channels (`int`, *optional*, defaults to 3): Number of channels in the input sample.
39
+ out_channels (`int`, *optional*, defaults to 3): Number of channels in the output.
40
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
41
+ time_embedding_type (`str`, *optional*, defaults to `"positional"`): Type of time embedding to use.
42
+ freq_shift (`int`, *optional*, defaults to 0): Frequency shift for Fourier time embedding.
43
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
44
+ Whether to flip sin to cos for Fourier time embedding.
45
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")`):
46
+ Tuple of downsample block types.
47
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2D"`):
48
+ Block type for middle of UNet, it can be either `UNetMidBlock2D` or `UnCLIPUNetMidBlock2D`.
49
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")`):
50
+ Tuple of upsample block types.
51
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(224, 448, 672, 896)`):
52
+ Tuple of block output channels.
53
+ layers_per_block (`int`, *optional*, defaults to `2`): The number of layers per block.
54
+ mid_block_scale_factor (`float`, *optional*, defaults to `1`): The scale factor for the mid block.
55
+ downsample_padding (`int`, *optional*, defaults to `1`): The padding for the downsample convolution.
56
+ downsample_type (`str`, *optional*, defaults to `conv`):
57
+ The downsample type for downsampling layers. Choose between "conv" and "resnet"
58
+ upsample_type (`str`, *optional*, defaults to `conv`):
59
+ The upsample type for upsampling layers. Choose between "conv" and "resnet"
60
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
61
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
62
+ attention_head_dim (`int`, *optional*, defaults to `8`): The attention head dimension.
63
+ norm_num_groups (`int`, *optional*, defaults to `32`): The number of groups for normalization.
64
+ attn_norm_num_groups (`int`, *optional*, defaults to `None`):
65
+ If set to an integer, a group norm layer will be created in the mid block's [`Attention`] layer with the
66
+ given number of groups. If left as `None`, the group norm layer will only be created if
67
+ `resnet_time_scale_shift` is set to `default`, and if created will have `norm_num_groups` groups.
68
+ norm_eps (`float`, *optional*, defaults to `1e-5`): The epsilon for normalization.
69
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
70
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
71
+ class_embed_type (`str`, *optional*, defaults to `None`):
72
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
73
+ `"timestep"`, or `"identity"`.
74
+ num_class_embeds (`int`, *optional*, defaults to `None`):
75
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim` when performing class
76
+ conditioning with `class_embed_type` equal to `None`.
77
+ """
78
+
79
+ @register_to_config
80
+ def __init__(
81
+ self,
82
+ sample_size: Optional[Union[int, Tuple[int, int]]] = None,
83
+ in_channels: int = 3,
84
+ out_channels: int = 3,
85
+ center_input_sample: bool = False,
86
+ time_embedding_type: str = "positional",
87
+ freq_shift: int = 0,
88
+ flip_sin_to_cos: bool = True,
89
+ down_block_types: Tuple[str, ...] = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
90
+ up_block_types: Tuple[str, ...] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
91
+ block_out_channels: Tuple[int, ...] = (224, 448, 672, 896),
92
+ layers_per_block: int = 2,
93
+ mid_block_scale_factor: float = 1,
94
+ downsample_padding: int = 1,
95
+ downsample_type: str = "conv",
96
+ upsample_type: str = "conv",
97
+ dropout: float = 0.0,
98
+ act_fn: str = "silu",
99
+ attention_head_dim: Optional[int] = 8,
100
+ norm_num_groups: int = 32,
101
+ attn_norm_num_groups: Optional[int] = None,
102
+ norm_eps: float = 1e-5,
103
+ resnet_time_scale_shift: str = "default",
104
+ add_attention: bool = True,
105
+ class_embed_type: Optional[str] = None,
106
+ num_class_embeds: Optional[int] = None,
107
+ num_train_timesteps: Optional[int] = None,
108
+ set_W_to_weight: Optional[bool] = True,
109
+ ):
110
+ super().__init__()
111
+
112
+ self.sample_size = sample_size
113
+ time_embed_dim = block_out_channels[0] * 4
114
+
115
+ # Check inputs
116
+ if len(down_block_types) != len(up_block_types):
117
+ raise ValueError(
118
+ 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}."
119
+ )
120
+
121
+ if len(block_out_channels) != len(down_block_types):
122
+ raise ValueError(
123
+ 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}."
124
+ )
125
+
126
+ # input
127
+ self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
128
+
129
+ # time
130
+ if time_embedding_type == "fourier":
131
+ self.time_proj = GaussianFourierProjection(embedding_size=block_out_channels[0], scale=16, set_W_to_weight=set_W_to_weight)
132
+ timestep_input_dim = 2 * block_out_channels[0]
133
+ elif time_embedding_type == "positional":
134
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
135
+ timestep_input_dim = block_out_channels[0]
136
+ elif time_embedding_type == "learned":
137
+ self.time_proj = nn.Embedding(num_train_timesteps, block_out_channels[0])
138
+ timestep_input_dim = block_out_channels[0]
139
+
140
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
141
+
142
+ # class embedding
143
+ if class_embed_type is None and num_class_embeds is not None:
144
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
145
+ elif class_embed_type == "timestep":
146
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
147
+ elif class_embed_type == "identity":
148
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
149
+ else:
150
+ self.class_embedding = None
151
+
152
+ self.down_blocks = nn.ModuleList([])
153
+ self.mid_block = None
154
+ self.up_blocks = nn.ModuleList([])
155
+
156
+ # down
157
+ output_channel = block_out_channels[0]
158
+ for i, down_block_type in enumerate(down_block_types):
159
+ input_channel = output_channel
160
+ output_channel = block_out_channels[i]
161
+ is_final_block = i == len(block_out_channels) - 1
162
+
163
+ down_block = get_down_block(
164
+ down_block_type,
165
+ num_layers=layers_per_block,
166
+ in_channels=input_channel,
167
+ out_channels=output_channel,
168
+ temb_channels=time_embed_dim,
169
+ add_downsample=not is_final_block,
170
+ resnet_eps=norm_eps,
171
+ resnet_act_fn=act_fn,
172
+ resnet_groups=norm_num_groups,
173
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
174
+ downsample_padding=downsample_padding,
175
+ resnet_time_scale_shift=resnet_time_scale_shift,
176
+ downsample_type=downsample_type,
177
+ dropout=dropout,
178
+ )
179
+ self.down_blocks.append(down_block)
180
+
181
+ # mid
182
+ self.mid_block = UNetMidBlock2D(
183
+ in_channels=block_out_channels[-1],
184
+ temb_channels=time_embed_dim,
185
+ dropout=dropout,
186
+ resnet_eps=norm_eps,
187
+ resnet_act_fn=act_fn,
188
+ output_scale_factor=mid_block_scale_factor,
189
+ resnet_time_scale_shift=resnet_time_scale_shift,
190
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1],
191
+ resnet_groups=norm_num_groups,
192
+ attn_groups=attn_norm_num_groups,
193
+ add_attention=add_attention,
194
+ )
195
+
196
+ # up
197
+ reversed_block_out_channels = list(reversed(block_out_channels))
198
+ output_channel = reversed_block_out_channels[0]
199
+ for i, up_block_type in enumerate(up_block_types):
200
+ prev_output_channel = output_channel
201
+ output_channel = reversed_block_out_channels[i]
202
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
203
+
204
+ is_final_block = i == len(block_out_channels) - 1
205
+
206
+ up_block = get_up_block(
207
+ up_block_type,
208
+ num_layers=layers_per_block + 1,
209
+ in_channels=input_channel,
210
+ out_channels=output_channel,
211
+ prev_output_channel=prev_output_channel,
212
+ temb_channels=time_embed_dim,
213
+ add_upsample=not is_final_block,
214
+ resnet_eps=norm_eps,
215
+ resnet_act_fn=act_fn,
216
+ resnet_groups=norm_num_groups,
217
+ attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
218
+ resnet_time_scale_shift=resnet_time_scale_shift,
219
+ upsample_type=upsample_type,
220
+ dropout=dropout,
221
+ )
222
+ self.up_blocks.append(up_block)
223
+ prev_output_channel = output_channel
224
+
225
+ # out
226
+ num_groups_out = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4, 32)
227
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=num_groups_out, eps=norm_eps)
228
+ self.conv_act = nn.SiLU()
229
+ self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
230
+
231
+ def forward(
232
+ self,
233
+ sample: torch.FloatTensor,
234
+ timestep: Union[torch.Tensor, float, int],
235
+ class_labels: Optional[torch.Tensor] = None,
236
+ return_dict: bool = True,
237
+ ) -> Union[UNet2DOutput, Tuple]:
238
+ r"""
239
+ The [`UNet2DModel`] forward method.
240
+ Args:
241
+ sample (`torch.FloatTensor`):
242
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
243
+ timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
244
+ class_labels (`torch.FloatTensor`, *optional*, defaults to `None`):
245
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
246
+ return_dict (`bool`, *optional*, defaults to `True`):
247
+ Whether or not to return a [`~models.unet_2d.UNet2DOutput`] instead of a plain tuple.
248
+ Returns:
249
+ [`~models.unet_2d.UNet2DOutput`] or `tuple`:
250
+ If `return_dict` is True, an [`~models.unet_2d.UNet2DOutput`] is returned, otherwise a `tuple` is
251
+ returned where the first element is the sample tensor.
252
+ """
253
+ # 0. center input if necessary
254
+ if self.config.center_input_sample:
255
+ sample = 2 * sample - 1.0
256
+
257
+ # 1. time
258
+ timesteps = timestep
259
+ if not torch.is_tensor(timesteps):
260
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
261
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
262
+ timesteps = timesteps[None].to(sample.device)
263
+
264
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
265
+ timesteps = timesteps * torch.ones(sample.shape[0], dtype=timesteps.dtype, device=timesteps.device)
266
+
267
+ t_emb = self.time_proj(timesteps)
268
+
269
+ # timesteps does not contain any weights and will always return f32 tensors
270
+ # but time_embedding might actually be running in fp16. so we need to cast here.
271
+ # there might be better ways to encapsulate this.
272
+ t_emb = t_emb.to(dtype=self.dtype)
273
+ emb = self.time_embedding(t_emb)
274
+
275
+ if self.class_embedding is not None:
276
+ if class_labels is None:
277
+ raise ValueError("class_labels should be provided when doing class conditioning")
278
+
279
+ if self.config.class_embed_type == "timestep":
280
+ class_labels = self.time_proj(class_labels)
281
+
282
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
283
+ emb = emb + class_emb
284
+ elif self.class_embedding is None and class_labels is not None:
285
+ raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
286
+
287
+ # 2. pre-process
288
+ skip_sample = sample
289
+ sample = self.conv_in(sample)
290
+
291
+ # 3. down
292
+ down_block_res_samples = (sample,)
293
+ for downsample_block in self.down_blocks:
294
+ if hasattr(downsample_block, "skip_conv"):
295
+ sample, res_samples, skip_sample = downsample_block(
296
+ hidden_states=sample, temb=emb, skip_sample=skip_sample
297
+ )
298
+ else:
299
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
300
+
301
+ down_block_res_samples += res_samples
302
+
303
+ # 4. mid
304
+ sample = self.mid_block(sample, emb)
305
+
306
+ # 5. up
307
+ skip_sample = None
308
+ for upsample_block in self.up_blocks:
309
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
310
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
311
+
312
+ if hasattr(upsample_block, "skip_conv"):
313
+ sample, skip_sample = upsample_block(sample, res_samples, emb, skip_sample)
314
+ else:
315
+ sample = upsample_block(sample, res_samples, emb)
316
+
317
+ # 6. post-process
318
+ sample = self.conv_norm_out(sample)
319
+ sample = self.conv_act(sample)
320
+ sample = self.conv_out(sample)
321
+
322
+ if skip_sample is not None:
323
+ sample += skip_sample
324
+
325
+ if self.config.time_embedding_type == "fourier":
326
+ timesteps = timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]))))
327
+ sample = sample / timesteps
328
+
329
+ if not return_dict:
330
+ return (sample,)
331
+
332
+ return UNet2DOutput(sample=sample)
unet/config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UNet2DModel",
3
+ "_diffusers_version": "0.27.2",
4
+ "act_fn": "silu",
5
+ "add_attention": true,
6
+ "attention_head_dim": null,
7
+ "attn_norm_num_groups": null,
8
+ "block_out_channels": [
9
+ 128,
10
+ 128,
11
+ 256,
12
+ 256,
13
+ 256,
14
+ 256,
15
+ 256
16
+ ],
17
+ "center_input_sample": true,
18
+ "class_embed_type": null,
19
+ "decay": 0.9999,
20
+ "down_block_types": [
21
+ "SkipDownBlock2D",
22
+ "SkipDownBlock2D",
23
+ "SkipDownBlock2D",
24
+ "SkipDownBlock2D",
25
+ "AttnSkipDownBlock2D",
26
+ "SkipDownBlock2D",
27
+ "SkipDownBlock2D"
28
+ ],
29
+ "downsample_padding": 1,
30
+ "downsample_type": "conv",
31
+ "dropout": 0.0,
32
+ "flip_sin_to_cos": true,
33
+ "freq_shift": 0,
34
+ "in_channels": 3,
35
+ "inv_gamma": 1.0,
36
+ "layers_per_block": 2,
37
+ "mid_block_scale_factor": 1.41421356237,
38
+ "min_decay": 0.0,
39
+ "norm_eps": 1e-06,
40
+ "norm_num_groups": null,
41
+ "num_class_embeds": 3,
42
+ "num_train_timesteps": null,
43
+ "optimization_step": 325540,
44
+ "out_channels": 3,
45
+ "power": 0.75,
46
+ "resnet_time_scale_shift": "default",
47
+ "sample_size": 64,
48
+ "set_W_to_weight": false,
49
+ "time_embedding_type": "fourier",
50
+ "up_block_types": [
51
+ "SkipUpBlock2D",
52
+ "SkipUpBlock2D",
53
+ "AttnSkipUpBlock2D",
54
+ "SkipUpBlock2D",
55
+ "SkipUpBlock2D",
56
+ "SkipUpBlock2D",
57
+ "SkipUpBlock2D"
58
+ ],
59
+ "update_after_step": 0,
60
+ "upsample_type": "conv",
61
+ "use_ema_warmup": true
62
+ }