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

Create conditional_pipeline.py

Browse files
Files changed (1) hide show
  1. conditional_pipeline.py +87 -0
conditional_pipeline.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ class ScoreSdeVePipelineConditioned(DiffusionPipeline):
9
+ r"""
10
+ Pipeline for unconditional image generation.
11
+
12
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
13
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
14
+
15
+ Parameters:
16
+ unet ([`UNet2DModel`]):
17
+ A `UNet2DModel` to denoise the encoded image.
18
+ scheduler ([`ScoreSdeVeScheduler`]):
19
+ A `ScoreSdeVeScheduler` to be used in combination with `unet` to denoise the encoded image.
20
+ """
21
+ def __init__(self, unet: UNet2DModel, scheduler: ScoreSdeVeScheduler):
22
+ super().__init__()
23
+ self.register_modules(unet=unet, scheduler=scheduler)
24
+
25
+ @torch.no_grad()
26
+ def __call__(
27
+ self,
28
+ batch_size: int = 1,
29
+ num_inference_steps: int = 2000,
30
+ class_labels: Optional[torch.Tensor] = None,
31
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
32
+ output_type: Optional[str] = "pil",
33
+ return_dict: bool = True,
34
+ **kwargs,
35
+ ) -> Union[ImagePipelineOutput, Tuple]:
36
+ r"""
37
+ The call function to the pipeline for generation.
38
+
39
+ Args:
40
+ batch_size (`int`, *optional*, defaults to 1):
41
+ The number of images to generate.
42
+ generator (`torch.Generator`, `optional`):
43
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
44
+ generation deterministic.
45
+ output_type (`str`, `optional`, defaults to `"pil"`):
46
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
47
+ return_dict (`bool`, *optional*, defaults to `True`):
48
+ Whether or not to return a [`ImagePipelineOutput`] instead of a plain tuple.
49
+
50
+ Returns:
51
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
52
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
53
+ returned where the first element is a list with the generated images.
54
+ """
55
+ img_size = self.unet.config.sample_size
56
+ shape = (batch_size, 3, img_size, img_size)
57
+
58
+ model = self.unet
59
+
60
+ sample = randn_tensor(shape, generator=generator, device=self.device) * self.scheduler.init_noise_sigma
61
+ sample = sample.to(self.device)
62
+
63
+ self.scheduler.set_timesteps(num_inference_steps)
64
+ self.scheduler.set_sigmas(num_inference_steps)
65
+
66
+ for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
67
+ sigma_t = self.scheduler.sigmas[i] * torch.ones(shape[0], device=self.device)
68
+
69
+ # correction step
70
+ for _ in range(self.scheduler.config.correct_steps):
71
+ model_output = self.unet(sample, sigma_t, class_labels).sample
72
+ sample = self.scheduler.step_correct(model_output, sample, generator=generator).prev_sample
73
+
74
+ # prediction step
75
+ model_output = model(sample, sigma_t, class_labels).sample
76
+ output = self.scheduler.step_pred(model_output, t, sample, generator=generator)
77
+
78
+ sample, sample_mean = output.prev_sample, output.prev_sample_mean
79
+
80
+ sample = sample_mean.clamp(0, 1)
81
+ sample = sample.cpu().permute(0, 2, 3, 1).numpy()
82
+ if output_type == "pil":
83
+ sample = self.numpy_to_pil(sample)
84
+
85
+ if not return_dict:
86
+ return (sample,)
87
+ return ImagePipelineOutput(images=sample)