giulio98 commited on
Commit
ac35ae9
1 Parent(s): 2914862

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +211 -0
pipeline.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union, List, Tuple, Callable
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 KarrasEDMConditionalPipeline(DiffusionPipeline):
8
+ r"""
9
+ Pipeline for unconditional or class-conditional image generation based on the EDM model from [1].
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
+ [1] Karras, Tero, et al. "Elucidating the Design Space of Diffusion-Based Generative Models."
13
+ https://arxiv.org/abs/2206.00364
14
+ Args:
15
+ unet ([`UNet2DModel`]):
16
+ A `UNet2DModel` to denoise the encoded image latents.
17
+ scheduler ([`SchedulerMixin`]):
18
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Currently only
19
+ supports KarrasEDMScheduler.
20
+ """
21
+
22
+ model_cpu_offload_seq = "unet"
23
+
24
+ def __init__(self, unet, scheduler) -> None:
25
+ super().__init__()
26
+
27
+ self.register_modules(
28
+ unet=unet,
29
+ scheduler=scheduler,
30
+ )
31
+
32
+ self.safety_checker = None
33
+
34
+ def prepare_latents(self, batch_size, num_channels, height, width, dtype, device, generator, latents=None):
35
+ shape = (batch_size, num_channels, height, width)
36
+ if isinstance(generator, list) and len(generator) != batch_size:
37
+ raise ValueError(
38
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
39
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
40
+ )
41
+
42
+ if latents is None:
43
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
44
+ else:
45
+ latents = latents.to(device=device, dtype=dtype)
46
+
47
+ # scale the initial noise by the standard deviation required by the scheduler
48
+ latents = latents * self.scheduler.init_noise_sigma
49
+ return latents
50
+
51
+ # Follows diffusers.VaeImageProcessor.postprocess
52
+ def postprocess_image(self, sample: torch.FloatTensor, output_type: str = "pil"):
53
+ if output_type not in ["pt", "np", "pil"]:
54
+ raise ValueError(
55
+ f"output_type={output_type} is not supported. Make sure to choose one of ['pt', 'np', or 'pil']"
56
+ )
57
+
58
+ # Equivalent to diffusers.VaeImageProcessor.denormalize
59
+ sample = (sample / 2 + 0.5).clamp(0, 1)
60
+ if output_type == "pt":
61
+ return sample
62
+
63
+ # Equivalent to diffusers.VaeImageProcessor.pt_to_numpy
64
+ sample = sample.cpu().permute(0, 2, 3, 1).numpy()
65
+ if output_type == "np":
66
+ return sample
67
+
68
+ # Output_type must be 'pil'
69
+ sample = self.numpy_to_pil(sample)
70
+ return sample
71
+
72
+ def check_inputs(self, num_inference_steps, timesteps, latents, batch_size, img_size, callback_steps):
73
+ if num_inference_steps is None and timesteps is None:
74
+ raise ValueError("Exactly one of `num_inference_steps` or `timesteps` must be supplied.")
75
+
76
+ if num_inference_steps is not None and timesteps is not None:
77
+ logger.warning(
78
+ f"Both `num_inference_steps`: {num_inference_steps} and `timesteps`: {timesteps} are supplied;"
79
+ " `timesteps` will be used over `num_inference_steps`."
80
+ )
81
+
82
+ if latents is not None:
83
+ expected_shape = (batch_size, 3, img_size, img_size)
84
+ if latents.shape != expected_shape:
85
+ raise ValueError(f"The shape of latents is {latents.shape} but is expected to be {expected_shape}.")
86
+
87
+ if (callback_steps is None) or (
88
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
89
+ ):
90
+ raise ValueError(
91
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
92
+ f" {type(callback_steps)}."
93
+ )
94
+
95
+ @torch.no_grad()
96
+ def __call__(
97
+ self,
98
+ batch_size: int = 1,
99
+ num_inference_steps: int = 1,
100
+ timesteps: List[int] = None,
101
+ class_labels: Optional[torch.Tensor] = None,
102
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
103
+ latents: Optional[torch.FloatTensor] = None,
104
+ output_type: Optional[str] = "pil",
105
+ return_dict: bool = True,
106
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
107
+ callback_steps: int = 1,
108
+ ):
109
+ r"""
110
+ Args:
111
+ batch_size (`int`, *optional*, defaults to 1):
112
+ The number of images to generate.
113
+ class_labels (`torch.Tensor` or `List[int]` or `int`, *optional*):
114
+ Optional class labels for conditioning class-conditional consistency models. Not used if the model is
115
+ not class-conditional.
116
+ num_inference_steps (`int`, *optional*, defaults to 1):
117
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
118
+ expense of slower inference.
119
+ timesteps (`List[int]`, *optional*):
120
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
121
+ timesteps are used. Must be in descending order.
122
+ generator (`torch.Generator`, *optional*):
123
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
124
+ generation deterministic.
125
+ latents (`torch.FloatTensor`, *optional*):
126
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
127
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
128
+ tensor is generated by sampling using the supplied random `generator`.
129
+ output_type (`str`, *optional*, defaults to `"pil"`):
130
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
131
+ return_dict (`bool`, *optional*, defaults to `True`):
132
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
133
+ callback (`Callable`, *optional*):
134
+ A function that calls every `callback_steps` steps during inference. The function is called with the
135
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
136
+ callback_steps (`int`, *optional*, defaults to 1):
137
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
138
+ every step.
139
+ Examples:
140
+ Returns:
141
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
142
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
143
+ returned where the first element is a list with the generated images.
144
+ """
145
+ # 0. Prepare call parameters
146
+ img_size = self.unet.config.sample_size
147
+ device = self._execution_device
148
+
149
+
150
+
151
+ # 2. Prepare image latents
152
+ # Sample image latents x_0 ~ N(0, sigma_0^2 * I)
153
+ sample = self.prepare_latents(
154
+ batch_size=batch_size,
155
+ num_channels=self.unet.config.in_channels,
156
+ height=img_size,
157
+ width=img_size,
158
+ dtype=self.unet.dtype,
159
+ device=device,
160
+ generator=generator,
161
+ latents=latents,
162
+ )
163
+
164
+ # 4. Prepare timesteps
165
+ if timesteps is not None:
166
+ self.scheduler.set_timesteps(timesteps=timesteps, device=device)
167
+ timesteps = self.scheduler.timesteps
168
+ num_inference_steps = len(timesteps)
169
+ else:
170
+ self.scheduler.set_timesteps(num_inference_steps)
171
+ timesteps = self.scheduler.timesteps
172
+
173
+ # 5. Denoising loop
174
+ # Implements the "EDM" column in Table 1 of the EDM paper
175
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
176
+
177
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
178
+ for i, t in enumerate(timesteps):
179
+ # 1. Add noise (if necessary) and precondition the input sample.
180
+ scaled_sample = self.scheduler.scale_model_input(sample, t)
181
+
182
+ if self.scheduler.step_index is None:
183
+ self.scheduler._init_step_index(t)
184
+
185
+ sigma = self.scheduler.sigmas[self.scheduler.step_index]
186
+
187
+ sigma_input = self.scheduler.precondition_noise(sigma)
188
+
189
+ # 2. Evaluate neural network at higher noise level (sample_hat, sigma_hat).
190
+ model_output = self.unet(scaled_sample, sigma_input.squeeze(), class_labels, return_dict=False)[0]
191
+
192
+ # 3. Apply output preconditioning on model_output to get denoiser output
193
+ # 4. Take either a first order (Euler) step or second order (Heun) step
194
+ sample = self.scheduler.step(model_output, t, sample).prev_sample
195
+
196
+ # call the callback, if provided
197
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
198
+ progress_bar.update()
199
+ if callback is not None and i % callback_steps == 0:
200
+ callback(i, t, latents)
201
+
202
+ # 6. Post-process image sample
203
+ image = self.postprocess_image(sample, output_type=output_type)
204
+
205
+ # Offload all models
206
+ self.maybe_free_model_hooks()
207
+
208
+ if not return_dict:
209
+ return (image,)
210
+
211
+ return ImagePipelineOutput(images=image)