giulio98 commited on
Commit
4856394
1 Parent(s): 743e331

Create conditional_pipeline.py

Browse files
Files changed (1) hide show
  1. conditional_pipeline.py +83 -0
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)